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/discuss/2795313/Python-Solution-Beats-97-Solutions
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: graph = [[] for _ in range(numCourses)] indegree = [0 for _ in range(numCourses)] for edge in prerequisites: graph[edge[0]].append(edge[1]) indegree[edge[1]] += 1 queue = [] for degree in range(len(indegree)): if indegree[degree]==0: queue.append(degree) ans = [] while queue: curr_node = queue.pop(0) for node in graph[curr_node]: indegree[node] -= 1 if indegree[node] == 0 : queue.append(node) ans.append(curr_node) if len(ans) == numCourses: return True return False
course-schedule
Python Solution Beats 97% Solutions
manishchhipa
0
7
course schedule
207
0.454
Medium
3,500
https://leetcode.com/problems/course-schedule/discuss/2784880/Simple-Python-Solution
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: # cycle detection problem preMap = { i:[] for i in range(numCourses) } for crs, pre in prerequisites: preMap[crs].append(pre) # visitSet = all courses along the curr DFS path (cycle detection) visitSet = set() def dfs(crs): # base cases if crs in visitSet: return False if preMap[crs] == []: return True visitSet.add(crs) for pre in preMap[crs]: if not dfs(pre): return False visitSet.remove(crs) preMap[crs] = [] return True for crs in range(numCourses): if not dfs(crs): return False return True
course-schedule
Simple Python Solution
ekomboy012
0
4
course schedule
207
0.454
Medium
3,501
https://leetcode.com/problems/course-schedule/discuss/2774671/Topological-easy-to-understand
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: graph = collections.defaultdict(list) indegree = [0] * numCourses topologicalSort = [] # Build graph and calculate indegree for course,prerec in prerequisites: graph[course].append(prerec) indegree[prerec]+=1 # Until the topological sort is done(Or fails) while len(topologicalSort) != numCourses: # Find a source with a indegree of 0 try: source = indegree.index(0) # If it doesnt exists, there is a cycle except: return False indegree[source] = -1 topologicalSort.append(source) for node in graph[source]: indegree[node] -=1 return True
course-schedule
Topological easy to understand
Sarthaksin1857
0
4
course schedule
207
0.454
Medium
3,502
https://leetcode.com/problems/course-schedule/discuss/2769438/Topological-Sorting-easily-written-in-python
class Solution: # topological sorting in python def canFinish(self, n: int, pre: List[List[int]]) -> bool: graph = defaultdict(list) indegree = defaultdict(int) for a, b in pre: graph[a].append(b) graph[b].append(a) indegree[a] += 1 q = deque() for node in graph: if node not in indegree: q.append(node) while q: node = q.popleft() for nei in graph[node]: indegree[nei] -= 1 if indegree[nei] == 0: q.append(nei) for node in graph: if node in indegree and indegree[node] > 0: return False return True
course-schedule
Topological Sorting easily written in python
shiv-codes
0
13
course schedule
207
0.454
Medium
3,503
https://leetcode.com/problems/course-schedule/discuss/2761106/Simple-Beginner-Friendly-Approach-or-DFS-or-O(V%2BE)
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: 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 False return True def dfs(self, vertex): self.path.add(vertex) for neighbour in self.graph[vertex]: if neighbour in self.path: return False if neighbour not in self.visited: self.visited.add(neighbour) if not self.dfs(neighbour): return False self.path.remove(vertex) self.order.append(vertex) return True
course-schedule
Simple Beginner Friendly Approach | DFS | O(V+E)
sonnylaskar
0
8
course schedule
207
0.454
Medium
3,504
https://leetcode.com/problems/course-schedule/discuss/2760799/simple-detect-DAG-using-DFS-striver-solution
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: dic=defaultdict(list) for a,b in prerequisites: dic[a]+=[b] vis=[0]*(numCourses) dfsvis=[0]*numCourses def dfs(node): vis[node]=1 dfsvis[node]=1 if node in dic: for it in dic[node]: if vis[it]==0: if not dfs(it): return False elif vis[it]==1 and dfsvis[it]==1: return False dfsvis[node]=0 return True for i in range(numCourses): if vis[i]==0: ans=dfs(i) if not ans: return False return True
course-schedule
simple detect DAG using DFS , striver solution
aryan3012
0
14
course schedule
207
0.454
Medium
3,505
https://leetcode.com/problems/course-schedule/discuss/2752083/Python3-or-Two-Approach-or-TopoSort-or-Cycle-Detection
class Solution: def canFinish(self, numCourses: int, pre: List[List[int]]) -> bool: def TopoSort(graph,indegree): ans=[] stack=[course for course in range(numCourses) if indegree[course]==0] while stack: currCourse=stack.pop() ans.append(currCourse) for it in graph[currCourse]: indegree[it]-=1 if indegree[it]==0: stack.append(it) return len(ans)==numCourses indegree=[0 for i in range(numCourses)] graph=[[] for i in range(numCourses)] for u,v in pre: indegree[v]+=1 graph[u].append(v) return TopoSort(graph,indegree)
course-schedule
[Python3] | Two Approach | TopoSort | Cycle Detection
swapnilsingh421
0
7
course schedule
207
0.454
Medium
3,506
https://leetcode.com/problems/course-schedule/discuss/2752083/Python3-or-Two-Approach-or-TopoSort-or-Cycle-Detection
class Solution: def canFinish(self, numCourses: int, pre: List[List[int]]) -> bool: graph=[[] for i in range(numCourses)] vis=set() temp_vis=set() def dfs(course): for it in graph[course]: if it in temp_vis: return True if it not in vis: vis.add(it) temp_vis.add(it) if dfs(it): return True temp_vis.remove(it) return False for u,v in pre: graph[u].append(v) for course in range(numCourses): if course not in vis: vis.add(course) temp_vis.add(course) if dfs(course): return False temp_vis.remove(course) return True
course-schedule
[Python3] | Two Approach | TopoSort | Cycle Detection
swapnilsingh421
0
7
course schedule
207
0.454
Medium
3,507
https://leetcode.com/problems/course-schedule/discuss/2739412/Python-dfs-solution
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: adjMap = collections.defaultdict(list) for course, pre in prerequisites: adjMap[course].append(pre) visited = set() def dfs(crs): if crs in visited: return False if adjMap[crs] == []: return True visited.add(crs) for pre in adjMap[crs]: if not dfs(pre): return False visited.remove(crs) adjMap[crs] = [] return True for n in range(numCourses): if not dfs(n): return False return True
course-schedule
Python dfs solution
gcheng81
0
20
course schedule
207
0.454
Medium
3,508
https://leetcode.com/problems/course-schedule/discuss/2739343/Python-Simple-Cycle-Detection-Method
class Solution: def buildGraph(self, numCourses, prerequisites): self.graph = [[] for _ in range(numCourses)] for course, prerequisite in prerequisites: self.graph[prerequisite].append(course) def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: if not prerequisites: return True self.buildGraph(numCourses, prerequisites) self.ok = True self.visited = [False for _ in range(numCourses)] def traverse(node, path): if not self.ok or self.visited[node]: return self.visited[node] = True path.append(node) for neighbour in self.graph[node]: if neighbour in path: self.ok = False else: traverse(neighbour, path) path.pop() for i in range(numCourses): traverse(i, []) return self.ok
course-schedule
Python Simple Cycle Detection Method
Rui_Liu_Rachel
0
16
course schedule
207
0.454
Medium
3,509
https://leetcode.com/problems/course-schedule/discuss/2735127/simple-pythonor-DFS
class Solution: def traversed(self, now_point): #print(self.onpath, self.flag, now_point) if self.onpath[now_point]: self.flag = True return if self.visited[now_point] or self.flag: return self.visited[now_point] = True self.onpath[now_point] = True for t in self.graph[now_point]: self.traversed(t) self.onpath[now_point] = False def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: self.graph = [[]for _ in range(numCourses)] for i in prerequisites: a = i[0] b = i[1] self.graph[b].append(a) #print(self.graph) self.flag = False self.onpath = [False for _ in range(numCourses)] self.visited = [False for _ in range(numCourses)] for i in range(numCourses): self.traversed(i) if self.flag: return False return True
course-schedule
simple python| DFS
lucy_sea
0
1
course schedule
207
0.454
Medium
3,510
https://leetcode.com/problems/course-schedule/discuss/2733375/Python-DFS
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: graph = defaultdict(list) seen = set() for next_course, prev_course in prerequisites: graph[prev_course].append(next_course) def detectCycle(node, path): # we can skip a node if that node has already been visited if node in seen: return False # if node in the execution stack then we detected cycle, e.g. 1 -> 2 -> 1 if path.get(node): return True path[node] = True for course in graph[node]: if detectCycle(course, path): return True del path[node] seen.add(node) return False for course in range(numCourses): if detectCycle(course, {}): return False return True
course-schedule
Python DFS
alexdomoryonok
0
6
course schedule
207
0.454
Medium
3,511
https://leetcode.com/problems/course-schedule/discuss/2718675/DFS-coloring-python3-solution
class Solution: # O(V + E) time, # O(V + E) space, # Approach: dfs coloring, topological sort def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: graph = defaultdict(list) for course, required in prerequisites: graph[required].append(course) def hasCycle(curr_course, colors): if colors[curr_course] == 2: return False if colors[curr_course] == 1: return True colors[curr_course] = 1 for neighbor in graph[curr_course]: if hasCycle(neighbor, colors): return True colors[curr_course] = 2 return False colors = [0 for _ in range(numCourses)] for course in range(numCourses): if hasCycle(course, colors): return False return True
course-schedule
DFS coloring python3 solution
destifo
0
4
course schedule
207
0.454
Medium
3,512
https://leetcode.com/problems/course-schedule/discuss/2710789/PYTHON-SOLUTION
class Solution: def canFinish(self, num: int, pre: List[List[int]]) -> bool: graph=defaultdict(list) indegree=[0]*num for u,v in pre: indegree[v]+=1 graph[u].append(v) queue=deque() for v in range(num): if indegree[v]==0: queue.append(v) count=0 while queue: u=queue.popleft() count+=1 for v in graph[u]: indegree[v]-=1 if indegree[v]==0: queue.append(v) return count==num
course-schedule
PYTHON SOLUTION
shashank_2000
0
20
course schedule
207
0.454
Medium
3,513
https://leetcode.com/problems/course-schedule/discuss/2661459/Python3-Topological-Sort
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: # topological sort # must take course b before taking course a in_degrees = {key: [] for key in range(numCourses)} out_degrees = {key: [] for key in range(numCourses)} top_sort = [] for prereq in prerequisites: in_degrees[prereq[0]].append(prereq[1]) out_degrees[prereq[1]].append(prereq[0]) no_indegrees = [] for key, value in in_degrees.items(): if not len(value): no_indegrees.append(key) while len(no_indegrees): cur = no_indegrees.pop() top_sort.append(cur) for out in out_degrees[cur]: in_degrees[out].remove(cur) if not in_degrees[out]: no_indegrees.append(out) return len(top_sort) == numCourses
course-schedule
Python3, Topological Sort
jzhao49
0
5
course schedule
207
0.454
Medium
3,514
https://leetcode.com/problems/course-schedule/discuss/2655428/BFS-(Kahns-Algorithm)-Python
class Solution: def getCounts(self, graph): counts = {node: 0 for node in graph} for parent in graph: for child in graph[parent]: counts[child] += 1 return counts def topoSort(self, numCourses,graph): q = deque() counts = self.getCounts(graph) res = 0 for node in counts: if counts[node] == 0: q.append(node) while q: node = q.popleft() res += 1 for child in graph[node]: counts[child] -= 1 if counts[child] == 0: q.append(child) return res == numCourses def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: graph = {course: [] for course in range(numCourses)} for b, a in prerequisites: graph[b].append(a) return self.topoSort(numCourses, graph)
course-schedule
BFS (Kahns Algorithm) - Python
user3734a
0
5
course schedule
207
0.454
Medium
3,515
https://leetcode.com/problems/course-schedule/discuss/2374271/Python-runtime-28.97-memory-63.14
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: d = {} for i in range(numCourses): d[i] = [] for pre in prerequisites: d[pre[1]].append(pre[0]) for num in range(numCourses): if not self.check(num, set(), d): return False return True def check(self, num, path, d): if num in path: return False path.add(num) while d[num] != []: node = d[num].pop() if not self.check(node, path, d): return False path.remove(num) return True
course-schedule
Python, runtime 28.97%, memory 63.14%
tsai00150
0
63
course schedule
207
0.454
Medium
3,516
https://leetcode.com/problems/course-schedule/discuss/2343372/Python-topological-sort
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: # { course : List[classes with course as prereq] } prerequisites_map = defaultdict(list) # number of prerequisites each course has indegrees = defaultdict(int) # Fill in values for prerequisites_map and indegrees for course, prereq in prerequisites: prerequisites_map[prereq].append(course) indegrees[course] += 1 # Add courses with no prereqs to stack (could also be a queue or a set) stack = deque() for course in range(numCourses): if indegrees[course] == 0: stack.append(course) # Find a topological ordering, if possible topological_ordering = [] while stack: curr_course = stack.pop() topological_ordering.append(curr_course) for neighbor in prerequisites_map[curr_course]: # Remove edge we're currently exploring from graph (equivalent to taking the course curr_course) indegrees[neighbor] -= 1 # If we meet all of the prereqs for neighbor, add it to the stack if indegrees[neighbor] == 0: stack.append(neighbor) # If len(topological_ordering) < numCourses, there is a cycle return len(topological_ordering) == numCourses
course-schedule
Python topological sort
chromium-52
0
75
course schedule
207
0.454
Medium
3,517
https://leetcode.com/problems/course-schedule/discuss/2329370/Python3-or-Topological-Sorting-using-Kahn's-Algorithm-BFS
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: #First, we will process each and every prerequisite to get a sense of each course #node's indegree and map out an adjacency list representation of the directed #graph in a 2d array! #list comprehension to initialize adjacency list 1-d arrays numCourses of them! #If we let n= numCourses and m = len(prereqs) #Time:O(m + n + n*n), in the worst case: the vertex's adjacency list goes out to every other vertex #in graph! -> O(m+ n^2) #Space: O(n*n + n + n + n) -> O(n^2) graph = [[] for _ in range(numCourses)] #initializing an 1-d array that keeps track of the indegrees! indegrees = [0] * numCourses #first, iterate through prereq and build up our graph as well as update indegrees array! for dest, src in prerequisites: #add the edge going from src to destin the appropriate adjacency list! graph[src].append(dest) #update the indegree of destination node! indegrees[dest] += 1 #initialize our todo queue! todo = deque() #this will keep track of number of nodes we deleted along with all of its outgoing edges as we #proceed with Kahn's algorithm for Topological sorting! index = 0 ordering = [None] * numCourses #iterate through our indegrees array and enqueue all courses that have no prereqs at the very beg! for i in range(len(indegrees)): #if ith course has no prereqs, add it to the queue! if(indegrees[i] == 0): todo.append(i) #proceed with kahn's algorithm as long as queue is nonempty! while todo: #dequeue from our todo! current = todo.pop() neighbors = graph[current] for neighbor in neighbors: #decrement the indegrees of each and every neighbor to the current node we just dequeued! indegrees[neighbor] -= 1 #if deleting that particular edge made neighbor course also have no prereqs, make sure to #add it to the queue! if(indegrees[neighbor] == 0): todo.append(neighbor) ordering[index] = current index += 1 #if we don't have cycle we should have processed every single unvisited node and be able to take #all the course! -> This implies our index would have ended up out of bounds at index numCourses #if Kahn's algorithm went to completion! #otherwise, if we have cycle, we can't take all courses since we have interdependency! if(index == numCourses): return True return False
course-schedule
Python3 | Topological Sorting using Kahn's Algorithm BFS
JOON1234
0
41
course schedule
207
0.454
Medium
3,518
https://leetcode.com/problems/course-schedule/discuss/2329095/Python3-or-Need-Help-Figuring-Key-Error-for-TopSort-Approach
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: #First, we will process each and every prerequisite to get a sense of each course #node's indegree and map out an adjacency list representation of the directed #graph! indegrees = [0] * numCourses #hashmap will be used for adjacency-list representation! hashmap = {} #this for loop will find initial indegrees of every node and map out adjacency-list #representation of the graph of the sitatuation! for pre in prerequisites: course_want = pre[0] prereq = pre[1] if(prereq not in hashmap): hashmap[prereq] = [course_want] else: further_courses = hashmap[prereq] hashmap[prereq] = further_courses.append(course_want) indegrees[course_want] += 1 queue = [] ordering = [] for i in range(len(indegrees)): #if the course has no prereqs, then add it to the queue! if(indegrees[i] == 0): queue.append(i) #as long as queue is not empty, do topological sorting! while queue: node = queue[0] queue = queue[1:] if node in hashmap[node]: neighbors = hashmap[node] for neighbor in neighbors: indegrees[neighbor] -= 1 #check if deleting the directed edge from node to neighbor #made neighboring course have no prereqs! if(indegrees[neighbor] == 0): queue.append(neighbor) ordering.append(node) #at the end, if index does not equal numCourses, then we did not process every node -> we have a #cycle in graph -> we can't take every Course! if(len(ordering) != numCourses): print(hashmap) return False return True
course-schedule
Python3 | Need Help Figuring Key Error for TopSort Approach
JOON1234
0
4
course schedule
207
0.454
Medium
3,519
https://leetcode.com/problems/course-schedule/discuss/2297675/Python-BFS-Topological-Sort
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: graph = defaultdict(list) deg = defaultdict(int) for course, pre in prerequisites: graph[pre].append(course) deg[course] += 1 queue = deque([i for i in range(numCourses) if deg[i] == 0]) while queue: curr_course = queue.popleft() while graph[curr_course]: next_course = graph[curr_course].pop() if next_course in deg: deg[next_course] -= 1 if deg[next_course] == 0: queue.append(next_course) return True if max(deg.values()) == 0 else False
course-schedule
Python BFS Topological Sort
willager
0
44
course schedule
207
0.454
Medium
3,520
https://leetcode.com/problems/course-schedule/discuss/2274217/Clear-Python-solution-using-directed-graph-and-DFS-traversal
class Solution: hasCycle = False onPaths = [] visited = [] def __init(self): self.hasCycle = hasCycle self.onPaths = onPaths self.visited = visited def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: # check if there exists a mutual dependency for class prerequisites self.hasCycle = False # record all the nodes in an one-time traveral self.onPaths = [False] * numCourses # record all visited nodes to avoid starting from a node twice self.visited = [False] * numCourses graph = self.buildGraph(numCourses, prerequisites) for i in range(numCourses): self.traverse(graph, i) return (not self.hasCycle) def traverse(self, graph, s): if (self.onPaths[s] == True): self.hasCycle = True if (self.visited[s] == True or self.hasCycle == True): return; self.visited[s] = True self.onPaths[s] = True for i in graph[s]: self.traverse(graph, i) self.onPaths[s] = False def buildGraph(self, numCourses, prerequisites): graph = [None] * numCourses for i in range(numCourses): graph[i] = [] for edge in prerequisites: fromNode = edge[1] toNode = edge[0] graph[fromNode].append(toNode) return graph
course-schedule
Clear Python solution using directed graph and DFS traversal
leqinancy
0
32
course schedule
207
0.454
Medium
3,521
https://leetcode.com/problems/course-schedule/discuss/2272158/Python3-Simple-Solution-or-Iteration
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: if len(prerequisites) == 0 : return True primary, secondary = [], [] for x in prerequisites : primary.append(x[1]) secondary.append(x[0]) current = [] current.append(primary[0]) while True : try : primaryIndex = primary.index(current[-1]) except : primaryIndex = -1 if primaryIndex == -1 : try : indexToRemove = primary.index(current[-2]) except : current.pop() current.append(primary[0]) continue primary.pop(indexToRemove) secondary.pop(indexToRemove) current.pop(-1) else : secondaryValue = secondary[primaryIndex] if secondaryValue in current : return False current.append(secondaryValue) if len(primary) == 0 : return True
course-schedule
Python3 Simple Solution | Iteration
jasoriasaksham01
0
69
course schedule
207
0.454
Medium
3,522
https://leetcode.com/problems/course-schedule/discuss/2184476/Based-on-Cycle-Detection-in-a-directed-graph-oror-DFS
class Solution: 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 canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: graph = {i:[] for i in range(numCourses)} for course, prerequisite in prerequisites: graph[course].append(prerequisite) isFinish = not self.detectCycle(numCourses, graph) return isFinish
course-schedule
Based on Cycle Detection in a directed graph || DFS
Vaibhav7860
0
73
course schedule
207
0.454
Medium
3,523
https://leetcode.com/problems/course-schedule/discuss/2153401/207.-Java-and-Python-solution-with-My-comments
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: # idea: topological sort to find if there is a cycle in graph, dfs # if cycle exsits, then it is not possible to finish courses. # save a graph by using matrix/array graph = [[] for _ in range(numCourses)] visited = [0]* numCourses # create graph for pair in prerequisites: x, y = pair graph[x].append(y) # visit each node: for i in range(numCourses): # check cycle from current node if not self.dfs(graph, visited, i): # if any one time of dfs return False, it means there is cycle, so we cannot finish course schedule return False return True #For DFS, in each visit, we start from a node and keep visiting its neighbors, # if at a time we return to a visited node, there is a cycle. # Otherwise, start again from another unvisited node and repeat this process. def dfs(self, graph, visited, i): # if we see the node again in the current trip, it's a cycle if visited[i] == -1: return False # a dfs has been done starting from this node, no cycle is found if visited[i] == 1: return True # mark as being visited, so in the curruent trip, if we see a node with -1 again, it means there is a cycle visited[i] = -1 # visit all neighbours of the node for j in graph[i]: if not self.dfs(graph, visited, j): return False # after visit all the neighbours, # set all nodes along current path as valid path (no cycle) by flag +1 visited[i] = 1 return True
course-schedule
207. Java & Python solution with My comments
JunyiLin
0
54
course schedule
207
0.454
Medium
3,524
https://leetcode.com/problems/course-schedule/discuss/2056354/Python3-or-Topo-Sort-or-Easy-Understand
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: def count_parents(graph): counts = {node: 0 for node in graph} for parent in graph: for node in graph[parent]: counts[node] += 1 return counts def topo_sort(graph): seq, queue =[], deque() counts = count_parents(graph) for node in counts: if counts[node] == 0: queue.append(node) seq.append(node) if len(queue) == 0: return False while queue: node = queue.popleft() for child in graph[node]: counts[child] -= 1 if counts[child] == 0: queue.append(child) seq.append(child) return len(seq) == numCourses graph = {node: [] for node in range(numCourses)} for seq in prerequisites: preq, course = seq[0], seq[1] graph[course].append(preq) return topo_sort(graph)
course-schedule
Python3 | Topo Sort | Easy Understand
itachieve
0
83
course schedule
207
0.454
Medium
3,525
https://leetcode.com/problems/course-schedule/discuss/2009740/Clean-Python-3-Solution-(Topological-Sorting-%2B-BFS)
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: 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) finished = 0 while q: u0 = q.pop(0) finished += 1 for v, u in prerequisites: if u == u0: in_degrees[v] -= 1 if in_degrees[v] == 0: q.append(v) return True if finished == numCourses else False
course-schedule
Clean Python 3 Solution (Topological Sorting + BFS)
Hongbo-Miao
0
176
course schedule
207
0.454
Medium
3,526
https://leetcode.com/problems/course-schedule/discuss/1999693/Easy-Python3-cycle-detection-with-recursive-DFS-(clear-comments)
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: #The prerequisites can be represented as a directed graph, thus #let's do a dfs to detect a dependency cycle #course -> [prereqs] graph = {} #Prepare graph of course dependency for i in range(numCourses): graph[i] = [] for pr in prerequisites: graph[pr[0]].append(pr[1]) gray = set() #grey vertexs: discovered, but not all of its neighbours have been visited (might incur in a cycle) black = set() #black vertexs: discovered and all its neighbours have been visited (no cycle) #Using a simple visited set works with undirected graph only. #In directed graph, a cycle is present if and only if a node is seen again #before all its descendants have been visited: if a node has a neighbor which is grey, then there is a cycle. #This logic is easier to code using recursive DFS def cycle_detect(course): if course in gray: #cycle! return True if course in black: #Early cut-off to avoid TLE, since there will be no cycles anyway return False #Exhaust dependency path gray.add(course) for dep in graph[course]: if cycle_detect(dep): return True #Exhausted all the neighbors and no cycle was detected. #Move node to black list gray.remove(course) black.add(course) return False #Explore all possible dependency paths #in search of a dependency loop for course in range(numCourses): if course not in black: #No need to check for cycle again, since the DFS from this node was successful if cycle_detect(course): return False return True
course-schedule
Easy Python3 cycle detection with recursive DFS (clear comments)
Zikker
0
43
course schedule
207
0.454
Medium
3,527
https://leetcode.com/problems/course-schedule/discuss/1970724/Python-BFS-topological-sort
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: children = defaultdict(list) count_parents = defaultdict(int) nodes = set() for child, parent in prerequisites: children[parent].append(child) count_parents[child] += 1 nodes.add(parent) nodes.add(child) q = deque(node for node in nodes if node not in count_parents) count_visited = 0 while q: node = q.popleft() count_visited += 1 for child in children[node]: count_parents[child] -= 1 if count_parents[child] == 0: q.append(child) return count_visited == len(nodes)
course-schedule
Python, BFS topological sort
blue_sky5
0
103
course schedule
207
0.454
Medium
3,528
https://leetcode.com/problems/course-schedule/discuss/1970682/Python-DFS-cycle-detection
class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: STATUS_VISITING = 0 STATUS_VISITED = 1 def no_cycle(node): if node in status: if status[node] == STATUS_VISITED: return True else: return False status[node] = STATUS_VISITING for child in adj[node]: if not no_cycle(child): return False status[node] = STATUS_VISITED return True adj = defaultdict(list) nodes = set() for a, b in prerequisites: adj[b].append(a) nodes.add(b) status = {} for node in nodes: if not no_cycle(node): return False return True
course-schedule
Python, DFS cycle detection
blue_sky5
0
75
course schedule
207
0.454
Medium
3,529
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/1774062/Python-Explanation-of-sliding-window-using-comments
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: left = 0 # keep track of left pointer rsum = 0 # keep the running sum res = None # Answer we will return # Iterate through the array, the index will be your right pointer for right in range(len(nums)): # Add the current value to the running sum rsum += nums[right] # Once you reach a value at or equal to the target you # can use a while loop to start subtracting the values from left # to right so that you can produce the minimum size subarray while rsum >= target: # The result is either the current result you have, # or the count of numbers from the current left position # to the rightmost position. You need it to be right + 1 # because index starts at 0 (if you based the right as the # last index it would be 4 or len(nums) - 1) # If res is None we compare it against the max float, # saves us from having an if/else res = min(res or float('inf'), right + 1 - left) # Subtract the number to see if we can continue subtracting based # on the while loop case and increment the left pointer rsum -= nums[left] left += 1 return res or 0
minimum-size-subarray-sum
Python - Explanation of sliding window using comments
iamricks
8
376
minimum size subarray sum
209
0.445
Medium
3,530
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2348029/Python-Easy-sliding-window-with-explanation
class Solution: def minSubArrayLen(self, target, nums): # Init left pointer and answer l, ans = 0, len(nums) + 1 # Init sum of subarray s = 0 # Iterate through all numbers as right subarray for r in range(len(nums)): # Add right number to sum s += nums[r] # Check for subarray greater than or equal to target while s >= target: # Calculate new min ans = min(ans, r - l + 1) # Remove current left nubmer from sum s -= nums[l] # Move left index up one l += 1 # No solution if ans == len(nums) + 1: return 0 # Solution return ans
minimum-size-subarray-sum
[Python] Easy sliding window with explanation
drblessing
6
301
minimum size subarray sum
209
0.445
Medium
3,531
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/862364/O(N*LOG(N))-SOLUTION-EXPLAINED-PYTHON
class Solution: def minSubArrayLen(self, s: int, nums: List[int]) -> int: """ O(N*LOG(N)) Solution using prefix-sum array Since, we know all of the elements are positive, we can generate a prefix-sum array for the given nums array, which will be guaranteed to be in increasing order, aka a sorted list. Use this knowledge to then perform a binary search on the prefix-sum array for every element in the nums array, so that we can find the smallest sub-array starting from element at index = i with sum >= s, IF there is one - there might be no sub-array from index = i to the end of the array that sums to s or more. For example, nums = [8, 2, 3] &amp; s = 8: There is no subarray starting from index 1 or 2 that sums to 8 or more, only from index 0. """ n = len(nums) if not n or sum(nums) < s: return 0 # Generate prefix-sum array: # [2,3,1,2,4,3] = nums # [0,2,5,6,8,12,15] = prefix-sum F = [num for num in nums] F.insert(0, 0) for i in range(1, n+1): F[i] += F[i-1] answer = float('inf') # Perform binary search on the prefix-sums array # for every element in the nums array to get the # smallest sub-array starting from index i that sums # to s or more, IF there is one for i in range(n): l, r = i, n while l <= r: mid = (l+r)//2 if F[mid] - F[i] >= s: r = mid-1 else: l = mid + 1 if l <= n and F[l] - F[i] >= s: answer = min(answer, l-i) return answer if answer != float('inf') else 0
minimum-size-subarray-sum
O(N*LOG(N)) SOLUTION EXPLAINED PYTHON
nyc_coder
3
130
minimum size subarray sum
209
0.445
Medium
3,532
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2802486/Python-oror-Easy-ororSliding-Window
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: n=len(nums) i=j=0 s=nums[0] m=9999999 while j<n and i<=j: if s>=target: m=min(m,j-i+1) s-=nums[i] i+=1 else: j+=1 if j<n: s+=nums[j] if m!=9999999: return m return 0
minimum-size-subarray-sum
Python || Easy ||Sliding Window
DareDevil_007
2
116
minimum size subarray sum
209
0.445
Medium
3,533
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2564106/Python-or-Two-Pointers-w-comments
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: l = 0 curSum = 0 minLen = float('inf') for r in range(len(nums)): # add to curSum curSum += nums[r] while curSum >= target and l <= r: # update minlen minLen = min(minLen, (r - l)+1) # minlen ever hits 1, just return 1 if minLen == 1: return 1 # update cursum and l pointer curSum -= nums[l] l += 1 return minLen if minLen != float('inf') else 0
minimum-size-subarray-sum
Python | Two Pointers w/ comments
Mark5013
1
120
minimum size subarray sum
209
0.445
Medium
3,534
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2398279/Binary-Search-%2B-Sliding-Window
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: low, high = 1, len(nums) + 1 while (low < high): mid = (low + high)//2 if self.slidingWin(target, nums, mid): high = mid else: low = mid + 1 if self.slidingWin(target, nums, low): return low else: return 0 def slidingWin(self, target, nums, k): curSum = 0 maxSum = 0 l = 0 for i in range(len(nums)): curSum += nums[i] if i > k - 1: curSum -= nums[l] l += 1 maxSum = max(curSum, maxSum) return (maxSum >= target)
minimum-size-subarray-sum
Binary Search + Sliding Window
logeshsrinivasans
1
178
minimum size subarray sum
209
0.445
Medium
3,535
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/1620080/Python-oror-Easy-Solution-oror-O(n)-and-O(1)
class Solution: def minSubArrayLen(self, t: int, lst: List[int]) -> int: i, j = 0, 0 count = 0 maxi = 10 ** 5 while j < len(lst): count += lst[j] if count == t: if maxi > (j - i + 1): maxi = (j - i + 1) count -= lst[i] i += 1 j += 1 elif count > t: if maxi > (j - i + 1): maxi = (j - i + 1) count -= lst[i] count -= lst[j] i += 1 else: j += 1 if maxi == 10 ** 5: return 0 return maxi
minimum-size-subarray-sum
Python || Easy Solution || O(n) and O(1)
naveenrathore
1
224
minimum size subarray sum
209
0.445
Medium
3,536
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/1378327/Python-O(N)-2-solutions
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: left = 0 mx = float('inf') N = len(nums) currentSum = 0 for right in range(N): currentSum += nums[right] while currentSum >= target: mx = min(mx, right - left + 1) currentSum -= nums[left] left += 1 return 0 if mx == float('inf') else mx
minimum-size-subarray-sum
[Python] O(N) 2 solutions
ShSaktagan
1
180
minimum size subarray sum
209
0.445
Medium
3,537
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/1378327/Python-O(N)-2-solutions
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: left = right = 0 mx = float('inf') N = len(nums) currentSum = 0 while left < N or right < N: if currentSum >= target: mx = min(mx, right - left) if currentSum < target and right < N: currentSum += nums[right] right += 1 elif left < N: currentSum -= nums[left] left += 1 return 0 if mx == float('inf') else mx
minimum-size-subarray-sum
[Python] O(N) 2 solutions
ShSaktagan
1
180
minimum size subarray sum
209
0.445
Medium
3,538
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/1227341/Sliding-Window-of-Python3
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: length = len(nums) if length == 0: return 0 left, total, ans = 0, 0, float('inf') for i in range(length): total += nums[i] while total >= target: ans = min(ans, i + 1 - left) total -= nums[left] left += 1 return 0 if ans == float('inf') else ans
minimum-size-subarray-sum
Sliding Window of Python3
faris-shi
1
59
minimum size subarray sum
209
0.445
Medium
3,539
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2842053/BEATS-99-SUBMISSIONS-oror-FASTEST-AND-EASIEST-oror-SLIDING-WINDOW
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: l,total=0,0 res=float("inf") for r in range(len(nums)): total += nums[r] while total >=target: res =min((r-l +1),res) total -=nums[l] l +=1 return 0 if res==float("inf") else res
minimum-size-subarray-sum
BEATS 99% SUBMISSIONS || FASTEST AND EASIEST || SLIDING WINDOW
Pritz10
0
2
minimum size subarray sum
209
0.445
Medium
3,540
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2838746/Python-O(n)-solution-Accepted
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: left: int = 0 curr_sum: int = 0 min_len = len(nums) for i in range(len(nums)): curr_sum += nums[i] while curr_sum >= target: min_len = min(min_len, i - left + 1) curr_sum -= nums[left] left += 1 return 0 if min_len == len(nums) and sum(nums) < target else min_len
minimum-size-subarray-sum
Python O(n) solution [Accepted]
lllchak
0
3
minimum size subarray sum
209
0.445
Medium
3,541
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2838377/Python-Solution-Clear
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: ans=float('inf') left=0 summ=0 for i in range(len(nums)): summ+=nums[i] while summ>=target: ans=min(ans,i+1-left) summ-=nums[left] left+=1 return ans if ans!=inf else 0
minimum-size-subarray-sum
Python Solution - Clear
jainsiddharth99
0
2
minimum size subarray sum
209
0.445
Medium
3,542
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2809775/Python-Solution-with-sliding-window
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: res = float("inf") total = 0 l,r = 0,-1 while r<len(nums): if total<target: r+=1 if r>=len(nums): break total += nums[r] else: res = min(res,r-l+1) total -= nums[l] l+=1 return res if res!=float("inf") else 0
minimum-size-subarray-sum
[Python] Solution with sliding window
kevin-shu
0
4
minimum size subarray sum
209
0.445
Medium
3,543
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2802193/Minimum-size-subarray-sum
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: if target in nums: return 1 res=1e9 s=0;left=0 for right,val in enumerate(nums): s+=val while s>=target: res=min(res,right-left+1) s-=nums[left] left+=1 return res if res!=1e9 else 0
minimum-size-subarray-sum
Minimum size subarray sum
hemanth_12
0
3
minimum size subarray sum
209
0.445
Medium
3,544
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2796577/Easy-Python-Solution-using-Sliding-Window-Approach
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: min_length = float('inf') num_sum = 0 left = 0 for right, _ in enumerate(nums): num_sum += nums[right] while num_sum >= target: min_length = min(min_length, right - left + 1) num_sum -= nums[left] left += 1 return 0 if min_length == float('inf') else min_length
minimum-size-subarray-sum
Easy Python Solution using Sliding Window Approach
nadirahcodes
0
2
minimum size subarray sum
209
0.445
Medium
3,545
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2794176/Clean-Python-Sliding-Window-solution
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: minLen = 100001 start = 0 end = 0 s = 0 while end < len(nums): s += nums[end] while s >= target: minLen = min(minLen, end - start + 1) s -= nums[start] start += 1 end += 1 return minLen if minLen != 100001 else 0
minimum-size-subarray-sum
Clean Python Sliding Window solution
disturbedbrown1
0
1
minimum size subarray sum
209
0.445
Medium
3,546
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2791236/sliding-window-and-Time-complexity%3AO(n)
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: minimum=math.inf start,end,summ=0,0,0 while end<len(nums): summ=summ+nums[end] end=end+1 while summ>=target and end>start: summ=summ-nums[start] start=start+1 minimum=min(minimum,end-start+1) if minimum==math.inf: return 0 return minimum
minimum-size-subarray-sum
sliding window & Time complexity:O(n)
ManojDluffy
0
3
minimum size subarray sum
209
0.445
Medium
3,547
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2783718/Sliding-Window-O(N)-solution
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: start, end , cur_max = 0, 0 , math.inf if len(nums) == 0 : return 0 running_sum = 0 while start <= end and end < len(nums): if running_sum + nums[end] >= target: cur_max = min(cur_max,end - start+1) running_sum -= nums[start] start+=1 else: running_sum += nums[end] end+=1 if start == 0 and end == len(nums) and running_sum < target: cur_max = 0 return cur_max
minimum-size-subarray-sum
Sliding Window O(N) solution
ishitakumardps
0
3
minimum size subarray sum
209
0.445
Medium
3,548
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2697615/Python-solution
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: ans = float('inf') sums = 0 length = len(nums) left = 0 for right in range(length): sums += nums[right] while sums >= target and right >= left: ans = min(ans, right - left + 1) sums -= nums[left] left += 1 return ans if ans != float('inf') else 0
minimum-size-subarray-sum
Python solution
maomao1010
0
6
minimum size subarray sum
209
0.445
Medium
3,549
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2692034/Python-O(N)-O(1)
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: l = r = curr = 0 res = sys.maxsize for r in range(len(nums)): curr += nums[r] while curr >= target and l <= r: res = min(res, r - l + 1) curr -= nums[l] l += 1 return res if res != sys.maxsize else 0
minimum-size-subarray-sum
Python - O(N), O(1)
Teecha13
0
10
minimum size subarray sum
209
0.445
Medium
3,550
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2662977/slidding-Window-technique-python
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: l, total = 0, 0 res = float("inf") for r in range(len(nums)): total += nums[r] while total >= target: res = min(r - l + 1, res) total -= nums[l] l += 1 return 0 if res == float("inf") else res
minimum-size-subarray-sum
slidding Window technique python
sahilkumar158
0
2
minimum size subarray sum
209
0.445
Medium
3,551
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2552734/Python-Solution-or-Beats-97
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: i=0 s=0 n=len(nums) mini=1e9 for j in range(n): s+=nums[j] while s>=target: mini=min(mini, j-i+1) s-=nums[i] i+=1 if mini==1e9: return 0 return mini
minimum-size-subarray-sum
Python Solution | Beats 97%
Siddharth_singh
0
82
minimum size subarray sum
209
0.445
Medium
3,552
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2504239/fast-or-easy-python-code
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: n=len(nums) if n==0: return 0 i=0 j=0 minlen=n currsum=0 valid=False while j<n: currsum+=nums[j] j+=1 while currsum>=target: valid=True minlen=min(minlen,j-i) currsum-=nums[i] i+=1 if valid: return minlen else: return 0
minimum-size-subarray-sum
fast | easy python code
ayushigupta2409
0
40
minimum size subarray sum
209
0.445
Medium
3,553
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2407765/Min-Size-Subarray-Sum-or-Python-or-Sliding-Window-or-Time-Complexity%3A-O(n)
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: minimum = float("inf") window_sum, window_start = 0,0 for window_end in range(len(nums)): window_sum += nums[window_end] while window_sum >= target: # for this step you add one due to the indexing issues minimum = min(minimum,window_end -window_start +1) window_sum -= nums[window_start] window_start += 1 if minimum != float("inf"): return minimum return 0
minimum-size-subarray-sum
Min Size Subarray Sum | Python | Sliding Window | Time Complexity: O(n)
obaissa
0
56
minimum size subarray sum
209
0.445
Medium
3,554
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2406225/Sliding-Window-and-Two-Pointer
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: if nums[0]>=target: return 1 summ=nums[0] left=0 l=float('inf') for right in range(1,len(nums)): if nums[right]>=target: return 1 summ+=nums[right] while summ>=target and left<=right: summ-=nums[left] l=min(l,right-left+1) left+=1 if l==float('inf'): return 0 return int(l)
minimum-size-subarray-sum
Sliding Window and Two Pointer
Neerajbirajdar
0
41
minimum size subarray sum
209
0.445
Medium
3,555
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2277144/Python-O(n)-easy
class Solution(object): def minSubArrayLen(self, s, nums): if sum(nums)< s: return 0 ans, sum_ = sys.maxsize, 0 i = 0 j = 0 while j<len(nums): sum_+= nums[j] if sum_>=s: while sum_>=s: ans = min(ans, j-i+1) sum_-=nums[i] i+=1 print(i,j) j+=1 return ans
minimum-size-subarray-sum
Python O(n) easy
Abhi_009
0
128
minimum size subarray sum
209
0.445
Medium
3,556
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2191209/Sliding-Window-Approach
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: i, j, n = 0, 0, len(nums) s = 0 minLength = float('inf') while j < n: s += nums[j] if s < target: j += 1 else: while s >= target: minLength = min(minLength, j - i + 1) s -= nums[i] i += 1 j += 1 if minLength != float('inf'): return minLength else: return 0
minimum-size-subarray-sum
Sliding Window Approach
Vaibhav7860
0
85
minimum size subarray sum
209
0.445
Medium
3,557
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2166807/Python-Sliding-Window-(Thought-Process)
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: # Handle null/empty scenario if not nums: return 0 # Define start/end pointers, running counter start = 0 end = 0 counter = nums[0] # Since we're comparing minimums, start at infinity (positive) minimumLength = math.inf while end < len(nums): if counter >= target: # Calculate minimum length minimumLength = min(minimumLength, end - start + 1) # Subtract from counter counter -= nums[start] # Increment start of window start +=1 else: # Increment counter end += 1 # Increment end and add, if above target if end <= (len(nums) - 1): counter += nums[end] # Handle case where we never reach target amount return 0 if minimumLength == math.inf else minimumLength
minimum-size-subarray-sum
[Python] Sliding Window (Thought Process)
ernestshackleton
0
145
minimum size subarray sum
209
0.445
Medium
3,558
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2144806/Python-two-pointers
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: start = 0 end = -1 sum_ = 0 result = math.inf while end < len(nums): if sum_ < target: if end < len(nums) - 1: sum_ += nums[end + 1] end += 1 else: sum_ -= nums[start] start += 1 if sum_ >= target: result = min(result, end - start + 1) return result if result is not math.inf else 0
minimum-size-subarray-sum
Python, two pointers
blue_sky5
0
21
minimum size subarray sum
209
0.445
Medium
3,559
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2092765/O(n)-Time-Complexity-Python-Solution
class Solution: def minSubArrayLen(self, target, nums): res = float("inf") sumcheck = length = 0 for inx,num in enumerate(nums): sumcheck,length = sumcheck+num,length+1 if sumcheck >= target: #while subtracting elements from the left doesn't unsatisfy the constraint while (valcheck := sumcheck-nums[inx-length+1]) >= target: sumcheck = valcheck length -= 1 res = min(res,length) return res if res != float("inf") else 0
minimum-size-subarray-sum
O(n) Time Complexity Python Solution
tomaetotomahto
0
87
minimum size subarray sum
209
0.445
Medium
3,560
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2080577/Python-or-Easy-Solution-Using-Two-Pointer
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: # ///// TC: O(N) and SC: O(1) //////// l,total = 0,0 res = float('inf') for r in range(len(nums)): total += nums[r] while total >= target: res = min(res,(r-l+1)) total -= nums[l] l += 1 return 0 if res == float('inf') else res
minimum-size-subarray-sum
Python | Easy Solution Using Two Pointer
__Asrar
0
95
minimum size subarray sum
209
0.445
Medium
3,561
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/2065685/Python-3-or-Sliding-Window-or-faster-than-93.43
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: res = math.inf l = r = s = 0 while r < len(nums): s += nums[r] if s >= target: while l <= r and s >= target: s -= nums[l] l += 1 res = min(res, r - l + 2) r += 1 return res if res < math.inf else 0
minimum-size-subarray-sum
Python 3 | Sliding Window | faster than 93.43%
anels
0
27
minimum size subarray sum
209
0.445
Medium
3,562
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/1923041/5-Lines-Python-Solution-oror-99-Faster-oror-Memory-less-than-60
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: l=0 ; sm=0 ; ans=len(nums)+1 for r in range(len(nums)): sm+=nums[r] while sm>=target: ans=min(ans,r-l+1) ; sm-=nums[l] ; l+=1 return 0 if ans>len(nums) else ans
minimum-size-subarray-sum
5-Lines Python Solution || 99% Faster || Memory less than 60%
Taha-C
0
98
minimum size subarray sum
209
0.445
Medium
3,563
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/1856292/Python-(Simple-Approach-and-Beginner-friendly)
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: total = 0 mini = float('inf') j = 0 for i in range(len(nums)): total+=nums[i] while total >= target: mini = min(mini, len(nums[j:i+1])) total-=nums[j] j+=1 return 0 if mini == float('inf') else mini ############## WORKS BUT TIME EXCEEDS FOR SOME TEST CASES ################### # arr = [] # for i in range(0, len(nums)): # for j in range(i+1, len(nums)+1): # if sum(nums[i:j]) >= target: # arr.append(len(nums[i:j])) # return min(arr) if arr else 0
minimum-size-subarray-sum
Python (Simple Approach and Beginner-friendly)
vishvavariya
0
75
minimum size subarray sum
209
0.445
Medium
3,564
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/1834369/Python-easy-to-read-and-understand-or-sliding-window
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: ans, i, sums = float("inf"), 0, 0 for j in range(len(nums)): sums += nums[j] while sums >= target: ans = min(ans, j-i+1) sums -= nums[i] i = i+1 return 0 if ans == float("inf") else ans
minimum-size-subarray-sum
Python easy to read and understand | sliding window
sanial2001
0
141
minimum size subarray sum
209
0.445
Medium
3,565
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/1801655/Python-Single-Loop-Sliding-Window-11-LoC
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: i, j, runningSum = 0, 0, 0 minLen = sys.maxsize while j < len(nums): if runningSum + nums[j] >= target: minLen = min(minLen, j - i + 1) runningSum -= nums[i] i += 1 else: runningSum += nums[j] j += 1 return minLen if minLen != sys.maxsize else 0
minimum-size-subarray-sum
Python - Single Loop Sliding Window - 11 LoC
olsonj
0
92
minimum size subarray sum
209
0.445
Medium
3,566
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/1712179/Two-pointers-and-binary-search
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: left = 0 sum_ = 0 count = len(nums) for right in range(len(nums)): sum_ += nums[right] if sum_<target: continue while sum_>=target and left<=right: sum_ -= nums[left] left += 1 count = min(count, right-left+2) if left==0 and sum_<target: return 0 else: return count
minimum-size-subarray-sum
Two pointers and binary search
michaelniki
0
35
minimum size subarray sum
209
0.445
Medium
3,567
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/1712179/Two-pointers-and-binary-search
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: prefix_sum = [0] for n in nums: prefix_sum.append(prefix_sum[-1] + n) res = inf for start in range(len(prefix_sum) - 1): left, right = start, len(prefix_sum) - 1 while left < right: mid = left + (right - left) // 2 if prefix_sum[mid] - prefix_sum[start] >= target: right = mid else: left = mid + 1 if prefix_sum[right] - prefix_sum[start] >= target: res = min(res, right - start) return res if res != inf else 0
minimum-size-subarray-sum
Two pointers and binary search
michaelniki
0
35
minimum size subarray sum
209
0.445
Medium
3,568
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/1692536/Python-faster-than-99.6-with-only-one-loop
class Solution: def minSubArrayLen(self, s: int, nums: List[int]) -> int: i = j = 0 length = len(nums) lastIndex = length - 1 minimum = length summ = nums[i] while (i < length): if (nums[i] >= s): return 1 if (j < lastIndex and summ < s): j += 1 summ += nums[j] elif (j < length and summ >= s): minimum = min(minimum, j-i+1) summ -= nums[i] i += 1 else: # same as elif (j == length and sum(nums[i:j+1]) < s): break if (i == 0): # when the sum of whole array is less than target value return 0 return minimum
minimum-size-subarray-sum
Python faster than 99.6%, with only one loop
hikoichihara
0
158
minimum size subarray sum
209
0.445
Medium
3,569
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/1468233/Python3-Sliding-window-solution-O(n)
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: begin, cur_sum = 0, 0 _min = len(nums) + 1 for end in range(len(nums)): cur_sum += nums[end] while cur_sum >= target: _min = min(_min, end - begin + 1) cur_sum -= nums[begin] begin += 1 if _min > len(nums): return 0 return _min
minimum-size-subarray-sum
[Python3] Sliding window solution O(n)
maosipov11
0
37
minimum size subarray sum
209
0.445
Medium
3,570
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/1231620/Detailed-explanation-using-two-pointers-faster-than-99-submission
class Solution: def minSubArrayLen(self, s: int, nums: List[int]) -> int: slow = 0 fast = 1 curr_sum = nums[0] res = len(nums) + 1 n = len(nums) while fast < n: if curr_sum >= s: res = min(res, fast-slow) curr_sum -= nums[slow] slow += 1 else: curr_sum += nums[fast] fast += 1 while slow < n and curr_sum >= s: res = min(res, fast-slow) curr_sum -= nums[slow] slow +=1 return res if res != len(nums) + 1 else 0
minimum-size-subarray-sum
Detailed explanation using two pointers, faster than 99% submission
PatrickPro2
0
58
minimum size subarray sum
209
0.445
Medium
3,571
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/1138542/python-solution-(faster-than-99.5-solutions)
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: start=0 end=0 n=len(nums) curr_len=n+1 curr=0 while(end<n): while(curr<target and end<n): curr+=nums[end] end+=1 while(curr>=target and start<n): if end-start<curr_len: curr_len=end-start curr-=nums[start] start+=1 return curr_len if curr_len!=n+1 else 0
minimum-size-subarray-sum
python solution (faster than 99.5% solutions)
samarthnehe
0
236
minimum size subarray sum
209
0.445
Medium
3,572
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/1110558/Python3-solution
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: result: Union[float, int] = float('inf') left: int = 0 cur_sum: int = 0 for i in range(len(nums)): cur_sum += nums[i] while cur_sum >= target: result = min(result, i + 1 - left) cur_sum -= nums[left] left += 1 return result if result != float('inf') else 0
minimum-size-subarray-sum
Python3 solution
alexforcode
0
115
minimum size subarray sum
209
0.445
Medium
3,573
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/1095463/Python-solutions
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: left = summ = 0 res = float('inf') for i in range(len(nums)): summ += nums[i] while(summ >= target): res = min(res, i+1-left) summ -= nums[left] left += 1 return res if res != float('inf') else 0
minimum-size-subarray-sum
Python solutions
ginaaiusing
0
285
minimum size subarray sum
209
0.445
Medium
3,574
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/978970/Python-faster-than-96
class Solution: def minSubArrayLen(self, s: int, nums: List[int]) -> int: result = float('inf') left = 0 total = 0 for i in range(len(nums)): total += nums[i] while total >= s: #result = min(result, i+1 - left) if result > i+1-left: result = i+1-left total -= nums[left] left+=1 return result if result!=float('inf') else 0
minimum-size-subarray-sum
Python faster than 96%
Skywalker5423
0
321
minimum size subarray sum
209
0.445
Medium
3,575
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/862306/TWO-POINTER-SOLUTION-EXPLAINED-PYTHON
class Solution: def minSubArrayLen(self, s: int, nums: List[int]) -> int: n = len(nums) if not n: return 0 left = right = 0 answer = float('inf') total = 0 while right < n: total += nums[right] if total >= s: answer = min(answer, right-left+1) while total >= s: total -= nums[left] left += 1 if total >= s: answer = min(answer, right-left+1) right += 1 return answer if answer != float('inf') else 0
minimum-size-subarray-sum
TWO POINTER SOLUTION EXPLAINED PYTHON
nyc_coder
0
43
minimum size subarray sum
209
0.445
Medium
3,576
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/734704/Python3-sliding-window
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: ans = inf ii = 0 for i, x in enumerate(nums): target -= x while ii <= i and target <= 0: ans = min(ans, i - ii + 1) target += nums[ii] ii += 1 return ans if ans < inf else 0
minimum-size-subarray-sum
[Python3] sliding window
ye15
0
99
minimum size subarray sum
209
0.445
Medium
3,577
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/495388/Python3-O(n)-solution-using-two-pointers
class Solution: def minSubArrayLen(self, s: int, nums: List[int]) -> int: if s in nums: return 1 res,n,left_index,sums = float("inf"),len(nums),0,0 for i in range(n): sums += nums[i] while s<=sums: res=min(res,i+1-left_index) sums -= nums[left_index] left_index+=1 return res if res!=float("inf") else 0
minimum-size-subarray-sum
Python3 O(n) solution using two pointers
jb07
0
94
minimum size subarray sum
209
0.445
Medium
3,578
https://leetcode.com/problems/minimum-size-subarray-sum/discuss/1190414/python3-Two-pointers-easy
class Solution: def minSubArrayLen(self, target: int, nums: List[int]) -> int: lb = 0 ub = 0 wSum = nums[0] numLen = len(nums) ans = [] while lb<numLen: # print(lb, ub, wSum) if wSum >= target: ans.append(ub-lb+1) if wSum < target and ub+1< numLen: ub+=1 wSum += nums[ub] else: wSum -= nums[lb] lb+=1 # print(ans) if ans: return min(ans) return 0
minimum-size-subarray-sum
python3 Two pointers easy
GC_in
-1
230
minimum size subarray sum
209
0.445
Medium
3,579
https://leetcode.com/problems/course-schedule-ii/discuss/1327646/Elegant-Python-DFS
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: # Handle edge case. if not prerequisites: return [course for course in range(numCourses)] # 'parents' maps each course to a list of its pre # -requisites. parents = {course: [] for course in range(numCourses)} for course, prerequisite in prerequisites: parents[course].append(prerequisite) topological_order = [] visited, current_path = [False]*numCourses, [False]*numCourses # Returns False if the digraph rooted at 'course' # is acyclic, else, appends courses to 'topological # _order' in topological order and returns True. def dfs(course): if current_path[course]: return False if visited[course]: return True visited[course], current_path[course] = True, True if parents[course]: for parent in parents[course]: if not dfs(parent): return False topological_order.append(course) current_path[course] = False return True for course in range(numCourses): if not dfs(course): return [] return topological_order
course-schedule-ii
Elegant Python DFS
soma28
4
467
course schedule ii
210
0.481
Medium
3,580
https://leetcode.com/problems/course-schedule-ii/discuss/1642387/Python3-ITERATIVE-TOPOSORT-(-_-)-Explained
class Solution: def findOrder(self, numCourses: int, pr: List[List[int]]) -> List[int]: # Build adjacency list adj = defaultdict(list) for a, b in prerequisites: adj[b].append(a) # TopoSort topo = list() vis = set() processed = set() for node in range(numCourses): if node in vis: continue st = [node] while st: cur = st[-1] vis.add(cur) if cur in processed: st.pop() continue for ch in adj[cur]: if not ch in vis: st.append(ch) if cur == st[-1]: topo.append(st.pop()) processed.add(cur) # Result res = [] i = 0 pos = dict() while topo: node = topo.pop() pos[node] = i i += 1 res.append(node) # Check for cycles for parent, children in adj.items(): for child in children: if pos[parent] > pos[child]: return [] return res
course-schedule-ii
✔️ [Python3] ITERATIVE TOPOSORT (´-_ゝ-`), Explained
artod
3
170
course schedule ii
210
0.481
Medium
3,581
https://leetcode.com/problems/course-schedule-ii/discuss/822651/Python3-DFS-and-BFS
class Solution: def findOrder(self, numCourses: int, prerequisites): # DFS 用递归 # 先找到 上了某门课以后可以解锁的全后置课,放入dict neighborNode 中 # 再做一个 status dict, 用来记录查找的状态, 默认value 0 代表没访问过 # dfs 更改 status, 0 代表没访问; 1 代表访问中; 2 代表访问过 # 如果递归遇到1,表示已成环,则无法上完所有课,返回 false;否则递归更新上课顺序在 result 里 from collections import deque result=deque([]) neighborNodes = collections.defaultdict(list) status = collections.defaultdict(int) for nodeTo,nodeFrom in prerequisites: neighborNodes[nodeFrom].append(nodeTo) def dfs(node): if status[node]==1: return False # 成环了,无法上完所有课 if status[node]: return #如果访问过了,退出 status[node] = 1 #没访问过,递归,把顺序 appendleft 加入deque中 for next_node in neighborNodes[node]: if dfs(next_node) == False: return False status[node] = 2 result.appendleft(node) for node in range(numCourses): if dfs(node) == False: return [] return result
course-schedule-ii
Python3 DFS and BFS
meiyaowen
2
90
course schedule ii
210
0.481
Medium
3,582
https://leetcode.com/problems/course-schedule-ii/discuss/822651/Python3-DFS-and-BFS
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: # BFS 用deque from collections import deque q = deque([]) result = deque([]) inDegree = [0]*numCourses neighborNodes = collections.defaultdict(list) # 计算每一门课的入度, 找到 每一门 course 可以解锁的课程 for nodeTo, nodeFrom in prerequisites: inDegree[nodeTo] +=1 neighborNodes[nodeFrom].append(nodeTo) # 将入度=0 的课程放入 deque 中,可以先上 for node in range(numCourses): if not inDegree[node]: q.append(node) while q: node = q.pop() result.append(node) for next_node in neighborNodes[node]: inDegree[next_node] -=1 if not inDegree[next_node]: q.append(next_node) # 如果有环,则 上过课的数量会小于 课程总数,返回[] if len(result) == numCourses: return result return []
course-schedule-ii
Python3 DFS and BFS
meiyaowen
2
90
course schedule ii
210
0.481
Medium
3,583
https://leetcode.com/problems/course-schedule-ii/discuss/2368808/Python-Easy-Short-Optimal-or-Simple-DFS-or-94-time-percentile
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: preq = defaultdict(list) for x in prerequisites: preq[x[0]] += [x[1]] order = [] visited = {} def isCycleDFS(node): if node in visited: return visited[node] visited[node] = True for n in preq[node]: if isCycleDFS(n): return True visited[node] = False order.append(node) return False for i in range(numCourses): if isCycleDFS(i): return [] return order
course-schedule-ii
[Python] Easy, Short, Optimal | Simple DFS | 94% time percentile
LongQ
1
42
course schedule ii
210
0.481
Medium
3,584
https://leetcode.com/problems/course-schedule-ii/discuss/2314708/Python-Simple-Solution-2-Dicts-%2B-BFS
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: if numCourses <= 0: return [] inDegree = {} adjList = {} for i in range(numCourses): inDegree[i] = 0 adjList[i] = [] for child, parent in prerequisites: adjList[parent].append(child) inDegree[child] += 1 q = deque() for i in range(numCourses): if inDegree[i] == 0: q.append(i) order = [] visit = set() while len(q) > 0: cur = q.popleft() order.append(cur) visit.add(cur) for n in adjList[cur]: inDegree[n] -= 1 if n not in visit and inDegree[n] == 0: q.append(n) if len(order) == numCourses: return order return []
course-schedule-ii
Python - Simple Solution - 2 Dicts + BFS
worldofthomas
1
29
course schedule ii
210
0.481
Medium
3,585
https://leetcode.com/problems/course-schedule-ii/discuss/1753718/Clean-Python-Topological-Sort-Solution
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: graph = {i:[] for i in range(numCourses)} in_degree = {i: 0 for i in range(numCourses)} for dest, prev in prerequisites: graph[prev].append(dest) in_degree[dest] += 1 course_chose, ans = 0, [] queue = collections.deque() for node, value in in_degree.items(): if value == 0: queue.append(node) while queue: curr_node = queue.popleft() course_chose += 1 ans.append(curr_node) for dest in graph[curr_node]: in_degree[dest] -= 1 if in_degree[dest] == 0: queue.append(dest) if course_chose != numCourses: return [] return ans
course-schedule-ii
Clean Python Topological Sort Solution
Chingtat27
1
119
course schedule ii
210
0.481
Medium
3,586
https://leetcode.com/problems/course-schedule-ii/discuss/1672343/Python3-BFS-98.2-or-Detailed-Explained-or-Beginner-Friendly
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: # init DAG: Course pre -> Course d = defaultdict(list) # indegree list: there are # courses as pre-requisites for takign Course A indeg = [0] * numCourses # c: course; p: pre for course for c, p in prerequisites: d[p].append(c) # p -> c will increase the indegree of c indeg[c] += 1 # BFS queue: enque all the 0 indegree courses q = deque([i for i, x in enumerate(indeg) if x == 0]) # milestone check, good habit # print(q) # learning path ans = [] while q: cur = q.popleft() # add it to our learning path ans.append(cur) # apply BFS to cur can yield the affected courses, decrease their indegree by 1 for c in d[cur]: indeg[c] -= 1 # if the indegree reach 0, enque if indeg[c] == 0: q.append(c) return ans if len(ans) == numCourses else []
course-schedule-ii
Python3 BFS 98.2% | Detailed Explained | Beginner Friendly
doneowth
1
70
course schedule ii
210
0.481
Medium
3,587
https://leetcode.com/problems/course-schedule-ii/discuss/1643809/Python3-(Beats-95)-Intuitive-%2B-Easy-to-Understand-%2B-Comments-or-BFS
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: cToP = {c: 0 for c in range(numCourses)} # Maps course to number of prerequisites pToC = {p: [] for p in range(numCourses)} # Maps prerequisite to list of courses for c, p in prerequisites: cToP[c] += 1 pToC[p].append(c) # We should start with courses with no prerequisites and then continue (BFS) coursesToTake = [c for c, pS in cToP.items() if not pS] res = [] while coursesToTake: res.extend(coursesToTake) nextCoursesToTake = [] for p in coursesToTake: for c in pToC[p]: cToP[c] -= 1 if not cToP[c]: nextCoursesToTake.append(c) coursesToTake = nextCoursesToTake return res if not any(cToP.values()) else [] # Return result if all courses have 0 prerequisites else return an empty list
course-schedule-ii
[Python3] (Beats 95%) Intuitive + Easy to Understand + Comments | BFS
PatrickOweijane
1
180
course schedule ii
210
0.481
Medium
3,588
https://leetcode.com/problems/course-schedule-ii/discuss/1583778/Python3-or-Faster-%3A-95.06-or-Recursive-Approach
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: def dfs(node, seen): if node in seen: self.cycle = True else: if not self.visited[node]: self.visited[node] = True seen.add(node) if node in self.dict_: for pre_course in self.dict_[node]: if self.cycle: break dfs(pre_course, seen) self.final.append(node) seen.remove(node) self.visited = [False]*numCourses self.dict_ = dict() self.cycle = False self.final = [] for course, pre_course in prerequisites: if course not in self.dict_: self.dict_[course] = [pre_course] else: self.dict_[course].append(pre_course) for course in range(numCourses): if self.cycle: return [] dfs(course, set()) return self.final
course-schedule-ii
Python3 | Faster : 95.06 | Recursive Approach
Call-Me-AJ
1
219
course schedule ii
210
0.481
Medium
3,589
https://leetcode.com/problems/course-schedule-ii/discuss/824281/Q269-Alien-Dictionary-BFS
class Solution: def alienOrder(self, words: List[str]) -> str: # BFS # https://leetcode-cn.com/problems/alien-dictionary/solution/python3-tuo-bu-pai-xu-by-bbqq-2/ neighborNodes = collections.defaultdict(list) queue = collections.deque([]) result = collections.deque([]) #初始化入度表 str = "".join(words) inDegree = dict.fromkeys(set(str), 0) #每两个互相比, 更新 neighborNode, 和 入度表 for i in range(len(words)-1): w1=words[i] w2=words[i+1] minlen = min(len(w1),len(w2)) for j in range(minlen): if w1[j] == w2[j]: if j == minlen-1 and len(w1) > len(w2): # 如果两个字符串完全相同,但是第一个比第二个长, return "" # 则认为是不合法的,返回空 else: pass else: # 否则只有第一个不同的字母间有 topo order neighborNodes[w1[j]].append(w2[j]) inDegree[w2[j]]+=1 break # 把入度为0的字幕放入 queue 中 for key in inDegree: if inDegree[key] == 0: queue.append(key) # 每次弹出一个字母,之后的node入度-1 while queue: node = queue.pop() result.append(node) for next_node in neighborNodes[node]: inDegree[next_node]-=1 if inDegree[next_node]==0: queue.append(next_node) if len(result) != len(inDegree): return "" else: return "".join(result)
course-schedule-ii
Q269 Alien Dictionary BFS
meiyaowen
1
101
course schedule ii
210
0.481
Medium
3,590
https://leetcode.com/problems/course-schedule-ii/discuss/735092/Python3-tri-color-approach
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: graph = {} for u, v in prerequisites: graph.setdefault(v, []).append(u) def fn(x): """Return True if cycle is deteced.""" if visited[x]: return visited[x] == 1 visited[x] = 1 for xx in graph.get(x, []): if fn(xx): return True ans.append(x) # collect values visited[x] = 2 return False ans = [] visited = [0]*numCourses for x in range(numCourses): if fn(x): return [] return ans[::-1]
course-schedule-ii
[Python3] tri-color approach
ye15
1
183
course schedule ii
210
0.481
Medium
3,591
https://leetcode.com/problems/course-schedule-ii/discuss/735092/Python3-tri-color-approach
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: graph = [[] for _ in range(numCourses)] indeg = [0] * numCourses for v, u in prerequisites: graph[u].append(v) indeg[v] += 1 ans = [] for i, x in enumerate(indeg): if x == 0: ans.append(i) for u in ans: for v in graph[u]: indeg[v] -= 1 if indeg[v] == 0: ans.append(v) return ans if len(ans) == numCourses else []
course-schedule-ii
[Python3] tri-color approach
ye15
1
183
course schedule ii
210
0.481
Medium
3,592
https://leetcode.com/problems/course-schedule-ii/discuss/342214/Python3-100-DFS-solution-100ms
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: # create graph graph = [[] for _ in range(numCourses)] for pre in prerequisites: graph[pre[0]].append(pre[1]) ans = [] seen = [0 for _ in range(numCourses)] # dfs def topSort(node, graph, seen, ans): if (seen[node] != 0): return seen[node] seen[node] = -1 # mark as seen for neigh in graph[node]: if(topSort(neigh, graph, seen, ans)==-1): return -1 ans.append(node) seen[node] = 1 # done without cycle return 0 for i in range(numCourses): if (seen[i] == 0): if (topSort(i, graph, seen, ans)==-1): # cycle return [] return ans
course-schedule-ii
[Python3] 100% DFS solution 100ms
PrGxw
1
124
course schedule ii
210
0.481
Medium
3,593
https://leetcode.com/problems/course-schedule-ii/discuss/2833655/Python3-Beats-75-Double-Dictionaries
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: needed = {i:set() for i in range(numCourses)} satisfies = {i:set() for i in range(numCourses)} for [a, b] in prerequisites: needed[b].add(a) satisfies[a].add(b) look_at = set([i for i in range(numCourses)]) done = set() ret= [] while look_at: cc = look_at.pop() if cc in done or len(satisfies[cc]): continue ret.append(cc) done.add(cc) for i in needed[cc]: look_at.add(i) satisfies[i].remove(cc) if len(ret) < numCourses: return [] return ret
course-schedule-ii
Python3 Beats 75% Double Dictionaries
godshiva
0
2
course schedule ii
210
0.481
Medium
3,594
https://leetcode.com/problems/course-schedule-ii/discuss/2826124/Easy-understand-solution
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: routes = collections.defaultdict(list) need = collections.defaultdict(set) lst = [0] * numCourses for premise in prerequisites: lst[premise[0]] += 1 routes[premise[1]].append(premise[0]) need[premise[0]].add(premise[1]) queue = collections.deque() answer = [] seen = set() for ind in range(numCourses): if lst[ind] == 0: answer.append(ind) queue.append(ind) while queue: cur = queue.popleft() lst = routes[cur] seen.add(cur) for item in lst: if len(need[item].difference(seen)) == 0: queue.append(item) answer.append(item) if len(answer) == numCourses: return answer return []
course-schedule-ii
Easy understand solution
lllymka
0
4
course schedule ii
210
0.481
Medium
3,595
https://leetcode.com/problems/course-schedule-ii/discuss/2822539/Python3-Both-BFS-and-DFS-methods
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:. self.graph = [[] for _ in range(numCourses)] # Directed graph. index = from. value = to. self.visited = [False] * numCourses self.onPath = [False] * numCourses self.postOrder = [] self.hasCycle = False for prerequisity in prerequisites: self.graph[prerequisity[1]].append(prerequisity[0]) # Build graph for i in range(numCourses): # In case there's non-connected graph, we need to loop all graphs self.dfs(i) if self.hasCycle: return [] return self.postOrder[::-1] # DO NOT Return postOrder.reverse() cause reverse() function return void... def dfs(self, node): if self.onPath[node]: # node already on the path -> means there's a cycle. self.hasCycle = True return if self.visited[node] or self.hasCycle: # visited -> the sub-graph has been checked. hasCycle -> find a cycle, we can return earlier. return self.visited[node] = True self.onPath[node] = True for neigh in self.graph[node]: self.dfs(neigh) self.postOrder.append(node) self.onPath[node] = False return
course-schedule-ii
[Python3] Both BFS and DFS methods
Cceline00
0
6
course schedule ii
210
0.481
Medium
3,596
https://leetcode.com/problems/course-schedule-ii/discuss/2822106/cycle-check-with-dos-in-python
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: if prerequisites == []: return range(numCourses) graph = [[] for i in range(numCourses)] for ls in prerequisites: graph[ls[1]].append(ls[0]) hasCycle = False visited = [False for i in range(numCourses)] onpath = visited.copy() seq = [] def traverse(n): nonlocal hasCycle if onpath[n]: hasCycle = True return if hasCycle or visited[n]: return onpath[n] = True visited[n] = True for i in graph[n]: traverse(i) seq.append(n) onpath[n] = False for i in range(numCourses): if not visited[i]: traverse(i) return seq[::-1] if not hasCycle else []
course-schedule-ii
cycle check with dos in python
ychhhen
0
3
course schedule ii
210
0.481
Medium
3,597
https://leetcode.com/problems/course-schedule-ii/discuss/2819063/Python-solution-or-DFS
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: prerequisite = defaultdict(list) ans = [] # 0 : Unchecked, 1: Checking, 2: Completed Status = [0] * numCourses for cur, pre in prerequisites: prerequisite[cur].append(pre) def LearnTheCourse(num): if Status[num] == 2: return True elif Status[num] == 1: return False else: Status[num] = 1 for pre in prerequisite[num]: if not LearnTheCourse(pre): return False ans.append(num) Status[num] = 2 return True for i in range(numCourses): if not LearnTheCourse(i): return [] return ans
course-schedule-ii
Python solution | DFS
maomao1010
0
5
course schedule ii
210
0.481
Medium
3,598
https://leetcode.com/problems/course-schedule-ii/discuss/2819060/Python-or-DAG-or-Topological-Sort
class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: adjlist = [[] for _ in range(numCourses)] for src, dst in prerequisites: adjlist[src].append(dst) visited = [-1]*numCourses departure = [-1]*numCourses topsort = [] def dfs(node): visited[node] = 1 for nbr in adjlist[node]: if visited[nbr] == -1: if dfs(nbr): return True else: if departure[nbr] == -1: return True departure[node] = 1 topsort.append(node) for node in range(numCourses): if visited[node] == -1: if dfs(node): return [] return topsort
course-schedule-ii
Python | DAG | Topological Sort
ajay_gc
0
3
course schedule ii
210
0.481
Medium
3,599