post_href
stringlengths 57
213
| python_solutions
stringlengths 71
22.3k
| slug
stringlengths 3
77
| post_title
stringlengths 1
100
| user
stringlengths 3
29
| upvotes
int64 -20
1.2k
| views
int64 0
60.9k
| problem_title
stringlengths 3
77
| number
int64 1
2.48k
| acceptance
float64 0.14
0.91
| difficulty
stringclasses 3
values | __index_level_0__
int64 0
34k
|
---|---|---|---|---|---|---|---|---|---|---|---|
https://leetcode.com/problems/course-schedule-ii/discuss/2795475/Python-Solution-Easy-to-Understand | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
graph = [[] for _ in range(numCourses)]
indegree = [0 for _ in range(numCourses)]
for course in prerequisites:
graph[course[0]].append(course[1])
indegree[course[1]] += 1
queue = []
for node in range(numCourses):
if indegree[node] ==0 :
queue.append(node)
course_order = []
while queue:
curr_node = queue.pop(0)
for node in graph[curr_node]:
indegree[node] -= 1
if indegree[node] == 0:
queue.append(node)
course_order.append(curr_node)
if len(course_order) == numCourses:
return course_order[::-1]
return [] | course-schedule-ii | Python Solution Easy to Understand | manishchhipa | 0 | 1 | course schedule ii | 210 | 0.481 | Medium | 3,600 |
https://leetcode.com/problems/course-schedule-ii/discuss/2794927/Simple-Depth-First-Search-and-Topological-Sort | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
seen = collections.defaultdict(bool)
pos = collections.defaultdict(int)
graph = collections.defaultdict(list)
def dfs(course) -> bool:
if seen[course] == 2:
return True
minPos = 0
seen[course] = 1
for nxt in graph[course]:
if seen[nxt] == 1:
# cycle
return False
elif seen[nxt] == 0:
check = dfs(nxt)
if not check:
return False
minPos = min(minPos, pos[nxt])
pos[course] = minPos - 1
seen[course] = 2
return True
for a, b in prerequisites:
graph[b].append(a)
for course in range(numCourses):
if seen[course] == 0:
check = dfs(course)
if not check:
return []
courses = list(range(numCourses))
return sorted(courses, key=lambda course: pos[course]) | course-schedule-ii | Simple Depth First Search and Topological Sort | ananth360 | 0 | 2 | course schedule ii | 210 | 0.481 | Medium | 3,601 |
https://leetcode.com/problems/course-schedule-ii/discuss/2763691/Simple-Beginner-Friendly-Approach-or-DFS-or-O(V%2BE) | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
self.graph = defaultdict(list)
for pre in prerequisites:
self.graph[pre[0]].append(pre[1])
self.visited = set()
self.path = set()
self.order = []
for course in range(numCourses):
if course not in self.visited:
self.visited.add(course)
if not self.dfs(course):
return []
return self.order
def dfs(self, vertex):
self.path.add(vertex)
for neighbour in self.graph[vertex]:
if neighbour in self.path:
return False #early exit
if neighbour not in self.visited:
self.visited.add(neighbour)
if not self.dfs(neighbour):
return False
self.path.remove(vertex) #remove from path and add to order
self.order.append(vertex)
return True | course-schedule-ii | Simple Beginner Friendly Approach | DFS | O(V+E) | sonnylaskar | 0 | 6 | course schedule ii | 210 | 0.481 | Medium | 3,602 |
https://leetcode.com/problems/course-schedule-ii/discuss/2760808/Using-khan's-algorithm-BFS-striver-solution | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
if numCourses==1:
return [0]
dic=defaultdict(list)
for a,b in prerequisites:
dic[a]+=[b]
vis=[0]*numCourses
for i in range(numCourses):
if i in dic:
for node in dic[i]:
vis[node]+=1
q=[]
ans=[]
for i in range(numCourses):
if vis[i]==0:
q.append(i)
while q:
node=q.pop(0)
ans.append(node)
if node in dic:
for it in dic[node]:
vis[it]-=1
if vis[it]==0:
q.append(it)
if vis[it]<0:
return []
if len(ans)==numCourses:
return ans[::-1] | course-schedule-ii | Using khan's algorithm, BFS, striver solution | aryan3012 | 0 | 4 | course schedule ii | 210 | 0.481 | Medium | 3,603 |
https://leetcode.com/problems/course-schedule-ii/discuss/2741463/simple-pythonor-DFS | class Solution:
def traverse(self, now_point):
if now_point in self.onpath:
self.circle = True
return
if now_point in self.visited or self.circle:
return
self.onpath.append(now_point)
self.visited.append(now_point)
for j in self.graph[now_point]:
self.traverse(j)
self.postorder.append(now_point)
self.onpath.pop()
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
self.graph = [[]for _ in range(numCourses)]
for ask in prerequisites:
a = ask[0]
b = ask[1]
self.graph[b].append(a)
self.visited = []
self.onpath = []
self.postorder = []
self.circle = False
for i in range(numCourses):
self.traverse(i)
if self.circle:
return []
return self.postorder[::-1] | course-schedule-ii | simple python| DFS | lucy_sea | 0 | 2 | course schedule ii | 210 | 0.481 | Medium | 3,604 |
https://leetcode.com/problems/course-schedule-ii/discuss/2716054/Python3-solution-with-detailed-explanation-O(V%2BE)-both-time-and-space-complexity | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
# init the nodes. for each node, first element
# is the state of DFS. 0 means not discovered yet,
# 1 means discovered, 2 means finished. node's
# second element is the adjancent neighbors that
# it connects to.
undiscovered, discovered, finished = 0, 1, 2
nodes = [{"state": undiscovered, "neighbors": []} for i in range(numCourses)]
for cur, pre in prerequisites:
nodes[cur]["neighbors"].append(pre)
res = []
# do a DFS. Graph will have a loop iff we find a node that's
# discovered but not yet finished. The key idea is that if
# we found a loop, then no solution cuz you have a prerequisites
# loop. If loop doesn't exist, then we push the course in DFS
# order. If you need some more info on DFS and DAG,
# introduction to algorithms by THC is a really good book.
def DFS(curNodeIndex):
curNode = nodes[curNodeIndex]
if curNode["state"]: return curNode["state"] == finished
curNode["state"] = discovered
for i in curNode["neighbors"]:
if not DFS(i): return False
curNode["state"] = finished
res.append(curNodeIndex)
return True
for i in range(numCourses):
if not DFS(i): return []
return res | course-schedule-ii | Python3 solution with detailed explanation, O(V+E) both time and space complexity | tinmanSimon | 0 | 9 | course schedule ii | 210 | 0.481 | Medium | 3,605 |
https://leetcode.com/problems/course-schedule-ii/discuss/2713174/python3-simple-dfs-iterative-solution | class Solution:
def findOrder(self, numCourses: int, pre: List[List[int]]) -> List[int]:
graph={c:[] for c in range(numCourses)}
for i in pre:
graph[i[1]].append(i[0])
cycle , vis = set(), set()
output = deque([])
for e in graph:
if e not in vis:
stk=[e]
while stk:
child=False
temp=stk[-1]
cycle.add(temp)
for nb in graph[stk[-1]]:
if nb in cycle:
return []
if nb not in vis:
if not child:
child=True
stk.append(nb)
if not child:
stk.pop()
cycle.remove(temp)
if temp not in vis:
output.appendleft(temp)
vis.add(temp)
return output | course-schedule-ii | python3 simple dfs iterative solution | benon | 0 | 9 | course schedule ii | 210 | 0.481 | Medium | 3,606 |
https://leetcode.com/problems/course-schedule-ii/discuss/2710912/PYTHON-SOLUTION | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
indegree=[0]*(numCourses)
graph=defaultdict(list)
res=[]
for courses in prerequisites:
graph[courses[1]].append(courses[0])
indegree[courses[0]] += 1
queue=deque()
for v in range(numCourses):
if indegree[v]==0:
queue.append(v)
while queue:
u=queue.popleft()
res.append(u)
for v in graph[u]:
indegree[v]-=1
if indegree[v]==0:
queue.append(v)
if len(res)==numCourses:
return res
return [] | course-schedule-ii | PYTHON SOLUTION | shashank_2000 | 0 | 16 | course schedule ii | 210 | 0.481 | Medium | 3,607 |
https://leetcode.com/problems/course-schedule-ii/discuss/2695167/python3-95-topoligical-sort | class Solution:
def findOrder(self, N: int, prerequisites: List[List[int]]) -> List[int]:
if not prerequisites:
return list(range(N))
prereqs_course, prereqs_amount = defaultdict(list), defaultdict(int)
for _, (c, pr) in enumerate(prerequisites):
prereqs_amount[c] += 1
prereqs_course[pr].append(c)
ans = []
que = deque()
que.extend(set(range(N)) - set(prereqs_amount))
while que:
pr = que.popleft()
ans.append(pr)
for c in prereqs_course[pr]:
prereqs_amount[c] -= 1
if prereqs_amount[c] < 1:
que.append(c)
if len(ans) == N:
return ans
return [] | course-schedule-ii | python3 95% topoligical sort | 1ncu804u | 0 | 7 | course schedule ii | 210 | 0.481 | Medium | 3,608 |
https://leetcode.com/problems/course-schedule-ii/discuss/2623419/DFS-BFS-AND-KHAN'S-ALGORITHM | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
# BFS / KAHN'S ALGORITHM
preMap = {i: [] for i in range(numCourses)}
indegree = [0 for _ in range(numCourses)]
"""
numCourses = 4
prerequisites = [[1,0],[2,0],[3,1],[3,2]]
"""
for course, pre in prerequisites:
indegree[course] += 1
preMap[pre].append(course)
queue = collections.deque([course for course in preMap if indegree[course] == 0])
results = []
count = 0
while queue:
course = queue.popleft()
results.append(course)
for pre in preMap[course]:
indegree[pre] -= 1
if indegree[pre] == 0:
queue.append(pre)
count += 1
return results if count == numCourses else []
# DFS APPROACH
checkCycle = [0 for _ in range(numCourses)]
visit, cycle, results = set(), set(), []
def dfs(course):
if checkCycle[course] == -1:
return False
if checkCycle[course] == 1:
return True
checkCycle[course] = -1
for pre in preMap[course]:
if not dfs(pre): return False
checkCycle[course] = 1
results.append(course)
return True
for course in range(numCourses):
if not dfs(course): return []
return results | course-schedule-ii | DFS / BFS AND KHAN'S ALGORITHM | leomensah | 0 | 26 | course schedule ii | 210 | 0.481 | Medium | 3,609 |
https://leetcode.com/problems/course-schedule-ii/discuss/2597705/Python-Easy-DFS | class Solution:
def findOrder(self, n: int, pre: List[List[int]]) -> List[int]:
res = []
vis = [0]*n
adj = [[] for _ in range(n)]
for p in pre:
adj[p[0]].append(p[1])
for u in range(n):
if vis[u] == 0:
if self.dfs(u, adj, vis, res):
return []
return res
def dfs(self, u, adj, vis, res):
vis[u] = 1
for v in adj[u]:
if vis[v] == 0:
if self.dfs(v, adj, vis, res) == True:
return True
elif vis[v] == 1:
return True
vis[u] = 2
res.append(u)
return False | course-schedule-ii | Python Easy DFS | lokeshsenthilkumar | 0 | 52 | course schedule ii | 210 | 0.481 | Medium | 3,610 |
https://leetcode.com/problems/course-schedule-ii/discuss/2537428/Course-Schedule-II%3A-Python3-Top-Sort-Kahn-algo | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
def top_sort(DAG: dict): # Time Complexity O(V+E), Space Complexity O(V+E)
# Topological sort: Kahn's algorithm
# step 1: create the incoming_degree dictionary {X: #} to indicate how many incoming edges a node X has
incoming_degree = { node: 0 for node in DAG }
for node in DAG:
for this_after_node in DAG[node]:
incoming_degree[this_after_node] += 1
# step 2: create a queue for nodes without any incoming edges
queue_of_before_nodes = []
for node in incoming_degree:
if incoming_degree[node] == 0:
queue_of_before_nodes.append(node)
# step 3: remove the adjacency in the "after nodes" for each "before node"
# when the incoming degree of the "after node" becomes 0, it will become another "before node"
# do this repeatedly until there is no more "before nodes" in the queue
top_order = []
while queue_of_before_nodes:
this_before_node = queue_of_before_nodes.pop(0)
top_order.append(this_before_node)
for this_after_node in DAG[this_before_node]:
incoming_degree[this_after_node] -= 1
if incoming_degree[this_after_node] == 0:
queue_of_before_nodes.append(this_after_node)
# if the graph contains a cycle, it won't be the same as n
if len(top_order) != len(DAG):
return []
return top_order
# step 1: create the DAG (directed acyclic graph) for the adjacency rule in the data
# for example, a dictionary {X: Y} to indicate that X (a before node) must be before Y (an after node)
DAG = { course: set() for course in range(numCourses) }
for dest, src in prerequisites:
DAG[src].add(dest)
# step 2: perform the topological sort
res = top_sort(DAG)
return res | course-schedule-ii | Course Schedule II: Python3 Top Sort Kahn algo | NinjaBlack | 0 | 11 | course schedule ii | 210 | 0.481 | Medium | 3,611 |
https://leetcode.com/problems/course-schedule-ii/discuss/2506001/Python-Solution-or-using-DFS-orTopological-sort | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
prereq = {c : [] for c in range(numCourses)}
for crs, pre in prerequisites:
prereq[crs].append(pre)
visit, cycle = set(), set()
output= []
def dfs(crs):
if crs in cycle:
return False
if crs in visit:
return True
cycle.add(crs)
for pre in prereq[crs]:
if dfs(pre) == False:
return False
cycle.remove(crs)
visit.add(crs)
output.append(crs)
return True
for c in range(numCourses):
if dfs(c) == False:
return []
return output | course-schedule-ii | Python Solution | using DFS |Topological sort | nikhitamore | 0 | 71 | course schedule ii | 210 | 0.481 | Medium | 3,612 |
https://leetcode.com/problems/course-schedule-ii/discuss/2190467/Python3-Topological-Sort-Easy-to-understand | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
preMap = { _ : [] for _ in range(numCourses)}
for cur, pre in prerequisites:
preMap[cur].append(pre)
path = set()
# path to remember all the node on the path we have visited
res = []
def dfs(n):
if n in res:
# node has already been added, we don't need to search again
return True
if n in path:
# circle found
return False
path.add(n)
for pre in preMap[n]:
if not dfs(pre):
return False
# start a new path
path.remove(n)
# means there is no prerequisite for the current node, we have reached the bottom, so we can safely take this course first
res.append(n)
return True
for n in range(numCourses):
if not dfs(n):
# circle found, return empty list
return []
return res
``` | course-schedule-ii | Python3 Topological Sort Easy to understand | jethu | 0 | 17 | course schedule ii | 210 | 0.481 | Medium | 3,613 |
https://leetcode.com/problems/course-schedule-ii/discuss/2184681/Topological-Sort-oror-Detecting-Cycle-in-a-Directed-Graph-oror-DFS | class Solution:
def topologicalSort(self, node, graph, visited, stack):
visited[node] = True
for neighbour in graph[node]:
if visited[neighbour] == False:
self.topologicalSort(neighbour, graph, visited, stack)
stack.append(node)
def dfs(self, i, graph, color):
color[i] = "GRAY"
for neighbour in graph[i]:
if color[neighbour] == "GRAY":
return True
elif color[neighbour] == "WHITE" and self.dfs(neighbour, graph, color):
return True
color[i] = "BLACK"
return False
def detectCycle(self, V, graph):
color = ["WHITE"]*V
for i in range(V):
if color[i] == "WHITE":
if self.dfs(i, graph, color):
return True
return False
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
graph = {i:[] for i in range(numCourses)}
for course, pre in prerequisites:
graph[course].append(pre)
# print(self.detectCycle(numCourses, graph))
if self.detectCycle(numCourses, graph):
return []
else:
stack = []
visited = [False]*(numCourses)
for i in range(numCourses):
if visited[i] == False:
self.topologicalSort(i, graph, visited, stack)
return stack | course-schedule-ii | Topological Sort || Detecting Cycle in a Directed Graph || DFS | Vaibhav7860 | 0 | 42 | course schedule ii | 210 | 0.481 | Medium | 3,614 |
https://leetcode.com/problems/course-schedule-ii/discuss/2153529/210.-Python-solution-with-my-comments | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
graph = [[] for i in range(numCourses)]
visited = [0]*numCourses
res = []
for pair in prerequisites:
x, y = pair
graph[x].append(y)
for i in range(numCourses):
if not self.dfs(graph, visited, i, res):
return []
return res
def dfs(self, graph, visited, i, res):
if visited[i]==-1:
return False
if visited[i]==1:
return True
visited[i]=-1
for j in graph[i]:
if not self.dfs(graph, visited, j, res):
return False
visited[i]=1
res.append(i) #acts like we traverse each unvisited node, then form a non-cycle path
return True | course-schedule-ii | 210. Python solution with my comments | JunyiLin | 0 | 34 | course schedule ii | 210 | 0.481 | Medium | 3,615 |
https://leetcode.com/problems/course-schedule-ii/discuss/2118581/Python3-Solution-88 | class Solution:
def __init__(self):
self.graph = {}
self.v = 0
def isCyclicUtil(self, v, visited, recStack, progressStack):
visited[v] = True
recStack[v] = True
if v not in self.graph:
recStack[v]=False
progressStack.append(v)
return False
for neighbour in self.graph[v]:
if visited[neighbour] == False:
if self.isCyclicUtil(neighbour, visited, recStack, progressStack) == True:
progressStack.clear()
return True
elif recStack[neighbour] == True:
return True
recStack[v] = False
progressStack.append(v)
return False
def isCyclic(self):
visited = [False] * (self.v)
recStack = [False] * (self.v)
progress = []
for node in range(self.v):
if visited[node] == False:
if self.isCyclicUtil(node,visited,recStack, progress) == True:
return progress
return progress
def findOrder(self, numCourses: int, prerequisites: list[list[int]]) -> list[int]:
graph={}
for a,b in prerequisites:
if a in graph:
graph[a].append(b)
else:
graph[a]=[b]
self.graph=graph
self.v=numCourses
return self.isCyclic() | course-schedule-ii | Python3 Solution 88% | ComicCoder023 | 0 | 52 | course schedule ii | 210 | 0.481 | Medium | 3,616 |
https://leetcode.com/problems/course-schedule-ii/discuss/2117795/simple-iterative-dfs | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
courses = [[] for _ in range(numCourses)]
for course, pre in prerequisites:
courses[course].append(pre)
visited = {}
order = []
for i in range(numCourses):
if visited.get(i, 0) == 0:
stack = [i]
while(stack):
node = stack[-1]
if visited.get(node, 0)==-1:
stack.pop()
order.append(node)
visited[node] = 1
continue
if visited.get(node, 0)==1:
stack.pop()
continue
visited[node] = -1
for c in courses[node]:
if visited.get(c, 0)==-1:
return []
if visited.get(c, 0)==0:
stack.append(c)
return order | course-schedule-ii | simple iterative dfs | gabhinav001 | 0 | 62 | course schedule ii | 210 | 0.481 | Medium | 3,617 |
https://leetcode.com/problems/course-schedule-ii/discuss/2093015/Python3%3A-Simple-DFS-%2B-Backtracking-Solution-using-defaultdict-and-Sets-(no-Topological-Sort) | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
"""
DFS + backtracking
"""
def dfs(course):
visited.add(course)
path.add(course)
# backtracking
for pre in graph[course]:
if pre in path:
return False
if pre not in visited and not dfs(pre):
return False
path.remove(course)
res.append(course)
return True
from collections import defaultdict
graph = defaultdict(list, {k:[] for k in range(numCourses)})
for course, pre in prerequisites:
if course == pre:
return []
graph[course].append(pre)
res = []
visited = set()
path = set()
for course in list(graph):
if course not in visited and not dfs(course):
return []
return res | course-schedule-ii | Python3: Simple DFS + Backtracking Solution using defaultdict and Sets (no Topological Sort) | yunglinchang | 0 | 48 | course schedule ii | 210 | 0.481 | Medium | 3,618 |
https://leetcode.com/problems/course-schedule-ii/discuss/2068732/Python-or-Topological-Sorting-or-O(n)-Time-O(n)-space | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
graph = defaultdict(list)
for a, b in prerequisites:
graph[b].append(a)
onPath = [False for _ in range(numCourses)]
visited = [False for _ in range(numCourses)]
hasCycle = False
courses = []
def traverse(node):
nonlocal hasCycle
if onPath[node]:
hasCycle = True
return
if visited[node] or hasCycle:
return
onPath[node] = True
visited[node] = True
# print("pre", node) # similar to root, left, right, so orders not guaranteed
for n in graph[node]:
traverse(n)
# print("post", node) # similar to right, left, root, so order is reversed
courses.append(node)
onPath[node] = False
for i in range(numCourses):
traverse(i)
if hasCycle:
return []
return courses[::-1] | course-schedule-ii | Python | Topological Sorting | O(n) Time, O(n) space | Kiyomi_ | 0 | 44 | course schedule ii | 210 | 0.481 | Medium | 3,619 |
https://leetcode.com/problems/course-schedule-ii/discuss/2041842/course-schedule-oror-python3-oror-topological-oror-DFS | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
# Nothing just modification of course-schedule-1
graph = [[] for _ in range(numCourses)]
visit = [0 for _ in range(numCourses)]
stack=[]
for x, y in prerequisites:
graph[x].append(y)
def dfs(i,stack):
# if cyclee found than smply return empty set
if visit[i] == -1:
return []
if visit[i] == 1:
return True
visit[i] = -1
# if we encounter state to be -1 in just adajacent of any node directly return empty set
# as it formed cycle there
for j in graph[i]:
if not dfs(j,stack):
return []
# else we marked node as visited and keeps on appending till it depend on others
visit[i] = 1
stack.append(i)
return True
for i in range(numCourses):
if not dfs(i,stack):
return []
# simply return stack which represent order of visiting node , if it doesn't contains any cycle.
return stack | course-schedule-ii | course schedule || python3 || topological || DFS | Aniket_liar07 | 0 | 30 | course schedule ii | 210 | 0.481 | Medium | 3,620 |
https://leetcode.com/problems/course-schedule-ii/discuss/2036907/Python3-DFS-solution-explained | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
visited = [None] * numCourses
onPath = [None] * numCourses
adjList = [[] for i in range(numCourses)]
res = []
for i in range(numCourses):
adjList.append([])
for pre in prerequisites:
adjList[pre[1]].append(pre[0])
def traverse(i):
if onPath[i]:
return False
if visited[i]:
return True
visited[i] = True
onPath[i] = True
for neighbor in adjList[i]:
if False == traverse(neighbor):
return False
onPath[i] = False
res.append(i)
for i in range(numCourses):
if False == traverse(i):
return []
res.reverse()
return res | course-schedule-ii | Python3 DFS solution explained | TongHeartYes | 0 | 33 | course schedule ii | 210 | 0.481 | Medium | 3,621 |
https://leetcode.com/problems/course-schedule-ii/discuss/2009702/Clean-Python-3-Solution-(Topological-Sorting-%2B-BFS) | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
in_degrees = [0] * numCourses
for v, _ in prerequisites:
in_degrees[v] += 1
q = []
for i in range(len(in_degrees)):
if in_degrees[i] == 0:
q.append(i)
res = []
while q:
u0 = q.pop(0)
res.append(u0)
for v, u in prerequisites:
if u == u0:
in_degrees[v] -= 1
if in_degrees[v] == 0:
q.append(v)
return res if len(res) == numCourses else [] | course-schedule-ii | Clean Python 3 Solution (Topological Sorting + BFS) | Hongbo-Miao | 0 | 83 | course schedule ii | 210 | 0.481 | Medium | 3,622 |
https://leetcode.com/problems/course-schedule-ii/discuss/1970320/Python3-Topological-Sort-Two-Solutions-with-BFS-and-DFS | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
graph = [[] for x in range(numCourses)]
for dest, src in prerequisites:
graph[src].append(dest)
index = [numCourses - 1]
result = [0] * numCourses
seen = [False] * numCourses
for cur in range(numCourses):
cycle = [False] * numCourses
if seen[cur] == False:
hasCycle = self.dfs(cur, graph, seen, cycle, result, index)
if hasCycle:
return []
return result
def dfs(self, cur, graph, seen, cycle, result, index) -> bool:
seen[cur] = True
cycle[cur] = True
for neigh in graph[cur]:
if seen[neigh] == False:
hasCycle = self.dfs(neigh, graph, seen, cycle, result, index)
if hasCycle:
return True
elif cycle[neigh]:
return True
result[index[0]] = cur
index[0] -= 1
cycle[cur] = False
return False | course-schedule-ii | Python3 Topological Sort Two Solutions with BFS & DFS | shtanriverdi | 0 | 50 | course schedule ii | 210 | 0.481 | Medium | 3,623 |
https://leetcode.com/problems/course-schedule-ii/discuss/1914146/Python-DFS-oror-Topological-Sort-oror-Simple-and-Easy | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
preMap = collections.defaultdict(list)
for crs, pre in prerequisites:
preMap[crs].append(pre)
output = []
visit, cycle = set(), set()
def dfs(crs):
if crs in cycle:
return False
if crs in visit:
return True
cycle.add(crs)
for pre in preMap[crs]:
if dfs(pre) == False:
return False
cycle.remove(crs)
visit.add(crs)
output.append(crs)
return True
for i in range(numCourses):
if dfs(i) == False:
return []
return output | course-schedule-ii | Python - DFS || Topological Sort || Simple and Easy | dayaniravi123 | 0 | 70 | course schedule ii | 210 | 0.481 | Medium | 3,624 |
https://leetcode.com/problems/course-schedule-ii/discuss/1906705/python-topological-sort-solution.-Easy-to-understand | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
incomingNodesCount = [0 for i in range(numCourses)]
graph = {i:[] for i in range(numCourses)}
# create a graph from the given prerequisites
for prereq in prerequisites:
# bi : [ai]
ai = prereq[0]
bi = prereq[1]
if bi not in graph:
graph[bi]=[ai]
else:
graph[bi].append(ai)
incomingNodesCount[ai]+=1
# now get all the nodes with no incoming
queue = []
i = 0
while i < len(incomingNodesCount):
if incomingNodesCount[i] == 0:
queue.append(i)
i+=1
path = []
while len(queue):
first = queue.pop(0)
path.append(first)
for nei in graph[first]:
incomingNodesCount[nei] -= 1
if incomingNodesCount[nei] == 0:
queue.append(nei)
if set(incomingNodesCount) != set([0]):
# some courses could not be taken (circular dependency)
return []
return path | course-schedule-ii | python topological sort solution. Easy to understand | karanbhandari | 0 | 96 | course schedule ii | 210 | 0.481 | Medium | 3,625 |
https://leetcode.com/problems/course-schedule-ii/discuss/1890364/Python-Topological-Sorting | class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
ans = []
d = {}
indegree = {}
for i in range(numCourses):
d[i] = []
indegree[i] = 0
for i in prerequisites:
d[i[0]].append(i[1])
indegree[i[1]] += 1
queue = []
for i in indegree:
if indegree[i] == 0:
queue.append(i)
while queue:
curr = queue.pop(0)
ans.insert(0,curr)
for i in d[curr]:
if indegree[i] > 0:
indegree[i]-= 1
if indegree[i] == 0:
queue.append(i)
for i in indegree:
if indegree[i] != 0:
return []
return(ans) | course-schedule-ii | Python Topological Sorting | DietCoke777 | 0 | 45 | course schedule ii | 210 | 0.481 | Medium | 3,626 |
https://leetcode.com/problems/word-search-ii/discuss/2351408/python3-solution-oror-99-more-faster-oror-39-ms | class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
m = len(board)
n = len(board[0])
res = []
d = [[0, 1], [0, -1], [1, 0], [-1, 0]]
ref = set()
for i in range(m):
for j in range(n-1):
ref.add(board[i][j] + board[i][j+1])
for j in range(n):
for i in range(m-1):
ref.add(board[i][j] + board[i+1][j])
for word in words:
f = True
for i in range(len(word)-1):
if word[i:i+2] not in ref and word[i+1] + word[i] not in ref:
f = False
break
if not f:
continue
if self.findWord(word, m, n, board, d):
res.append(word)
return res
def findWord(self, word, m, n, board, d) -> bool:
if word[:4] == word[0] * 4:
word = ''.join([c for c in reversed(word)])
starts = []
stack = []
visited = set()
for i in range(m):
for j in range(n):
if board[i][j] == word[0]:
if len(word) == 1:
return True
starts.append((i, j))
for start in starts:
stack.append(start)
visited.add((start, ))
l = 1
while stack != [] and l < len(word):
x, y = stack[-1]
for dxy in d:
nx, ny = x + dxy[0], y + dxy[1]
if 0 <= nx < m and 0 <= ny < n:
if board[nx][ny] == word[l]:
if (nx, ny) not in stack and tuple(stack) + ((nx, ny),) not in visited:
stack.append((nx, ny))
visited.add(tuple(stack))
l += 1
if l == len(word):
return True
break
else:
stack.pop()
l -= 1
else:
return False | word-search-ii | python3 solution || 99% more faster || 39 ms | vimla_kushwaha | 3 | 301 | word search ii | 212 | 0.368 | Hard | 3,627 |
https://leetcode.com/problems/word-search-ii/discuss/1061088/Python-AC-Backtracking-in-three-steps%3A-Terminate-Success-Backtrack | class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
@functools.lru_cache(None)
def backtrack(i, j, path):
# 1) terminate
if i not in range(0, len(board)): return
if j not in range(0, len(board[0])): return
if board[i][j] == "#": return
# 2) success
path += board[i][j]
if path in self.words:
self.result.add(path)
# 3) backtrack
c = board[i][j]
board[i][j] = "#"
for x, y in [(i+1, j), (i-1, j), (i, j-1), (i, j+1)]:
backtrack(x, y, path)
board[i][j] = c
self.words = set(words)
self.result = set()
for i in range(len(board)):
for j in range(len(board[0])):
backtrack(i, j, "")
return self.result | word-search-ii | Python AC Backtracking in three steps: Terminate, Success, Backtrack | dev-josh | 3 | 342 | word search ii | 212 | 0.368 | Hard | 3,628 |
https://leetcode.com/problems/word-search-ii/discuss/2779919/or-Python-or-Trie-Easy-Solution | class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
res = []
Trie = lambda : defaultdict(Trie)
root = Trie()
def add(s):
cur = root
for c in s: cur = cur[c]
cur['$'] = s
for word in words: add(word)
m, n = len(board), len(board[0])
def dfs(i, j, root):
ch = board[i][j]
cur = root.get(ch)
if not cur: return
if '$' in cur:
res.append(cur['$'])
del cur['$']
board[i][j] = '#'
if i<m-1: dfs(i+1, j, cur)
if i>0: dfs(i-1, j, cur)
if j<n-1: dfs(i, j+1, cur)
if j>0: dfs(i, j-1, cur)
board[i][j] = ch
for i in range(m):
for j in range(n):
dfs(i, j, root)
return res | word-search-ii | ✔️ | Python | Trie Easy Solution | code_alone | 2 | 289 | word search ii | 212 | 0.368 | Hard | 3,629 |
https://leetcode.com/problems/word-search-ii/discuss/2781923/Python-or-Trie-with-node-deletion | class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
rows, cols = len(board), len(board[0])
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
seen = []
res = set()
trie = {}
for word in words:
current = trie
for c in word:
if c not in current:
current[c] = {}
current = current[c]
current['#'] = word #to denote end of word
def dfs(r, c, seen, node):
if '#' in node:
res.add(node['#'])
del node['#']
for dr, dc in directions:
nr, nc = r + dr, c + dc
if nr in range(rows) and nc in range(cols) and (nr, nc) not in seen and board[nr][nc] in node:
seen.append((nr, nc))
dfs(nr, nc, seen, node[board[nr][nc]])
if len(node[board[nr][nc]]) == 0:
del node[board[nr][nc]]
seen.pop()
for r in range(rows):
for c in range(cols):
if board[r][c] in trie:
seen.append((r, c))
dfs(r, c, seen, trie[board[r][c]])
seen.pop()
return list(res) | word-search-ii | Python | Trie with node deletion | KevinJM17 | 1 | 38 | word search ii | 212 | 0.368 | Hard | 3,630 |
https://leetcode.com/problems/word-search-ii/discuss/2794297/DP-Approach-More-intuitive-than-Trie | class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
if not board:
return []
rtn = []
memo = {}
for word in words:
self.dp(board, word, memo)
if not (-1,-1) in memo[word]:
rtn.append(word)
validatedRtn = []
for w in rtn:
for k in memo[w]:
if self.dfs(board, k[0], k[1], w):
validatedRtn.append(w)
break
return validatedRtn
def dp(self, board, word, memo):
if word in memo:
return
leftOver = word[1:]
if leftOver != '':
self.dp(board, leftOver, memo)
if (-1, -1) in memo[leftOver]:
memo[word] = {(-1,-1): 1}
return
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == word[0]:
if leftOver == '' or (i,j+1) in memo[leftOver] or (i,j-1) in memo[leftOver] or (i+1,j) in memo[leftOver] or (i-1,j) in memo[leftOver]:
if word in memo:
memo[word][(i,j)] = 1
else:
memo[word] = {(i,j): 1}
if not word in memo:
memo[word] = {(-1,-1): 1}
def dfs(self, board, i, j, word):
if len(word) == 0: # all the characters are checked
return True
if i<0 or i>=len(board) or j<0 or j>=len(board[0]) or word[0]!=board[i][j]:
return False
tmp = board[i][j] # first character is found, check the remaining part
board[i][j] = "#" # avoid visit agian
# check whether can find "word" along one direction
res = self.dfs(board, i+1, j, word[1:]) or self.dfs(board, i-1, j, word[1:]) \
or self.dfs(board, i, j+1, word[1:]) or self.dfs(board, i, j-1, word[1:])
board[i][j] = tmp
return res | word-search-ii | DP Approach - More intuitive than Trie | nickpavini | 0 | 11 | word search ii | 212 | 0.368 | Hard | 3,631 |
https://leetcode.com/problems/word-search-ii/discuss/2788822/Python3-Faster-than-90-explained-using-dictionaries-and-NO-Tries | class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
prefix = {}
word2prefixes = {} #for pruning
for w in words:
word2prefixes[w] = set()
for i in range(1,len(w)+1):
p = w[0:i]
if p in prefix:
prefix[p]+=1
else:
prefix[p]=1
word2prefixes[w].add(p)
words = set(words)
found = set()
nrows,ncols = len(board),len(board[0])
visited = set()
def dfs(node,w):
visited.add(node)
x,y = node
if w in words:
found.add(w)
#remove all its prefixes to prevent duplicate searches in the board
words.remove(w)
for w_ in word2prefixes[w]:
prefix[w_]-=1
if prefix[w_]==0:
prefix.pop(w_)
word2prefixes.pop(w)
for nei in [(x+1,y),(x,y+1),(x-1,y),(x,y-1)]:
nx,ny = nei
if nei not in visited\
and nx>=0 and nx<nrows\
and ny>=0 and ny<ncols:
new_w = w + board[nx][ny]
if new_w in prefix:
dfs(nei,new_w)
visited.remove(node)
#start from only valid states
for i in range(nrows):
for j in range(ncols):
if board[i][j] in prefix:
dfs((i,j),board[i][j])
return list(found) | word-search-ii | Python3 Faster than 90% explained using dictionaries and NO Tries | user9611y | 0 | 11 | word search ii | 212 | 0.368 | Hard | 3,632 |
https://leetcode.com/problems/word-search-ii/discuss/2787688/Python-3-backtracking-%2B-Trie-friendly-to-beginner-no-fancy-syntax | class Solution:
def buildtrie(self, words):
trie = {}
head = trie
for word in words:
for letter in word:
if letter not in trie:
trie[letter] = {}
trie = trie[letter]
trie['$'] = {}
trie = head
return trie
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
trie = self.buildtrie(words)
res = set()
def inBounds(i, j, m, n):
return 0<=i<m and 0<=j<n
def backtracking(i, j, node, track, m, n, visited, board):
nonlocal res
nonlocal trie
if '$' in node:
res.add(''.join(track))
if len(node.keys())==1:
return
directions = [[+1,0], [-1,0], [0,+1], [0,-1]]
for direction in directions:
x = i+direction[0]; y = j+direction[1]
if inBounds(x,y,m,n) and visited[x][y] == 0:
char = board[x][y]
if char in node:
visited[x][y] = 1
record = node
node = node[char]
track.append(char)
backtracking(x, y, node, track, m, n, visited, board)
track.pop()
node = record
visited[x][y] = 0
m = len(board)
n = len(board[0])
visited = [0 for _ in range(n)]
visited = [list(visited) for _ in range(m)]
track = []
for i in range(m):
for j in range(n):
if board[i][j] in trie:
visited[i][j] = 1
node = trie[board[i][j]]
track.append(board[i][j])
backtracking(i, j, node, track, m, n, visited, board)
track.pop()
visited[i][j] = 0
return list(res) | word-search-ii | Python 3 backtracking + Trie, friendly to beginner, no fancy syntax | Arana | 0 | 8 | word search ii | 212 | 0.368 | Hard | 3,633 |
https://leetcode.com/problems/word-search-ii/discuss/2785159/Python-%2B-DFS-with-Trie-Lookup | class Solution:
def __init__(self):
self.res = []
self.m = 0
self.n = 0
self.board = [[]]
def add(self, s:str, root):
cur = root
for c in s: cur = cur[c]
cur['
```] = s
def dfs(self, i:int, j:int, root):
char = self.board[i][j]
word = root.get(char)
if not word:
return
if '
``` in word:
self.res.append(word['
```])
del word['
```]
self.board[i][j] = '#'
if i < self.m - 1: self.dfs(i+1, j , word)
if i> 0: self.dfs(i-1, j, word)
if j < self.n - 1: self.dfs(i, j+1, word)
if j > 0: self.dfs(i, j-1, word)
self.board[i][j] = char
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
Trie = lambda : defaultdict(Trie)
#get length of board(row and col)
self.m, self.n = len(board), len(board[0])
self.board = board
#create a lookup
root = Trie()
#add dictionary words to lookup
for word in words:
self.add(word, root)
for i in range(self.m):
for j in range(self.n):
self.dfs(i, j, root)
return self.res | word-search-ii | Python + DFS with Trie Lookup | ratva0717 | 0 | 21 | word search ii | 212 | 0.368 | Hard | 3,634 |
https://leetcode.com/problems/word-search-ii/discuss/2782513/Help-optimizing-NON-TRIE-based-set-inclusion-method.-Accepted-one-time-TLE-ever-after | class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
word_set = set(words)
prefix_set = set()
rows = len(board)
cols = len(board[0])
words_found = []
for word in words:
for i in range(len(word)):
prefix_set.add("".join(word[:i + 1]))
def traverse_grid(m: int, n: int, protoword: str, visited: set) -> List[str]:
found_words = []
if protoword in word_set:
found_words.append( protoword )
if protoword not in prefix_set:
return found_words
if m - 1 >= 0 and (m - 1, n) not in visited:
found_words += traverse_grid( m - 1, n, protoword + board[m - 1][n], visited.union({(m - 1, n)}) )
if m + 1 < rows and (m + 1, n) not in visited:
found_words += traverse_grid( m + 1, n, protoword + board[m + 1][n], visited.union({(m + 1, n)}) )
if n - 1 >= 0 and (m, n - 1) not in visited:
found_words += traverse_grid( m, n - 1, protoword + board[m][n - 1], visited.union({(m, n - 1)}) )
if n + 1 < cols and (m, n + 1) not in visited:
found_words += traverse_grid( m, n + 1, protoword + board[m][n + 1], visited.union({(m, n + 1)}) )
return found_words
for m in range(rows):
for n in range(cols):
words_found += traverse_grid(m, n, board[m][n], {(m,n)} )
return set(words_found) | word-search-ii | Help optimizing NON-TRIE based set-inclusion method. Accepted one time, TLE ever after | cswartzell | 0 | 15 | word search ii | 212 | 0.368 | Hard | 3,635 |
https://leetcode.com/problems/word-search-ii/discuss/2781477/python-solution | class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
Words = set()
m = len(board)
n = len(board[0])
map = [[0]*n for i in range(m)]
for i in words:
Words.add(i)
prefix = set()
for it in words:
for j in range(len(it) -1):
prefix.add(it[:j+1])
def dfs(row, col, strin):
parent = strin
strin += board[row][col]
if strin in prefix or strin in Words:
map[row][col] = 1
if strin in Words:
Words.remove(strin)
output.append(strin)
for i, j in adjacent(row,col):
dfs(i, j, strin)
map[row][col] = 0
return
def adjacent(row, col):
res = []
if row - 1 >= 0 and map[row - 1][col] == 0:
res.append([row - 1, col])
if row + 1 < m and map[row + 1][col] == 0:
res.append([row + 1, col])
if col + 1 < n and map[row][col + 1] == 0:
res.append([row, col + 1])
if col - 1 >= 0 and map[row][col - 1] == 0:
res.append([row, col - 1])
return res
output = []
for i in range(m):
for j in range(n):
map[i][j] = 1
dfs(i, j, '')
map[i][j] = 0
return output | word-search-ii | python solution | _saurav_pandey_ | 0 | 12 | word search ii | 212 | 0.368 | Hard | 3,636 |
https://leetcode.com/problems/word-search-ii/discuss/2781476/python-solution | class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
Words = set()
m = len(board)
n = len(board[0])
map = [[0]*n for i in range(m)]
for i in words:
Words.add(i)
prefix = set()
for it in words:
for j in range(len(it) -1):
prefix.add(it[:j+1])
def dfs(row, col, strin):
parent = strin
strin += board[row][col]
if strin in prefix or strin in Words:
map[row][col] = 1
if strin in Words:
Words.remove(strin)
output.append(strin)
for i, j in adjacent(row,col):
dfs(i, j, strin)
map[row][col] = 0
return
def adjacent(row, col):
res = []
if row - 1 >= 0 and map[row - 1][col] == 0:
res.append([row - 1, col])
if row + 1 < m and map[row + 1][col] == 0:
res.append([row + 1, col])
if col + 1 < n and map[row][col + 1] == 0:
res.append([row, col + 1])
if col - 1 >= 0 and map[row][col - 1] == 0:
res.append([row, col - 1])
return res
output = []
for i in range(m):
for j in range(n):
map[i][j] = 1
dfs(i, j, '')
map[i][j] = 0
return output | word-search-ii | python solution | _saurav_pandey_ | 0 | 8 | word search ii | 212 | 0.368 | Hard | 3,637 |
https://leetcode.com/problems/word-search-ii/discuss/2780396/Simple-Python-Trie-solution | class Solution:
def findWords(self, board: list[list[str]], words: list[str]) -> list[str]:
hasword = "true"
trie = {}
for word in words:
root = trie
for c in word:
root = root.setdefault(c, {})
root[hasword] = word
output = []
def findWord(i, j, root):
if hasword in root:
output.append(root[hasword])
del root[hasword]
save = board[i][j]
board[i][j] = '#'
for x, y in ((i-1,j), (i+1,j), (i,j-1), (i,j+1)):
if 0<=x<len(board) and 0<=y<len(board[0]) and board[x][y] in root:
findWord(x, y, root[board[x][y]])
board[i][j] = save
for i, row in enumerate(board):
for j, c in enumerate(row):
if c in trie:
findWord(i, j, trie[c])
return output | word-search-ii | Simple Python Trie solution | tinlittle | 0 | 30 | word search ii | 212 | 0.368 | Hard | 3,638 |
https://leetcode.com/problems/word-search-ii/discuss/2780368/Python3-Solution | class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
m = len(board)
n = len(board[0])
res = []
d = [[0, 1], [0, -1], [1, 0], [-1, 0]]
ref = set()
for i in range(m):
for j in range(n-1):
ref.add(board[i][j] + board[i][j+1])
for j in range(n):
for i in range(m-1):
ref.add(board[i][j] + board[i+1][j])
for word in words:
f = True
for i in range(len(word)-1):
if word[i:i+2] not in ref and word[i+1] + word[i] not in ref:
f = False
break
if not f:
continue
if self.findWord(word, m, n, board, d):
res.append(word)
return res
def findWord(self, word, m, n, board, d) -> bool:
if word[:4] == word[0] * 4:
word = ''.join([c for c in reversed(word)])
starts = []
stack = []
visited = set()
for i in range(m):
for j in range(n):
if board[i][j] == word[0]:
if len(word) == 1:
return True
starts.append((i, j))
for start in starts:
stack.append(start)
visited.add((start, ))
l = 1
while stack != [] and l < len(word):
x, y = stack[-1]
for dxy in d:
nx, ny = x + dxy[0], y + dxy[1]
if 0 <= nx < m and 0 <= ny < n:
if board[nx][ny] == word[l]:
if (nx, ny) not in stack and tuple(stack) + ((nx, ny),) not in visited:
stack.append((nx, ny))
visited.add(tuple(stack))
l += 1
if l == len(word):
return True
break
else:
stack.pop()
l -= 1
else:
return False | word-search-ii | Python3 Solution | Motaharozzaman1996 | 0 | 19 | word search ii | 212 | 0.368 | Hard | 3,639 |
https://leetcode.com/problems/word-search-ii/discuss/2780002/Python3-Trim-The-Trie-to-Beat-TLE | class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
"""LeetCode 212
What a journey! I have solved this problem before by myself, but the
same method back then no longer worked today, because the test cases
had been enlarged. This means the method must be even more optimized.
I was not able to figure out the optimized method, so I took a look at
various comments. It turns out the trick is at trimming the trie on the
words that have already been identified. This prevents duplication in
the result and avoids traversing the same path that has been done before.
The mechanism used for trimming is to keep a 'count' of the number of
times a node has been passed through during the creation of the trie.
Then, each time a word has been found, we go through the same path and
decrement the count. This way, when all the words that go through a node
have been found, that node's count would decrement to 0. We don't have
to traverse that node anymore.
With trimming, I was able to pass OC. 4136 ms, faster than 32.07%
But I am too lazy right now to figure out the time complexity.
"""
trie = lambda: defaultdict(trie)
board_count = Counter(chain(*board)) # count the frequency of each letter in board
root = trie()
# Preprocess the words. Eliminate all the ones that are impossible to be
# formed by the letters in board
for word in words:
for le, c in Counter(word).items():
if board_count[le] < c:
break
else:
node = root
node['count'] = node.get('count', 0) + 1
for le in word:
node = node[le]
# keep track of the number of words passing through this le
node['count'] = node.get('count', 0) + 1
node['*'] = word
def check(i: int, j: int, node) -> List[str]:
cur_le = board[i][j]
board[i][j] = '.'
res = []
if cur_le in node and node['count'] > 0:
next_node = node[cur_le]
if '*' in next_node:
w = next_node['*']
res.append(w)
# remove the word and decrement count for the current word
del next_node['*']
tmp = root
for le in w:
tmp = tmp[le]
tmp['count'] -= 1
for di, dj in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
ni, nj = i + di, j + dj
if 0 <= ni < M and 0 <= nj < N and board[ni][nj] != '.':
res.extend(check(ni, nj, next_node))
board[i][j] = cur_le
return res
M, N = len(board), len(board[0])
res = []
for i in range(M):
for j in range(N):
res.extend(check(i, j, root))
return res | word-search-ii | [Python3] Trim The Trie to Beat TLE | FanchenBao | 0 | 23 | word search ii | 212 | 0.368 | Hard | 3,640 |
https://leetcode.com/problems/word-search-ii/discuss/2779891/Python3-solution-with-trie-removal | class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
def _trie():
return defaultdict(_trie)
_trie.TERMINAL = None
_trie.PARENT = 'pa'
_trie.LETTER = 'le'
#None and 2-character string to avoid overwriting traversal keys
self.trie = _trie()
self.trie[_trie.PARENT] = None
#add words into trie
for word in words:
trie = self.trie
for letter in word:
if letter not in trie:
new_trie = trie[letter]
new_trie[_trie.PARENT] = trie
new_trie[_trie.LETTER] = letter
trie = trie[letter]
trie[_trie.TERMINAL] = word
M = len(board)
N = len(board[0])
res = []
seen = set()
def search(trie, y, x):
if y < 0 or x < 0 or y >= M or x >= N:
return
if (y, x) in seen:
return
seen.add((y, x))
if board[y][x] not in trie:
seen.remove((y, x))
return
trie = trie[board[y][x]]
if _trie.TERMINAL in trie: #word
res.append(trie[_trie.TERMINAL])
del trie[_trie.TERMINAL]
if len(trie) == 2: #only has 'PARENT' and 'LETTER', longest trie has been reached
while len(trie) == 2 and trie[_trie.PARENT]:
#since we only start removing when the longest trie has been reached
#we need a loop to also remove the shorter ones
parent_trie = trie[_trie.PARENT]
del parent_trie[trie[_trie.LETTER]]
del trie
trie = parent_trie
seen.remove((y, x))
return
search(trie, y-1, x)
search(trie, y+1, x)
search(trie, y, x-1)
search(trie, y, x+1)
seen.remove((y, x))
return
for y in range(M):
for x in range(N):
search(self.trie, y, x)
return res | word-search-ii | Python3 solution with trie removal | TheDucker1 | 0 | 19 | word search ii | 212 | 0.368 | Hard | 3,641 |
https://leetcode.com/problems/word-search-ii/discuss/2554597/Python-simple-trie-solution | class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
class Trie:
def __init__(self) -> None:
self.root={}
def insert(self,word):
cur=self.root
for w in word:
if w not in cur:
cur[w]={}
cur=cur[w]
cur["#"]=True
trie=Trie()
for word in words:
trie.insert(word)
m=len(board)
n=len(board[0])
res=[]
directions=[(0,1),(0,-1),(1,0),(-1,0)]
def dfs(i,j,board,m,n,cur_dict,cur_str):
cur_str+=board[i][j]
prev=cur_dict
temp=board[i][j]
cur_dict=cur_dict[temp]
board[i][j]="#"
if "#" in cur_dict:
res.append(cur_str)
# need to delete #
del cur_dict["#"]
if not cur_dict.keys():
board[i][j]=temp
del prev[temp]
return
for dir in directions:
x,y=i+dir[0],j+dir[1]
if x<0 or y<0 or x>=m or y>=n or board[x][y] not in cur_dict:
continue
dfs(x,y,board,m,n,cur_dict,cur_str)
board[i][j]=temp
for i in range(m):
for j in range(n):
if board[i][j] in trie.root:
dfs(i,j,board,m,n,trie.root,"")
return res | word-search-ii | Python simple trie solution | shatheesh | 0 | 150 | word search ii | 212 | 0.368 | Hard | 3,642 |
https://leetcode.com/problems/word-search-ii/discuss/2395867/python-trie-and-dfs-or-anyone-knows-why-this-is-slow | class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
trie = {}
for w in words:
cur = trie
for c in w:
if c not in cur:
cur[c] = {}
cur = cur[c]
cur[-1] = -1
ans = []
for i in range(len(board)):
for j in range(len(board[0])):
self.dfs(board, i,j,"",trie, ans)
return ans
def dfs(self, board, i,j,path,trie, ans):
if i<0 or j<0 or i>=len(board) or j >= len(board[0]):
return
if board[i][j] in trie:
temp = board[i][j]
board[i][j] = "#"
cur = trie[temp]
if -1 in cur:
ans.append(path+temp)
cur.pop(-1)
self.dfs(board,i-1, j,path+temp, cur, ans)
self.dfs(board,i+1, j,path+temp, cur, ans)
self.dfs(board,i, j-1,path+temp, cur, ans)
self.dfs(board,i, j+1,path+temp, cur, ans)
board[i][j] = temp | word-search-ii | python trie and dfs | anyone knows why this is slow? | li87o | 0 | 141 | word search ii | 212 | 0.368 | Hard | 3,643 |
https://leetcode.com/problems/word-search-ii/discuss/1966819/Word-Search-II-Python-3Totally-Math-Method | class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
words_out = []
for w_x in words:
inx_words = []
inx_count = []
for xx in range(len(w_x)):
inx_words.append(self.index_all(board, w_x[xx]))
inx_count.append(len(inx_words[xx]))
if inx_count.count(0) > 0:
pass
else:
board_2 = []
for x in range(len(board)):
for y in range(len(board[0])):
try:
b2 = [f'{board[x][y]}{board[x][y + 1]}']
except IndexError:
b2 = [0]
try:
b2 += [f'{board[x][y]}{board[x + 1][y]}']
except IndexError:
b2 += [0]
b2 += [f'{board[x][y]}{board[x][y - 1]}', f'{board[x][y]}{board[x - 1][y]}']
if x == 0 and y == 0:
board_2 += b2[:2]
elif x == 0 and y != 0:
board_2 += b2[:3]
elif x != 0 and y == 0:
board_2 += [b2[0], b2[1], b2[3]]
else:
board_2 += b2
break_c = False
for x in range(len(w_x) - 1):
words_2 = w_x[x] + w_x[x + 1]
if board_2.count(words_2) == 0:
break_c = True
break
if break_c:
continue
w_x0 = w_x[:]
if inx_count[-1] <= inx_count[0]:
w_x = w_x[::-1]
inx_words = inx_words[::-1]
inx = [0 for i in range(len(w_x))]
while inx[0] < len(inx_words[0]):
inx_s1 = inx_words[0][inx[0]]
i = 1
path = [inx_s1]
inx_words0 = [aa[:] for aa in inx_words]
while i < len(w_x):
try:
for ix in range(i, len(w_x)):
if inx_words0[ix].count(inx_s1) > 0:
inx_words0[ix].remove(inx_s1)
inx_s2 = inx_words0[i][inx[i]]
inx_s12 = [[inx_s1[0] + 1, inx_s1[1]], [inx_s1[0] - 1, inx_s1[1]],
[inx_s1[0], inx_s1[1] + 1], [inx_s1[0], inx_s1[1] - 1]]
if inx_s12.count(inx_s2) == 0:
inx[i] += 1
break
inx_s1 = inx_s2
path.append(inx_s1)
i += 1
except IndexError:
inx[i - 1] += 1
inx[i:] = [0] * (len(w_x) - i)
break
if i == len(w_x):
inx[i - 1] += 1
if len(w_x) == len(set(map(tuple, path))):
words_out.append(w_x0)
break
return words_out
def index_all(self, my_list, v):
inx_s = []
for i, x in enumerate(my_list):
inx_c = [i for i, m in enumerate(x) if m == v]
for xx in inx_c:
inx_s.append([i, xx])
return inx_s | word-search-ii | Word Search II - [Python 3]Totally Math Method | kkimm | 0 | 115 | word search ii | 212 | 0.368 | Hard | 3,644 |
https://leetcode.com/problems/word-search-ii/discuss/1783115/Python3-or-Faster-than-60-Memory-less-than-99 | class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
h, w = len(board), len(board[0])
def visit(word, start, i, j, path=[]):
if start >= len(word):
path.append([i, j])
return True
elif len(word)-1 == start and word[start] == board[i][j]:
path.append([i, j])
return True
elif word[start] != board[i][j]:
return False
else:
path.append([i, j])
res = []
for a, b in [[1, 0], [-1, 0], [0, 1], [0,-1]]:
if 0 <= i+a < h and 0 <= j+b < w and [i+a, j+b] not in path:
newp = [e for e in path]
res.append(visit(word, start+1, i+a, j+b, newp))
if res and True in res:
return True
vocab = set([board[i][j] for i in range(h) for j in range(w)])
out = []
for word in words:
chars = set(word)
skip = False
for c in chars:
if c not in vocab:
skip = True
break
if skip:
continue
res = False
for i in range(h):
for j in range(w):
if word[0] == board[i][j]:
res = visit(word, 0, i, j, [])
if res:
break
if res:
out.append(word)
break
return out | word-search-ii | Python3 | Faster than 60%, Memory less than 99% | elainefaith0314 | 0 | 165 | word search ii | 212 | 0.368 | Hard | 3,645 |
https://leetcode.com/problems/word-search-ii/discuss/1429990/Simple-Trie-based-solution-35-Lines-(50-50) | class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
### ADD to Trie
def add(word):
if word[0] not in trie:
trie[word[0]] = {}
addOn(word[1:],trie[word[0]])
def addOn(word,node):
if not word:
node['$'] = True
return
if word[0] not in node:
node[word[0]] = {}
addOn(word[1:],node[word[0]])
### search+backtrack over Trie
def search(i,j,path,node) -> bool:
if '$' in node and node['$']:
response.append(''.join(path+[board[i][j]]))
node['$'] = False # Ensures no duplicate entry in response.
letter = board[i][j]
board[i][j] = '#'
path.append(letter)
for x,y in [[0,-1],[-1,0],[0,1],[1,0]]:
c,d=x+i,y+j
if 0 <= c < m and 0 <= d < n and board[c][d] in node:
search(c,d,path,node[board[c][d]])
path.pop()
board[i][j] = letter
### Main
trie,response = {},[]
for word in words:
add(word)
m,n = len(board),len(board[0])
for i in range(m):
for j in range(n):
if board[i][j] in trie:
search(i,j,[],trie[board[i][j]])
return response | word-search-ii | Simple Trie based solution , 35 Lines (50%, 50%) | worker-bee | 0 | 125 | word search ii | 212 | 0.368 | Hard | 3,646 |
https://leetcode.com/problems/word-search-ii/discuss/1242247/Python-DFS-Beats-99-Pass-All-Test-Cases-But-WRONG | class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
# My Effort - Passed all test cases, yet backtracking line doesn't work
cntBoard = collections.Counter(''.join([e for row in board for e in row ]))
cntW = [collections.Counter(w) for w in words]
idxBoard = collections.defaultdict(list)
m, n = len(board), len(board[0])
for i in range(m):
for j in range(n):
idxBoard[board[i][j]].append((i,j))
# print(idxBoard)
dirs = [(0,1), (0,-1), (-1,0), (1,0)]
# dirs = [(0,1), (0,-1), (1,0), (-1,0)] # fail some test cases
def dfs(x, y, w, i):
if i == len(w):
return True
for a, b in dirs:
nx, ny = x + a, y + b
if 0 <= nx < m and 0 <= ny < n and (nx, ny) not in visited and board[nx][ny] == w[i]:
visited.add((nx, ny))
return dfs(nx, ny, w, i+1) # if I don't add return, the recursive function call returns None or False
# visited.remove((nx, ny)) # However, if I add return, this line is never executed, backtracking doesn't work but we actually need backtracking
ans = []
for w in words:
if collections.Counter(w) - cntBoard:
continue
for x, y in idxBoard[w[0]]:
visited = set()
visited.add((x,y))
result = dfs(x, y, w, 1)
if result:
ans.append(w)
break
return ans | word-search-ii | Python DFS Beats 99% Pass All Test Cases But WRONG | Yan_Air | 0 | 290 | word search ii | 212 | 0.368 | Hard | 3,647 |
https://leetcode.com/problems/house-robber-ii/discuss/2158878/Do-house-robber-twice | class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
dp = {}
def getResult(a,i):
if i>=len(a):
return 0
if i in dp:
return dp[i]
sum = 0
if i<len(a)-1:
sum+= max(a[i]+getResult(a,i+2),a[i+1]+getResult(a,i+3))
else:
sum+=a[i]+getResult(a,i+2)
dp[i] = sum
return sum
x = getResult(nums[:len(nums)-1],0)
dp = {}
y = getResult(nums[1:],0)
return max(x, y) | house-robber-ii | 📌 Do house robber twice | Dark_wolf_jss | 4 | 104 | house robber ii | 213 | 0.407 | Medium | 3,648 |
https://leetcode.com/problems/house-robber-ii/discuss/2345845/Success-Details-Runtime%3A-41-ms-oror-Python3-oror-vimla_kushwaha | class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
a1 = 0
b1 = nums[0]
a2 = 0
b2 = nums[1]
for i in range(1, len(nums) - 1):
a1, b1 = b1, max(a1 + nums[i], b1)
a2, b2 = b2, max(a2 + nums[i + 1], b2)
return max(b1, b2) | house-robber-ii | Success Details Runtime: 41 ms, || Python3 || vimla_kushwaha | vimla_kushwaha | 3 | 94 | house robber ii | 213 | 0.407 | Medium | 3,649 |
https://leetcode.com/problems/house-robber-ii/discuss/2345845/Success-Details-Runtime%3A-41-ms-oror-Python3-oror-vimla_kushwaha | class Solution:
def rob(self, nums: List[int]) -> int:
n=len(nums)
# step 1 or 2
if n<=2:
return max(nums)
return max(self.helper(nums[:-1]),self.helper(nums[1:]))
def helper(self,nums):
dp=[0]*len(nums)
dp[0]=nums[0]
dp[1]=max(nums[0],nums[1])
for i in range(2,len(nums)):
dp[i]=max(nums[i]+dp[i-2],dp[i-1])
return max(dp) | house-robber-ii | Success Details Runtime: 41 ms, || Python3 || vimla_kushwaha | vimla_kushwaha | 3 | 94 | house robber ii | 213 | 0.407 | Medium | 3,650 |
https://leetcode.com/problems/house-robber-ii/discuss/2177085/Python-DP-or-Beats-99-or-Very-Clearly-explained! | class Solution:
def rob(self, houses: List[int]) -> int:
if len(houses) == 1:
return houses[0]
if len(houses) == 2 or len(houses) == 3:
return max(houses)
def find(nums):
n = len(nums)
dp = [0] * n
dp[0], dp[1], dp[2] = nums[0], nums[1], nums[2] + nums[0]
for i in range(3, n):
dp[i] = max(dp[i-2], dp[i-3]) + nums[i]
return max(dp[-1], dp[-2])
return max(find(houses[1:]), find(houses[:-1])) | house-robber-ii | ✅Python DP | Beats 99% | Very Clearly explained! | PythonerAlex | 3 | 182 | house robber ii | 213 | 0.407 | Medium | 3,651 |
https://leetcode.com/problems/house-robber-ii/discuss/1468663/Python-or-DP-or-Memoization-or-With-Comments | class Solution:
def hh(self,nums):
dp=nums.copy() #memo table
dp[1]=max(dp[0],dp[1])
#this loop stores the values in memo table as : highest amount that can be stolen upto that house
for i in range(2,len(nums)):
dp[i]=max(dp[i-2]+nums[i],dp[i-1])
return max(dp)
def rob(self, nums: List[int]) -> int:
if len(nums)<3: #if less than 3 numbers are present in array then no need to loop
return max(nums)
# as first element and last element cant be used at the same time we can consider one at time and run the process
return max(self.hh(nums[1:]),self.hh(nums[:-1])) | house-robber-ii | Python | DP | Memoization | With Comments | nmk0462 | 2 | 205 | house robber ii | 213 | 0.407 | Medium | 3,652 |
https://leetcode.com/problems/house-robber-ii/discuss/2269240/Python-3-oror-Dynamic-programming | class Solution:
def rob(self, nums: List[int]) -> int:
return max(nums[0], self.helper(nums[1:]), self.helper(nums[:-1]))
def helper(self, nums):
rob1, rob2 = 0, 0
for n in nums:
newRob = max(rob1 + n, rob2)
rob1 = rob2
rob2 = newRob
return rob2 | house-robber-ii | Python 3 || Dynamic programming | sagarhasan273 | 1 | 24 | house robber ii | 213 | 0.407 | Medium | 3,653 |
https://leetcode.com/problems/house-robber-ii/discuss/2034891/Pythonor-Easy-Solution-including-Helper-function-of-House-Robber-1 | class Solution:
def rob(self, nums):
return max(nums[0], self.helper(nums[1:]), self.helper(nums[:-1]))
def helper(self, nums):
rob1, rob2 = 0, 0
for n in nums:
newRob = max(rob1 + n, rob2)
rob1 = rob2
rob2 = newRob
return rob2 | house-robber-ii | Python| Easy Solution including Helper function of House Robber 1 | shikha_pandey | 1 | 132 | house robber ii | 213 | 0.407 | Medium | 3,654 |
https://leetcode.com/problems/house-robber-ii/discuss/1505865/Python3-Easy-DFS-%2B-Memoization | class Solution:
def rob(self, nums: List[int]) -> int:
n = len(nums)
@cache
def dfs(i, robbedFirst):
if (i >= n or (i == n - 1 and robbedFirst)):
return 0
return max(dfs(i + 1, robbedFirst), nums[i] + dfs(i + 2, robbedFirst))
return max(dfs(1, False), nums[0] + dfs(2, True)) | house-robber-ii | Python3 - Easy DFS + Memoization ✅ | Bruception | 1 | 222 | house robber ii | 213 | 0.407 | Medium | 3,655 |
https://leetcode.com/problems/house-robber-ii/discuss/1468736/Python-DP-solution | class Solution:
def rob(self, nums: List[int]) -> int:
dp = [0]*(len(nums)-1)
if len(nums)==1:
return nums[0]
if len(nums)==2:
return max(nums[0],nums[1])
else:
# from starting to n-1
dp[0] = nums[0]
dp[1] = max(nums[0],nums[1])
for i in range(2,len(nums)-1):
dp[i] = max(nums[i]+dp[i-2],dp[i-1])
res1 = dp[-1]
#from second to last
dp[0] = nums[1]
dp[1] = max(nums[1],nums[2])
for i in range(2,len(nums)-1):
dp[i] = max(nums[i+1]+dp[i-2],dp[i-1])
res2 = dp[-1]
return max(res1,res2) | house-robber-ii | Python DP solution | dhanikshetty | 1 | 182 | house robber ii | 213 | 0.407 | Medium | 3,656 |
https://leetcode.com/problems/house-robber-ii/discuss/1459822/PyPy3-Solution-using-DP-w-comments | class Solution:
def rob(self, nums: List[int]) -> int:
# If array is empty
if not len(nums):
return 0
# If array has no more than three elements,
# as it is a circular array we can only select
# one of the three elements.
if len(nums) <= 3:
return max(nums)
# For all other cases, i.e., no. of elements are more
# than three
# Init
n = len(nums)
# Function to solve the subproblem
def maxAmountRobbed(arr: List) -> int:
# If array is empty
if not len(arr):
return 0
# If array has only two elements
if len(arr) <= 2:
return max(arr)
# For all other cases
m = len(arr)
t = dict()
# When only first element is scanned
t[0] = arr[0]
# When first two elements are scanned
t[1] = max(arr[0], arr[1])
# Scanning from second elements onwards
for i in range(2,m):
t[i] = max(arr[i] + t[i-2], t[i-1])
return t[m-1]
# IF we take 0th value we have to consider next possible
# values are upto n-1, as 0 and n are connected
v1 = maxAmountRobbed(nums[0:n-1])
# IF we take 1th value we have to consider next possible
# values up to n, as 0 and n are connected
v2 = maxAmountRobbed(nums[1:n])
return max(v1,v2) | house-robber-ii | [Py/Py3] Solution using DP w/ comments | ssshukla26 | 1 | 163 | house robber ii | 213 | 0.407 | Medium | 3,657 |
https://leetcode.com/problems/house-robber-ii/discuss/1440067/Simple-Python-dynamic-programming-solution | class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) <= 3:
return max(nums)
def max_profit(money):
dp = [0]*len(money)
for i in range(len(dp)):
prev = dp[i-1] if i > 0 else 0
prevprev = dp[i-2] if i > 1 else 0
dp[i] = max(prev, prevprev+money[i])
return dp[-1]
plan1 = max_profit(nums[:-1]) # either rob houses 0 to n-1
plan2 = max_profit(nums[1:]) # or rob houses 1 to n
return max(plan1, plan2) | house-robber-ii | Simple Python dynamic programming solution | Charlesl0129 | 1 | 121 | house robber ii | 213 | 0.407 | Medium | 3,658 |
https://leetcode.com/problems/house-robber-ii/discuss/893967/A-straightforward-solution-Python-faster-than-87.5 | class Solution:
def rob(self, a: List[int]) -> int:
@lru_cache(maxsize=None)
def g(i):
if i == 0: return 0
if i == 1: return a[1]
return max(g(i-1), g(i-2) + a[i])
@lru_cache(maxsize=None)
def f(i):
if i == 0: return a[0]
if i == 1: return max(a[0], a[1])
if i == n-1:
return max(f(n-2), g(n-3) + a[n-1])
return max(f(i-1), f(i-2) + a[i])
n = len(a)
return f(n-1) | house-robber-ii | A straightforward solution [Python, faster than 87.5%] | dh7 | 1 | 102 | house robber ii | 213 | 0.407 | Medium | 3,659 |
https://leetcode.com/problems/house-robber-ii/discuss/751488/Python-3%3A-O(N)-time-and-O(1)-space-easy-solution. | class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums)==1:
return nums[0]
elif len(nums)==0:
return 0
return max(self.robHelper(nums[1:]),self.robHelper(nums[:-1]))
def robHelper(self, arr):
"""
:type nums: List[int]
:rtype: int
"""
if len(arr)==0:
return 0
if len(arr)==1:
return arr[0]
if len(arr)==2:
return max(arr)
# maxSums[0] = arr[0]
first = arr[0]
second = max(first , arr[1])
for i in range(2,len(arr)):
current = max(second,first+arr[i])
first =second
second = current
return second | house-robber-ii | [Python 3]: O(N) time and O(1) space easy solution. | py_js | 1 | 88 | house robber ii | 213 | 0.407 | Medium | 3,660 |
https://leetcode.com/problems/house-robber-ii/discuss/2843265/Dynamic-Programming-Python3. | class Solution:
def rob(self, nums: List[int]) -> int:
n=len(nums)
if (n==1): return nums[0]
if (n==2): return max(nums[0],nums[1])
if (n==3): return max(nums[0],nums[1],nums[2])
def robPlain(nums):
nums[1]=max(nums[0],nums[1])
for i in range(2,len(nums)): nums[i]=max(nums[i-1],nums[i-2]+nums[i])
return nums[-1]
return max(robPlain(nums[:-1]),robPlain(nums[1:])) | house-robber-ii | Dynamic Programming, Python3. | minhhoanghectorjack | 0 | 2 | house robber ii | 213 | 0.407 | Medium | 3,661 |
https://leetcode.com/problems/house-robber-ii/discuss/2843180/Python-DP | class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) <= 2:
return max(nums)
DP0, DP1 = 0, 0
for i in range(len(nums) - 1):
DP0, DP1 = DP1, max(DP0 + nums[i], DP1)
res = DP1
DP0, DP1 = 0, 0
for i in range(1, len(nums)):
DP0, DP1 = DP1, max(DP0 + nums[i], DP1)
return max(res, DP1) | house-robber-ii | [Python] DP | i-hate-covid | 0 | 2 | house robber ii | 213 | 0.407 | Medium | 3,662 |
https://leetcode.com/problems/house-robber-ii/discuss/2822264/Python-solution-or-DP-faster-than-91 | class Solution:
def rob(self, nums: List[int]) -> int:
n = len(nums)
dp1 = [0] * n
dp2 = [0] * n
if n <= 3:
return max(nums)
# take first
dp1[0] = nums[0]
dp1[1] = nums[1]
#take last
dp2[1] = nums[1]
dp2[2] = nums[2]
for i in range(2,n-1):
dp1[i] = max(dp1[i-1], dp1[i-2] + nums[i], dp1[i-3] + nums[i])
for i in range(2,n):
dp2[i] = max(dp2[i-1], dp2[i-2] + nums[i], dp2[i-3] + nums[i])
return max(dp1[-2], dp2[-1]) | house-robber-ii | Python solution | DP faster than 91% | maomao1010 | 0 | 4 | house robber ii | 213 | 0.407 | Medium | 3,663 |
https://leetcode.com/problems/house-robber-ii/discuss/2821933/Python-Using-First-Version-But-Checking-Houses-Length-1 | class Solution:
def rob(self, nums: List[int]) -> int:
'''
Here, the additional condition is that first & last house are "adjacent"
so we can instead take the max of range excluding first vs. excluding last
In case only 1 house, return itself
'''
if len(nums) == 1:
return nums[0]
return max(self.loot(nums[:-1]), self.loot(nums[1:]))
def loot(self, houses):
'''
The idea is, given we cannot rob 2 adjacent houses, we care
do we rob current-house + last-last-house
or do we forgo current-house, and take last-house
To make calculations and base cases easier, we can prefix 2 houses
0, 0,[2,7, 9, 3, 1] curr + last-last OR just last
0 0 2 2 + 0 = 2 or 0
0 0 2 7 7 + 0 = 7 or 2
0 0 2 7 11 9 + 2 = 11 or 7
0 0 2 7 11 11 3 + 7 = 10 or 11
0 0 2 7 11 11 12 1 + 11 = 12 or 12
'''
last_last, last = 0, 0
for house in houses:
curr = max(house + last_last, last)
last_last, last = last, curr
return last | house-robber-ii | [Python] Using First Version, But Checking Houses Length 1 | graceiscoding | 0 | 3 | house robber ii | 213 | 0.407 | Medium | 3,664 |
https://leetcode.com/problems/house-robber-ii/discuss/2811029/PYTHON-99-Faster-Solution | class Solution:
def rob(self, nums: List[int]) -> int:
bup = nums[:]
nums = nums[:-1]
a, b = 0, 0
for i in nums:
a, b = b, max(i+a, b)
ans = b
nums = bup[1:]
a, b = 0, 0
for i in nums:
a, b = b, max(i+a, b)
return max(b, ans, bup[0]) | house-robber-ii | PYTHON 99% Faster Solution | hks_007 | 0 | 5 | house robber ii | 213 | 0.407 | Medium | 3,665 |
https://leetcode.com/problems/house-robber-ii/discuss/2794738/Concise-O(1)-space-solution | class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) < 3: return max(nums)
return max(self.robLinear(nums, 1, len(nums)), self.robLinear(nums,0,len(nums)-1))
def robLinear(self, nums: List[int], l: int, r: int) -> int:
c1, c2 = 0, 0
for i in range(l, r):
c1, c2 = c2, max(c2, nums[i] + c1)
return c2 | house-robber-ii | Concise O(1) space solution | mittoocode | 0 | 2 | house robber ii | 213 | 0.407 | Medium | 3,666 |
https://leetcode.com/problems/house-robber-ii/discuss/2730934/Veryy-easy-to-understand-beginner-level-Bottom-up | class Solution:
def solve1(self, nums): # exclude first 1 - ()n-1)
n = len(nums)
dp = [0]*n
dp[0] = 0
dp[1] = nums[1]
dp[2] = max(nums[1] , nums[2])
for i in range(2 , n):
take = nums[i]
if i > 2:
take += dp[i-2]
no = dp[i-1]
dp[i] = max(take , no)
return dp[n-1]
def solve2(self , nums): # 0 to n-2 exclude last element
n = len(nums)-1
dp = [0]*n
dp[0] = nums[0]
for i in range(1 , n):
take = nums[i]
if i >1:
take += dp[i-2]
no = dp[i-1]
dp[i] = max(take , no)
return dp[n-1]
def rob(self, nums: List[int]) -> int:
n = len(nums)
if(n==1):
return nums[n-1]
if(n==2):
return max(nums[0] , nums[1])
f2 = self.solve2(nums) # 0 to n-2 exclude last element
f1 = self.solve1(nums)
return max(f1 , f2) | house-robber-ii | Veryy easy to understand , beginner level Bottom-up | rajitkumarchauhan99 | 0 | 8 | house robber ii | 213 | 0.407 | Medium | 3,667 |
https://leetcode.com/problems/house-robber-ii/discuss/2713307/Python-solution-or-dp-and-O(n)-times | class Solution:
def rob(self, nums: List[int]) -> int:
length = len(nums)
if length <= 3:
return max(nums)
dp1 = [0] * length
dp2 = [0] * length
dp1[0] = nums[0]
dp1[1] = nums[1]
dp1[2] = max(dp1[0] + nums[2], dp1[1])
dp2[1] = nums[1]
dp2[2] = nums[2]
for i in range(3, len(nums) - 1):
dp1[i] = max(dp1[i-2] + nums[i], dp1[i-1], dp1[i-3] + nums[i])
for i in range(3, len(nums)):
dp2[i] = max(dp2[i-2] + nums[i], dp2[i-1], dp2[i-3] + nums[i])
return max(dp1 + dp2) | house-robber-ii | Python solution | dp & O(n) times | maomao1010 | 0 | 14 | house robber ii | 213 | 0.407 | Medium | 3,668 |
https://leetcode.com/problems/house-robber-ii/discuss/2710477/PYTHON-easy-oror-solution-or-using-DP-bottom-up-approach | class Solution:
def rob(self, nums: List[int]) -> int:
n=len(nums)
if n==1:
return nums[-1]
if n==2:
return max(nums[0],nums[1])
last=[0]*(n-1)
first=[0]*(n-1)
last[0]=nums[0]
last[1]=max(nums[0],nums[1])
first[0]=nums[1]
first[1]=max(nums[1],nums[2])
for i in range (2,n-1):
last[i]=max(nums[i]+last[i-2],last[i-1])
first[i]=max(nums[i+1]+first[i-2],first[i-1])
return max(first[-1],last[-1]) | house-robber-ii | PYTHON easy || solution | using DP bottom up approach | tush18 | 0 | 6 | house robber ii | 213 | 0.407 | Medium | 3,669 |
https://leetcode.com/problems/house-robber-ii/discuss/2707603/Python-DP | class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
def dp(cur, d, nums):
if d[cur] != -1:
return d[cur]
if cur >= len(nums) - 2:
# print(d, nums, cur)
d[cur] = nums[cur]
return d[cur]
elif cur >= len(nums) - 3:
d[cur] = nums[cur] + dp(cur + 2, d, nums)
else:
d[cur] = nums[cur] + max(dp(cur + 2, d, nums), dp(cur + 3, d, nums))
return d[cur]
n = len(nums)
res = 0
for i in range(len(nums)):
temp = nums[:]
temp = temp[i:] + temp[:i]
temp.pop()
d = [-1] * n
dp(0, d, temp)
res = max(res, max(d))
return res | house-robber-ii | Python DP | JSTM2022 | 0 | 3 | house robber ii | 213 | 0.407 | Medium | 3,670 |
https://leetcode.com/problems/house-robber-ii/discuss/2665019/Python-or-Dynamic-programming-(with-comments)-or-O(n) | class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
# For the first iteration we start from 1st house.
# But we can't visit last house so we dont't fill last value of dp1 array
dp1 = [0]*len(nums)
dp1[0], dp1[1] = nums[0], max(nums[0], nums[1])
for i in range(2, len(nums) - 1):
dp1[i] = max(dp1[i - 1], dp1[i - 2] + nums[i])
# On the second iteration we start from second house
# Because of that, we can visit last house
dp2 = [0]*len(nums)
dp2[0], dp2[1] = 0, nums[1]
for i in range(2, len(nums)):
dp2[i] = max(dp2[i - 1], dp2[i - 2] + nums[i])
# Here is one thing - for dp1 we should use penultimate element
return max(dp1[-2], dp2[-1]) | house-robber-ii | Python | Dynamic programming (with comments) | O(n) | LordVader1 | 0 | 30 | house robber ii | 213 | 0.407 | Medium | 3,671 |
https://leetcode.com/problems/house-robber-ii/discuss/2660830/here-is-my-solution-O(n)-greatergreater%3A) | class Solution:
def rob(self, n: List[int]) -> int:
l=len(n)
if(l==1):
return n[0]
elif l==2:
return max(n[0],n[1])
else:
prev2=n[0]
prev1=max(prev2,n[1])
for i in range(2,(l-1)):
pick=n[i]+prev2
notpick=prev1
prev2=prev1
prev1=max(pick,notpick)
ans1=prev1
prev2=n[1]
prev1=max(prev2,n[2])
for i in range(3,(l)):
pick=n[i]+prev2
notpick=prev1
prev2=prev1
prev1=max(pick,notpick)
ans2=prev1
return max(ans1,ans2) | house-robber-ii | here is my solution O(n)->>:) | re__fresh | 0 | 3 | house robber ii | 213 | 0.407 | Medium | 3,672 |
https://leetcode.com/problems/house-robber-ii/discuss/2652964/Pyhton-easy-oror-DP-oror | class Solution:
def rob(self, A: List[int]) -> int:
if len(A)<4: return max(A)
def solve(A):
dp = [0]*len(A)
dp[0],dp[1] = A[0],max(A[0],A[1])
for i in range(2,len(A)):
dp[i] = max(A[i]+dp[i-2],dp[i-1])
return dp[-1]
return max(solve(A[1:]),solve(A[:-1])) | house-robber-ii | Pyhton easy || DP || | Akash_chavan | 0 | 10 | house robber ii | 213 | 0.407 | Medium | 3,673 |
https://leetcode.com/problems/house-robber-ii/discuss/2597575/Simple-python-code-with-explanation | class Solution:
def rob(self, nums: List[int]) -> int:
return max(nums[0],self.helper(nums[1:]),self.helper(nums[:-1]))
def helper(self,nums):
nums.insert(0,0)
nums.insert(0,0)
rob1= 0
rob2 = 1
for i in range(2,len(nums)):
nums[i] = max((nums[i] + nums[rob1]),nums[rob2])
rob1 +=1
rob2 +=1
return nums[-1] | house-robber-ii | Simple python code with explanation | thomanani | 0 | 60 | house robber ii | 213 | 0.407 | Medium | 3,674 |
https://leetcode.com/problems/house-robber-ii/discuss/2587297/Python-Solution-using-DP | class Solution:
def rob(self, nums: List[int]) -> int:
return max(nums[0], self.helper(nums[1:]), self.helper(nums[:-1]))
def helper(self, nums):
rob1, rob2 = 0, 0
for n in nums:
temp = max(n + rob1, rob2)
rob1 = rob2
rob2 = temp
return rob2 | house-robber-ii | Python Solution using DP | nikhitamore | 0 | 25 | house robber ii | 213 | 0.407 | Medium | 3,675 |
https://leetcode.com/problems/house-robber-ii/discuss/2545377/Python-Recursion-or-beats-99.98 | class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
return max(self.dp(nums[0:len(nums)-1]), self.dp(nums[1:len(nums)]))
def dp(self, subarray: List[int]) -> int:
rob2 = 0
rob1 = 0
for i in subarray:
rob2, rob1 = max(rob2, rob1 + i), rob2
return rob2 | house-robber-ii | Python Recursion | beats 99.98% | amany5642 | 0 | 79 | house robber ii | 213 | 0.407 | Medium | 3,676 |
https://leetcode.com/problems/house-robber-ii/discuss/2519285/Python-%3A-House-Robber-1-Code-Copy-paste | class Solution:
def rob(self, num: List[int]) -> int:
if len(num)==1:
return num[0]
def rob1(nums):
n=len(nums)
# dp=[0 for i in range(n)]
if n==1:
return nums[0]
prev2=nums[0]
prev1=max(nums[0],nums[1])
# prev2=dp[0]
for i in range(2,n):
temp=prev1
prev1=max(prev2+nums[i],prev1)
prev2=temp
return prev1
return max(rob1(num[1:]),rob1(num[:-1])) | house-robber-ii | Python : House Robber 1 Code Copy paste | Prithiviraj1927 | 0 | 38 | house robber ii | 213 | 0.407 | Medium | 3,677 |
https://leetcode.com/problems/house-robber-ii/discuss/2518898/Easy-Solution-based-on-House-Rober-I-Python | class Solution:
def rob(self, nums: List[int]) -> int:
# Check if only one element
if len(nums) == 1:
return nums[0]
# First iteration
rob1, rob2 = 0, 0
for i in nums[:-1]:
temp = max(i+rob1, rob2)
rob1 = rob2
rob2 = temp
res1 = rob2
# Second iteration
rob1, rob2 = 0, 0
for i in nums[1:]:
temp = max(i+rob1, rob2)
rob1 = rob2
rob2 = temp
res2 = rob2
return max(res1,res2) | house-robber-ii | Easy Solution based on House Rober I - Python | cosminpm | 0 | 27 | house robber ii | 213 | 0.407 | Medium | 3,678 |
https://leetcode.com/problems/house-robber-ii/discuss/2407869/Python-3-solution-with-tabulation%2Bspace-optimization-and-29-ms-time | class Solution:
def solveTabSop(self,nums):
curr = 0
prev2 = 0
prev = nums[0]
for i in range(1,len(nums)):
curr = max(prev2+nums[i] , prev)
prev2= prev
prev = curr
return prev
def rob(self,nums):
if(len(nums)==1):
return nums[0]
if len(nums)==3:
return max(nums)
n=len(nums)
# return self.solve(nums,n-1)
first = nums[0:n-1]
last = nums[1::]
return max(self.solveTabSop(first),self.solveTabSop(last)) | house-robber-ii | Python 3 solution with tabulation+space optimization and 29 ms time | Sahil-Chandel | 0 | 26 | house robber ii | 213 | 0.407 | Medium | 3,679 |
https://leetcode.com/problems/house-robber-ii/discuss/2354633/Python-Bottom-Up-Approach-or-Easy-Solution | class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
if len(nums) == 2:
return max(nums[0], nums[1])
return max(nums[0], self.helper(nums[1:]), self.helper(nums[:-1]))
def helper(self, nums: List[int]):
nums.append(0)
for i in range(len(nums)-3, -1, -1):
nums[i] = max(nums[i+1], nums[i]+nums[i+2])
return max(nums[0], nums[1]) | house-robber-ii | Python Bottom Up Approach | Easy Solution | shreeruparel | 0 | 61 | house robber ii | 213 | 0.407 | Medium | 3,680 |
https://leetcode.com/problems/house-robber-ii/discuss/2352350/DP-or-Python-or-Beats-93.92 | class Solution:
def solve(self, ind, first_ind=0):
if ind >= len(self.nums):
return 0
if first_ind and ind == len(self.nums) - 1 and ind != 0:
return -1e9
if self.dp.get(ind) is not None and self.dp[ind][first_ind] is not None:
return self.dp[ind][first_ind]
self.dp[ind] = [None] * 2
self.dp[ind][first_ind] = max(self.solve(ind + 2, first_ind) + self.nums[ind], self.solve(ind + 3, first_ind) + self.nums[ind])
return self.dp[ind][first_ind]
def rob(self, nums: List[int]) -> int:
self.dp = {}
self.nums = nums
return max(self.solve(0, 1), self.solve(1), self.solve(2)) | house-robber-ii | DP | Python | Beats 93.92% | fake_death | 0 | 66 | house robber ii | 213 | 0.407 | Medium | 3,681 |
https://leetcode.com/problems/house-robber-ii/discuss/2328288/Python-Solution-%3A-Reusing-code-of-House-Robber-I | class Solution:
def rob(self, nums: List[int]) -> int:
return max(nums[0], self.helper(nums[1:]), self.helper(nums[:-1]))
def helper(self, nums):
ans1, ans2 = 0, 0
for n in nums:
temp = max(n + ans1, ans2)
ans1 = ans2
ans2 = temp
return ans2 | house-robber-ii | Python Solution : Reusing code of House Robber I | zip_demons | 0 | 70 | house robber ii | 213 | 0.407 | Medium | 3,682 |
https://leetcode.com/problems/house-robber-ii/discuss/2327570/SIMPLE-oror-FASTER-THAN-91 | class Solution:
def helper(self,nums):
n=len(nums)
prev,prev2=nums[0],0
for i in range(1,n):
if i>1:
curr=max(nums[i]+prev2,prev)
else:
curr=max(nums[i],prev)
prev2,prev=prev,curr
return prev
def rob(self,nums):
if len(nums)==1: return nums[0]
return max(self.helper(nums[1:]),self.helper(nums[:-1])) | house-robber-ii | SIMPLE || FASTER THAN 91% | vijayvardhan6 | 0 | 31 | house robber ii | 213 | 0.407 | Medium | 3,683 |
https://leetcode.com/problems/house-robber-ii/discuss/2313993/Python-Slower-than-95-but-easy | class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 1: return nums[0]
res = [0]*len(nums)
res[0] = 0
res[1] = nums[1]
for i in range(2,len(nums)):
res[i] = nums[i] + max(res[:i-1])
a = max(res[:])
res[0] = nums[0]
for i in range(2,len(nums)):
res[i] = nums[i] + max(res[:i-1])
b = max(res[:-1])
return max(a,b) | house-robber-ii | [Python] Slower than 95%, but easy | AvocadoDiCaprio | 0 | 11 | house robber ii | 213 | 0.407 | Medium | 3,684 |
https://leetcode.com/problems/house-robber-ii/discuss/2285785/Python-DP-Beats-98-with-full-working-explanation | class Solution:
def rob(self, nums: List[int]) -> int: # Time: O(n) and Space: O(1)
# breaking the list into 1 to n and 0 to n-1, such that 0 and n are adjacent to each other
# so, we can only include one of them and finding the max value from these lists and comparing them with 0 to find the max value among them
# in case of empty list the helper function will return null, so nums[0] will return an empty list
return max(nums[0], self.helper(nums[1:]), self.helper(nums[:-1]))
def helper(self, nums): # helper function is explained thoroughly in House Robber I solution
rob1, rob2 = 0, 0
for n in nums: # n represents current house
newRob = max(rob1 + n, rob2) # max of till previous-1 + current house or till previous not adjacent houses
rob1 = rob2
rob2 = newRob
return rob2 | house-robber-ii | Python [DP / Beats 98%] with full working explanation | DanishKhanbx | 0 | 67 | house robber ii | 213 | 0.407 | Medium | 3,685 |
https://leetcode.com/problems/house-robber-ii/discuss/2269100/Python-Dynamic-Programming-Easy-Soln | class Solution:
def rob(self, nums: List[int]) -> int:
n = len(nums)
return max(nums[0], self.helper(0, nums[1:], None), self.helper(0, nums[:n-1], None))
def helper(self, i, nums, lookup=None):
lookup = {} if lookup is None else lookup
if i in lookup:
return lookup[i]
if i >= len(nums):
return 0
lookup[i] = max(nums[i]+self.helper(i+2, nums, lookup), self.helper(i+1, nums, lookup))
return lookup[i] | house-robber-ii | Python Dynamic Programming Easy Soln | logeshsrinivasans | 0 | 66 | house robber ii | 213 | 0.407 | Medium | 3,686 |
https://leetcode.com/problems/house-robber-ii/discuss/2254112/Easy-Python-Solution-or-DP-or-Memoization-or-Faster-than-97 | class Solution:
def rob(self, nums: List[int]) -> int:
# memoization implementation
if len(nums)==1:
return nums[0]
def helper(ind, dp, arr):
if ind==0:
return arr[0]
if ind<0:
return 0
if dp[ind]!=-1:
return dp[ind]
pick=arr[ind]
if ind>1:
pick+=helper(ind-2, dp, arr)
notPick=helper(ind-1, dp, arr)
dp[ind]=max(pick, notPick)
return dp[ind]
first=nums[:-1]
last=nums[1:]
dp_first=[-1]*(len(first))
dp_last=[-1]*(len(last))
return max(helper(len(first)-1, dp_first, first), helper(len(last)-1, dp_last, last))
# tabulation implementation
# first=nums[:-1]
# dp_first=[0]*len(first)
# dp_first[0]=nums[0]
# for i in range(1, len(first)):
# if i>1:
# dp_first[i]=max(dp_first[i-1], dp_first[i-2]+first[i])
# else:
# dp_first[i]=max(dp_first[i-1], first[i])
# last=nums[1:]
# dp_last=[0]*len(last)
# dp_last[-1]=last[-1]
# for i in range(len(last)-2, -1, -1):
# if i<len(last)-2:
# dp_last[i]=max(dp_last[i+1], dp_last[i+2]+last[i])
# else:
# dp_last[i]=max(dp_last[i+1], last[i])
# return max(dp_last[0], dp_first[-1]) | house-robber-ii | Easy Python Solution | DP | Memoization | Faster than 97% | Siddharth_singh | 0 | 103 | house robber ii | 213 | 0.407 | Medium | 3,687 |
https://leetcode.com/problems/house-robber-ii/discuss/2233758/Faster-than-84-of-python-submission-and-68-less-space-usage | class Solution:
def rob(self, nums: List[int]) -> int:
# This below function is also a solution to HouseRobber-I question
def helper(nums):
rob1, rob2 = 0, 0
for value in nums:
newRobValue = max(value+rob1, rob2)
rob1 = rob2
rob2 = newRobValue
return rob2
return max(nums[0], helper(nums[1:]), helper(nums[:-1])) | house-robber-ii | Faster than 84% of python submission and 68% less space usage | himanshu17__ | 0 | 40 | house robber ii | 213 | 0.407 | Medium | 3,688 |
https://leetcode.com/problems/house-robber-ii/discuss/2227186/Easy-Python-Solution-using-DP-or-House-Robber-II | class Solution:
def helper(self, nums):
rob1, rob2 = 0, 0
for n in nums:
temp = max(rob1 + n, rob2)
rob1 = rob2
rob2 = temp
return rob2
def rob(self, nums: List[int]) -> int:
return max(nums[0],self.helper(nums[1:]),self.helper(nums[:-1])) | house-robber-ii | Easy Python Solution using DP | House Robber II | nishanrahman1994 | 0 | 53 | house robber ii | 213 | 0.407 | Medium | 3,689 |
https://leetcode.com/problems/house-robber-ii/discuss/2218149/House-Robber2-House-Robber1-with-1-extra-variable-or-recursion-with-memoization | class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums)==1:
return nums[0]
def robbing(index,memo,choosed):
if index in memo:return memo[index]
if index==0:return nums[index] if choosed else 0
if index<0:return 0
pick=nums[index]+robbing(index-2,memo,choosed)
notpick=0+robbing(index-1,memo,choosed)
memo[index]=max(pick,notpick)
return memo[index]
return max(robbing(len(nums)-2,{},True),robbing(len(nums)-1,{},False)) | house-robber-ii | House Robber2 = House Robber1 with 1 extra variable | recursion with memoization | glimloop | 0 | 84 | house robber ii | 213 | 0.407 | Medium | 3,690 |
https://leetcode.com/problems/house-robber-ii/discuss/2066723/Simple-Python-solution-oror-DYNAMIC-PROGRAMMING | class Solution:
def rob(self, nums: List[int]) -> int:
n=len(nums)
if n<=1:
return nums[0]
dp = [[-1]*n for _ in range(2)]
def rob(ind,dp,arr):
if ind == 0:
return arr[ind]
if ind<0:
return 0
if dp[ind] != -1:
return dp[ind]
pick = arr[ind] + rob(ind-2,dp,arr)
not_pick = 0 + rob(ind-1,dp,arr)
dp[ind] = max(pick, not_pick)
return dp[ind]
temp1 = nums[1:]
temp2 = nums[0:n-1]
return max(rob(len(temp1)-1, dp[0], temp1), rob(len(temp2)-1, dp[1], temp2)) | house-robber-ii | Simple Python solution || DYNAMIC PROGRAMMING | testbugsk | 0 | 102 | house robber ii | 213 | 0.407 | Medium | 3,691 |
https://leetcode.com/problems/house-robber-ii/discuss/2033940/Python-Faster-DP-Solution-(O(1)-memory-O(n)-time) | class Solution:
def helper(self, arr, start, end):
prev2 = 0
prev1 = 0
maxRes = 0
for i in range(start, end):
maxRes = max(prev2 + arr[i], prev1)
prev2 = prev1
prev1 = maxRes
return maxRes
def rob(self, nums: List[int]) -> int:
n = len(nums)
if n == 1:
return nums[0]
return max(self.helper(nums, 0, n-1), self.helper(nums, 1, n)) | house-robber-ii | Python Faster DP Solution (O(1) memory, O(n) time) | dbansal18 | 0 | 65 | house robber ii | 213 | 0.407 | Medium | 3,692 |
https://leetcode.com/problems/house-robber-ii/discuss/2024010/Python-or-DP-or-Easy-to-Understand | class Solution:
def rob(self, nums: List[int]) -> int:
n = len(nums)
if n == 1:
return nums[0]
if n == 2:
return max(nums[0], nums[1])
# result1: don't consider the first house
# result2: don't consider the last house
result1 = self.robRange(nums, 1, n-1)
result2 = self.robRange(nums, 0, n-2)
return max(result1, result2)
def robRange(self, nums, start, end):
dp = [0] * len(nums)
dp[start] = nums[start]
dp[start + 1] = max(nums[start], nums[start + 1])
for i in range(start + 2, end + 1):
dp[i] = max(dp[i -2] + nums[i], dp[i - 1])
return dp[end] | house-robber-ii | Python | DP | Easy to Understand | Mikey98 | 0 | 127 | house robber ii | 213 | 0.407 | Medium | 3,693 |
https://leetcode.com/problems/shortest-palindrome/discuss/2157861/No-DP-No-DS-Intuitive-with-comments-oror-Python | class Solution:
def shortestPalindrome(self, s: str) -> str:
end = 0
# if the string itself is a palindrome return it
if(s == s[::-1]):
return s
# Otherwise find the end index of the longest palindrome that starts
# from the first character of the string
for i in range(len(s)+1):
if(s[:i]==s[:i][::-1]):
end=i-1
# return the string with the remaining characters other than
# the palindrome reversed and added at the beginning
return (s[end+1:][::-1])+s | shortest-palindrome | No DP; No DS; Intuitive with comments || Python | a-myth | 2 | 124 | shortest palindrome | 214 | 0.322 | Hard | 3,694 |
https://leetcode.com/problems/shortest-palindrome/discuss/1665104/Python3-groupby-solution-without-KMP | class Solution1:
def shortestPalindrome(self, s: str) -> str:
"""We create two new arrays to represent the original string. We use
`groupby` to count the number of repeats of each consecutive letters
and record them in two arrays. One is letters, recording all
consecutively distinct letters. The other is indices, recording the
index of the last appearance of the corresponding letter in letters.
Let idx = len(indices) - 2. We want to examine whether a palindrome can
be formed from the start of s with the repeats of letters[idx] being in
the middle. There are three scenarios.
1. idx reaches the first letter and still no palindrome insight. We
need to reverse the substring starting from indices[idx + 1] to the end
and add it to the front of s.
2. A palindrome is found when idx is not pointing to the first letter
of s. This means we just need to reverse the remaining of s outside the
palindrome and add it to the front of s.
3. idx has not reached the first letter of s, yet a palindrome almost
forms. By almost forms, it means that the palindrome check has reaches
the first letter and the first letter is equal to the last letter in
the current palindrome check, yet the number of repeats of these two
do not match. In particular, the number of repeats of the first letter
is smaller than that of the last letter in check. In this case, we can
simply add to the front the difference in count between the first and
the last letter to form the palindrome, and then add the reversed
remaining substring to the front.
O(N), 56 ms, 73% ranking.
"""
letters = ['#']
indices = [-1]
for k, g in groupby(s):
letters.append(k)
indices.append(indices[-1] + len(list(g)))
idx = len(indices) - 2
while idx >= 0:
# scenario 1
if idx == 1:
return s[:indices[1]:-1] + s
# palindrome check
lo, hi = idx - 1, idx + 1
while lo >= 1 and hi < len(indices):
if letters[lo] != letters[hi] or (indices[lo] - indices[lo - 1]) != (indices[hi] - indices[hi - 1]):
break
lo -= 1
hi += 1
# scenario 2
if lo == 0:
return s[:indices[hi - 1]:-1] + s
# scenario 3
if lo == 1 and hi < len(indices) and letters[lo] == letters[hi]:
dif = (indices[hi] - indices[hi - 1]) - (indices[lo] - indices[lo - 1])
if dif > 0:
return s[:indices[hi]:-1] + letters[lo] * dif + s
idx -= 1
return s | shortest-palindrome | [Python3] `groupby` solution without KMP | FanchenBao | 2 | 99 | shortest palindrome | 214 | 0.322 | Hard | 3,695 |
https://leetcode.com/problems/shortest-palindrome/discuss/2820508/100-Faster-Python-Solution-using-KMP-Algorithm | class Solution:
def shortestPalindrome(self, s: str) -> str:
def kmp(txt, patt):
newString = patt + '#' + txt
freqArray = [0 for _ in range(len(newString))]
i = 1
length = 0
while i < len(newString):
if newString[i] == newString[length]:
length += 1
freqArray[i] = length
i += 1
else:
if length > 0:
length = freqArray[length - 1]
else:
freqArray[i] = 0
i += 1
return freqArray[-1]
cnt = kmp(s[::-1],s)
return s[cnt:][::-1]+s | shortest-palindrome | 100% Faster Python Solution - using KMP Algorithm | prateekgoel7248 | 1 | 32 | shortest palindrome | 214 | 0.322 | Hard | 3,696 |
https://leetcode.com/problems/shortest-palindrome/discuss/2541808/Python3-Epic-3-Liner | class Solution:
def shortestPalindrome(self, s: str) -> str:
for i in range(len(s), -1, -1):
if s[:i] == s[i-1::-1]:
return s[:i-1:-1] + s | shortest-palindrome | Python3 Epic 3 Liner | ryangrayson | 1 | 155 | shortest palindrome | 214 | 0.322 | Hard | 3,697 |
https://leetcode.com/problems/shortest-palindrome/discuss/2159251/Python-Stupidly-Simple-5-lines-solution | class Solution:
def shortestPalindrome(self, s: str) -> str:
if not s: return ""
for i in reversed(range(len(s))):
if s[0:i+1] == s[i::-1]:
return s[:i:-1] + s | shortest-palindrome | [Python] Stupidly Simple 5 lines solution | Saksham003 | 1 | 175 | shortest palindrome | 214 | 0.322 | Hard | 3,698 |
https://leetcode.com/problems/shortest-palindrome/discuss/739903/Python3-2-line-brute-force-and-9-line-KMP | class Solution:
def shortestPalindrome(self, s: str) -> str:
k = next((i for i in range(len(s), 0, -1) if s[:i] == s[:i][::-1]), 0)
return s[k:][::-1] + s | shortest-palindrome | [Python3] 2-line brute force & 9-line KMP | ye15 | 1 | 92 | shortest palindrome | 214 | 0.322 | Hard | 3,699 |
Subsets and Splits