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/thousand-separator/discuss/806429/Python-String-manipulation
class Solution: def thousandSeparator(self, n: int) -> str: ans = [] num = str(n) for i, ch in enumerate(reversed(num)): ans.append(ch) if i > 0 and (i + 1) % 3 == 0 and i + 1 < len(num): ans.append('.') return ''.join(reversed(ans))
thousand-separator
[Python] String manipulation
hw11
0
37
thousand separator
1,556
0.549
Easy
23,000
https://leetcode.com/problems/thousand-separator/discuss/1474337/Easy-Python-Solution
class Solution: def thousandSeparator(self, n: int) -> str: n=str(n) res="" if len(str(n)) <4: return str(n) count=0 for i in range(len(n)-1,-1,-1): if count<3: res+=str(n[i]) count+=1 if count==3 and i!=0: res+="." count=0 return str(res[::-1])
thousand-separator
Easy Python Solution
sangam92
-2
96
thousand separator
1,556
0.549
Easy
23,001
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/1212672/Python-Easy-Solution-Count-of-Nodes-with-Zero-Incoming-Degree
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: if not edges: return [] incoming_degrees = {i: 0 for i in range(n)} for x, y in edges: incoming_degrees[y] += 1 result = [k for k, v in incoming_degrees.items() if v == 0] return result
minimum-number-of-vertices-to-reach-all-nodes
Python Easy Solution - Count of Nodes with Zero Incoming-Degree
ChidinmaKO
4
195
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,002
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/2738640/Simple-python-solution-with-explanation-oror-TC%3A-O(N)-SC%3A-O(N)
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: indegree=[0]*n for i,j in edges: indegree[j]+=1 lst=[] for i in range(n): if indegree[i]==0: lst.append(i) return lst
minimum-number-of-vertices-to-reach-all-nodes
Simple python solution with explanation || TC: O(N), SC: O(N)
beneath_ocean
3
110
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,003
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/2319945/Python3-nodes-with-no-in-degree
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: graph = defaultdict(set) visited = set() seen = set() for src,dest in edges: graph[src].add(dest) seen.add(dest) output = [] for i in range(n): if i not in seen: output.append(i) return output
minimum-number-of-vertices-to-reach-all-nodes
📌 Python3 nodes with no in-degree
Dark_wolf_jss
2
50
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,004
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/2319944/Python3-standard-DFS-traversal
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: graph = defaultdict(set) visited = set() result = set() for src,dest in edges: graph[src].add(dest) def dfs(src): visited.add(src) for dest in graph[src]: if dest not in visited: dfs(dest) elif dest in result: result.remove(dest) for i in range(n): if i not in visited: result.add(i) dfs(i) return result
minimum-number-of-vertices-to-reach-all-nodes
📌 Python3 standard DFS traversal
Dark_wolf_jss
1
43
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,005
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/2045218/Find-nodes-that-have-an-indegree-of-0
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: # find all nodes with indegree of 0, these are the vertices that you must start from and cant be reached by anything else # so thats the smallest set of vertices that allow for you to dfs over all nodes indegrees = [0 for _ in range(n)] for a, b in edges: indegrees[b] += 1 return [i for i in range(len(indegrees)) if indegrees[i] == 0]
minimum-number-of-vertices-to-reach-all-nodes
Find nodes that have an indegree of 0
normalpersontryingtopayrent
1
34
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,006
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/1910913/python3-or-DFS
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: graph = collections.defaultdict(list) for u, v in edges: graph[u].append(v) def dfs(vertex, visited: list, graph: dict, ans:list): visited[vertex] = True for node in graph[vertex]: if not visited[node]: dfs(node, visited, graph, ans) elif node in ans: ans.remove(node) visited = [False]*n ans = set() for i in range(n): if not visited[i]: dfs(i, visited, graph, ans) ans.add(i) return ans
minimum-number-of-vertices-to-reach-all-nodes
python3 | DFS
milannzz
1
47
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,007
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/1481409/Python3-O(n)-solution
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: seen = set([i for i in range(n)]) for edge in edges: if edge[1] in seen: seen.remove(edge[1]) return list(seen)
minimum-number-of-vertices-to-reach-all-nodes
[Python3] O(n) solution
maosipov11
1
56
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,008
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/1416721/Python3-or-A-readable-Solution-for-the-simple-man-or-97.47
class Solution: ''' Utilize a list from range 0 - (n-1) to determine whether a node is a destination ''' def __init__(self): self.isADestination = [] ''' The result for this problem are all nodes that are not destinations. ''' def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: self.checkIfNodeIsADestination(n, edges) res = [] for i in range(n): if not self.isADestination[i]: res.append(i) return res ''' Set the isADestination for nodeTo index to True for all edges ''' def checkIfNodeIsADestination(self, n: int, edges: List[List[int]]): self.isADestination = [False] * n for nodeFrom, nodeTo in edges: self.isADestination[nodeTo] = True
minimum-number-of-vertices-to-reach-all-nodes
Python3 | A readable Solution for the simple man | 97.47%
jermarino16
1
55
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,009
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/1033150/Python3-solution-using-set
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: s = set() for i in edges: s.add(i[1]) return set(range(0,n)).difference(s)
minimum-number-of-vertices-to-reach-all-nodes
Python3 solution using set
EklavyaJoshi
1
110
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,010
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/805853/Python3-1-line
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: return set(range(n)) - {v for _, v in edges}
minimum-number-of-vertices-to-reach-all-nodes
[Python3] 1-line
ye15
1
70
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,011
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/805853/Python3-1-line
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: indeg = [0]*n for _, v in edges: indeg[v] += 1 return [i for i, x in enumerate(indeg) if x == 0]
minimum-number-of-vertices-to-reach-all-nodes
[Python3] 1-line
ye15
1
70
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,012
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/805812/Python-or-Explained-or-Simply-find-nodes-which-have-no-edges-coming-into-them-or-In-Degree-approach
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: indegree_map = dict() for i in range(n): indegree_map[i] = 0 for edge in edges: indegree_map[edge[1]] += 1 output = [] for node in indegree_map: if indegree_map[node] == 0: output.append(node) return output
minimum-number-of-vertices-to-reach-all-nodes
Python | Explained | Simply find nodes which have no edges coming into them | In-Degree approach
bhavul
1
328
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,013
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/2843407/Python3-Solution-simple
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: xfrom = {i for i, n in edges} xto = {n for i, n in edges} return xfrom - xto # return list({i for i, n in edges if i not in [n for i, n in edges]})
minimum-number-of-vertices-to-reach-all-nodes
Python3 Solution - simple
sipi09
0
1
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,014
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/2827727/Python-with-nodes-not-reachable-appraoach
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: bools = [True] *n for edge in edges: bools[edge[1]] = False return [i for (i,v) in enumerate(bools) if v]
minimum-number-of-vertices-to-reach-all-nodes
Python with nodes not reachable appraoach
bharatmk89
0
3
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,015
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/2827655/Python-Solution-or-99-Faster-or-Set-Theory-%2B-Topological-Sorting
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: # nodes that have some incoming edges areChildrens = set(val for key, val in edges) # all nodes tillN = set(range(n)) # all - nodes with incoming = no incoming edge nodes return (tillN - areChildrens)
minimum-number-of-vertices-to-reach-all-nodes
Python Solution | 99% Faster | Set Theory + Topological Sorting
Gautam_ProMax
0
3
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,016
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/2796527/Python3%3A-Easy-to-understand
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: reachable = set() for source, dest in edges: reachable.add(dest) notreachable = set() for i in range(n): if i not in reachable: notreachable.add(i) return notreachable
minimum-number-of-vertices-to-reach-all-nodes
Python3: Easy to understand
mediocre-coder
0
14
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,017
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/2715991/bEATS-100-of-solutions
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: l=[0]*n for (i,j) in edges: l[j]+=1 return [i for i in range(n) if l[i]==0]
minimum-number-of-vertices-to-reach-all-nodes
bEATS 100% of solutions
2001640100048_2C
0
1
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,018
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/2567465/Very-Simple-Python3-Solution-Explained-or-Faster-than-95
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: roots = set(range(n)) for fr, to in edges: roots.discard(to) return roots
minimum-number-of-vertices-to-reach-all-nodes
Very Simple Python3 Solution Explained | Faster than 95%
ryangrayson
0
14
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,019
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/2036774/Python-easy-to-read-and-understand-or-DFS
class Solution: def dfs(self, graph, node, visit): visit.add(node) for nei in graph[node]: if nei not in visit: visit.add(nei) self.dfs(graph, nei, visit) elif nei in self.ans: self.ans.remove(nei) def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: graph = {i:[] for i in range(n)} for u, v in edges: graph[u].append(v) self.ans = set() visit = set() for i in range(n): if i not in visit: self.ans.add(i) self.dfs(graph, i, visit) return list(self.ans)
minimum-number-of-vertices-to-reach-all-nodes
Python easy to read and understand | DFS
sanial2001
0
66
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,020
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/1710032/Easy-solution-with-memory-usage-less-than-99.79-per-cent
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: g = {} for i in range(n): g[i] = 0 for i in edges: g[i[1]] += 1 b = [] for i in g: if g[i] == 0: b.append(i) return b
minimum-number-of-vertices-to-reach-all-nodes
Easy solution with memory usage less than 99.79 per cent
premansh2001
0
43
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,021
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/1690608/easy-to-understand-python-solution
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: arr = [0] * n ret = [] for edge in edges: arr[edge[1]] = 1 for i in range(n): if arr[i] == 0: ret.append(i) return ret
minimum-number-of-vertices-to-reach-all-nodes
easy to understand python solution
josejassojr
0
62
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,022
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/1603879/Python-easy-8-lines-code
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: reachable=[0]*n result=[] for edge in edges: reachable[edge[1]]+=1 for i in range(n): if reachable[i]==0: result.append(i) return result
minimum-number-of-vertices-to-reach-all-nodes
Python easy 8 lines code
diksha_choudhary
0
40
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,023
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/1582842/Python-3-9798-Generator-linear-solution
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: vertices_reachable = [False] * n for edge_from, edge_to in edges: vertices_reachable[edge_to] = True return (index for index, reachable in enumerate(vertices_reachable) if not reachable)
minimum-number-of-vertices-to-reach-all-nodes
Python 3 97/98% Generator linear solution
tamat
0
22
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,024
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/1341270/Python-4-Liner-solution-with-In-Degree-beats-93-time
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: in_degree = [0] * n for i in edges: in_degree[i[1]]+=1 return [x for x in range(n) if in_degree[x]==0]
minimum-number-of-vertices-to-reach-all-nodes
Python 4 Liner solution with In-Degree beats 93 % time
prajwal_vs
0
95
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,025
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/1330052/WEEB-DOES-PYTHON
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: inDegree = [0] * n for fromNode, toNode in edges: inDegree[toNode] += 1 result = [] for node in range(len(inDegree)): if inDegree[node] == 0: result.append(node) return result
minimum-number-of-vertices-to-reach-all-nodes
WEEB DOES PYTHON
Skywalker5423
0
62
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,026
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/1223670/Python3-O(n)-solution-with-explanation
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: # We need to find all the vertex whose incoming edge is zero # set of all vertex setOfAllVertex = set(range(n)) # vertex having incoming edge v = set() for edge in edges: # [x,y]=x->y, therefore y has incoming edge v.add(edge[1]) # Find all the vertex with zero incoming edge # vertex in setOfAllVertex which are not in v has zero incoming edges ans = setOfAllVertex-v return ans
minimum-number-of-vertices-to-reach-all-nodes
Python3 O(n) solution with explanation
werfree
0
89
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,027
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/1155756/Simple-Python3-solution-with-no-inbound-traffics
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: # return nodes that do not have any inbound traffic unreached = set(i for i in range(n)) for out_node, in_node in edges: if in_node in unreached: unreached.remove(in_node) return list(unreached)
minimum-number-of-vertices-to-reach-all-nodes
Simple Python3 solution with no inbound traffics
tkuo-tkuo
0
41
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,028
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/829294/Intuitive-approach-by-searching-node-with-indegree-as-zero
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: is_head_dict = {i:True for i in range(n)} for s, e in edges: is_head_dict[e] = False return list(map(lambda t: t[0], filter(lambda t: t[1], is_head_dict.items())))
minimum-number-of-vertices-to-reach-all-nodes
Intuitive approach by searching node with indegree as zero
puremonkey2001
0
35
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,029
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/805688/Simple-Python-Solution
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: d = {} ans = [] for x,y in edges: if y not in d: d[y] = [x] else: d[y].append(x) for x in range(n): if x not in d: ans.append(x) return ans
minimum-number-of-vertices-to-reach-all-nodes
Simple Python Solution
spec_he123
0
101
minimum number of vertices to reach all nodes
1,557
0.796
Medium
23,030
https://leetcode.com/problems/minimum-numbers-of-function-calls-to-make-target-array/discuss/807358/Python-Bit-logic-Explained
class Solution: def minOperations(self, nums: List[int]) -> int: return sum(bin(a).count('1') for a in nums) + len(bin(max(nums))) - 2 - 1
minimum-numbers-of-function-calls-to-make-target-array
Python Bit logic Explained
akhil_ak
3
125
minimum numbers of function calls to make target array
1,558
0.642
Medium
23,031
https://leetcode.com/problems/minimum-numbers-of-function-calls-to-make-target-array/discuss/1337405/Python3-simple-solution
class Solution: def minOperations(self, nums: List[int]) -> int: x = sum(nums) count = 0 while x != 0: for i in range(len(nums)): if nums[i] % 2 != 0: count += 1 x -= 1 if x != 0: for i in range(len(nums)): if nums[i] != 0: nums[i] //= 2 x -= nums[i] count += 1 return count
minimum-numbers-of-function-calls-to-make-target-array
Python3 simple solution
EklavyaJoshi
1
58
minimum numbers of function calls to make target array
1,558
0.642
Medium
23,032
https://leetcode.com/problems/minimum-numbers-of-function-calls-to-make-target-array/discuss/2206792/Python-easy-to-read-and-understand-or-BFS
class Solution: def solve(self, target): n = len(target) nums = [0] * n q = [nums] ans = 0 visit = set() nums = [str(i) for i in nums] visit.add(''.join(nums)) while q: num = len(q) for i in range(num): arr = q.pop(0) if arr == target: return ans for j in range(len(arr)): temp = arr[::] temp[j] = arr[j] + 1 # print(temp) x = [str(p) for p in temp] visit_check = ''.join(x) if visit_check not in visit: visit.add(visit_check) q.append(temp) temp = [val * 2 for val in arr] x = [str(p) for p in temp] visit_check = ''.join(x) if visit_check not in visit: visit.add(visit_check) q.append(temp) if q: ans += 1
minimum-numbers-of-function-calls-to-make-target-array
Python easy to read and understand | BFS
sanial2001
0
28
minimum numbers of function calls to make target array
1,558
0.642
Medium
23,033
https://leetcode.com/problems/minimum-numbers-of-function-calls-to-make-target-array/discuss/1395188/Python3-solution-or-explained
class Solution: def minOperations(self, nums: List[int]) -> int: count = 0 n = len(nums) if max(nums) == 0: return 0 while max(nums) != 0: for i in range(n): if nums[i] % 2 == 1: nums[i] -= 1 count += 1 for i in range(n): nums[i] //= 2 count += 1 return count - 1
minimum-numbers-of-function-calls-to-make-target-array
Python3 solution | explained
FlorinnC1
0
92
minimum numbers of function calls to make target array
1,558
0.642
Medium
23,034
https://leetcode.com/problems/minimum-numbers-of-function-calls-to-make-target-array/discuss/806621/Python3-recursive-(6-line)
class Solution: def minOperations(self, nums: List[int]) -> int: ans = 0 for i in range(len(nums)): if nums[i] &amp; 1: nums[i] -= 1 ans += 1 return ans if all(x == 0 for x in nums) else ans + 1 + self.minOperations([x//2 for x in nums])
minimum-numbers-of-function-calls-to-make-target-array
[Python3] recursive (6-line)
ye15
0
31
minimum numbers of function calls to make target array
1,558
0.642
Medium
23,035
https://leetcode.com/problems/minimum-numbers-of-function-calls-to-make-target-array/discuss/806621/Python3-recursive-(6-line)
class Solution: def minOperations(self, nums: List[int]) -> int: return sum(bin(x).count("1") for x in nums) + len(bin(max(nums))) - 3
minimum-numbers-of-function-calls-to-make-target-array
[Python3] recursive (6-line)
ye15
0
31
minimum numbers of function calls to make target array
1,558
0.642
Medium
23,036
https://leetcode.com/problems/detect-cycles-in-2d-grid/discuss/806630/Python3-memoized-dfs-with-a-direction-parameter-(16-line)
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: m, n = len(grid), len(grid[0]) @lru_cache(None) def fn(i, j, d): """Traverse the grid to find cycle via backtracking.""" if grid[i][j] != "BLACK": val = grid[i][j] grid[i][j] = "GRAY" # mark visited in this trial for ii, jj, dd in ((i-1, j, -2), (i, j-1, -1), (i, j+1, 1), (i+1, j, 2)): if 0 <= ii < m and 0 <= jj < n and d + dd != 0: # in range &amp; not going back if grid[ii][jj] == "GRAY": return True #cycle found if grid[ii][jj] == val: fn(ii, jj, dd) grid[i][j] = val for i in range(m): for j in range(n): if fn(i, j, 0): return True grid[i][j] = "BLACK" # mark "no cycle" return False
detect-cycles-in-2d-grid
[Python3] memoized dfs with a direction parameter (16-line)
ye15
1
75
detect cycles in 2d grid
1,559
0.48
Medium
23,037
https://leetcode.com/problems/detect-cycles-in-2d-grid/discuss/2840881/Python-3-DFS-fast-solution-with-comments
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: visited, visited_cur = set(), set() stack = deque() row_n = len(grid) col_n = len(grid[0]) for row, row_g in enumerate(grid): for col, val in enumerate(row_g): if (row, col) not in visited: # if new cell # add to stack current cell and previous cell # we don't have previous cell, so replace it to -1, -1 stack.append([row, col, -1, -1]) visited_cur.clear() while stack: r, c, r_prv, c_prv = stack.pop() if (r, c) in visited_cur: return True # we saw this cell before -> cycle visited_cur.add((r, c)) for d_r, d_c in [[-1, 0], [0, -1], [1, 0], [0, 1]]: # we exclude previous cell from addition to stack if 0 <= r + d_r < row_n and (r + d_r, c + d_c) != (r_prv, c_prv) and \ 0 <= c + d_c < col_n and grid[r + d_r][c + d_c] == val: stack.append([r + d_r, c + d_c, r, c]) visited.update(visited_cur) # add current set to general set return False
detect-cycles-in-2d-grid
Python 3 - DFS - fast solution with comments
noob_in_prog
0
2
detect cycles in 2d grid
1,559
0.48
Medium
23,038
https://leetcode.com/problems/detect-cycles-in-2d-grid/discuss/2597264/Cycle-Detection-In-an-Undirected-Graph-Python-Solution
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: def bfs(row,col,visited): visited[row][col] = 1 queue = [[[row,col],[-1,-1]]] while queue: popped = queue.pop(0) row, col = popped[0][0], popped[0][1] pr, pc = popped[1][0], popped[1][1] val = grid[row][col] for i in range(4): nrow = row + delrow[i] ncol = col + delcol[i] if nrow >= 0 and nrow < n and ncol >= 0 and ncol < m and grid[nrow][ncol] == val: if not visited[nrow][ncol]: visited[nrow][ncol] = 1 queue.append([[nrow,ncol],[row,col]]) elif pr != nrow and pc != ncol: return True return False n = len(grid) m = len(grid[0]) delrow = [-1,0,1,0] delcol = [0,1,0,-1] visited = [[0 for _ in range(m)] for _ in range(n)] for i in range(n): for j in range(m): if not visited[i][j]: if bfs(i,j,visited): return True return False
detect-cycles-in-2d-grid
Cycle Detection In an Undirected Graph - Python Solution
abroln39
0
18
detect cycles in 2d grid
1,559
0.48
Medium
23,039
https://leetcode.com/problems/detect-cycles-in-2d-grid/discuss/1789840/Python-easy-to-read-and-understand-or-recursive-dfs
class Solution: def dfs(self, grid, row, col, visit, prev_row, prev_col, prev, visited): if row < 0 or col < 0 or row == len(grid) or col == len(grid[0]) or grid[row][col] != prev: return if (row, col) in visit: #print(row, col) self.ans = True return #print(row, col, prev_row, prev_col) visit.add((row, col)) visited[row][col] = True if row-1 != prev_row: self.dfs(grid, row-1, col, visit, row, col, grid[row][col], visited) if col-1 != prev_col: self.dfs(grid, row, col-1, visit, row, col, grid[row][col], visited) if row+1 != prev_row: self.dfs(grid, row+1, col, visit, row, col, grid[row][col], visited) if col+1 != prev_col: self.dfs(grid, row, col+1, visit, row, col, grid[row][col], visited) visit.remove((row, col)) def containsCycle(self, grid: List[List[str]]) -> bool: self.ans = False m, n = len(grid), len(grid[0]) visited = [[False for _ in range(n)] for _ in range(m)] for i in range(m): for j in range(n): if visited[i][j] == False: self.ans = False visit = set() self.dfs(grid, i, j, visit, -1, -1, grid[i][j], visited) if self.ans == True: return True return False
detect-cycles-in-2d-grid
Python easy to read and understand | recursive-dfs
sanial2001
0
165
detect cycles in 2d grid
1,559
0.48
Medium
23,040
https://leetcode.com/problems/detect-cycles-in-2d-grid/discuss/1694578/python-union-find-solution-or-96.55
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: m,n = len(grid),len(grid[0]) parent = list(range(m*n)) rank = [1 for _ in range(m*n)] def find(node): if parent[node]!=node: parent[node] = find(parent[node]) return parent[node] def union(node1,node2): p1,p2 = find(node1),find(node2) if p1==p2: return if rank[p1]>rank[p2]: p1,p2 = p2,p1 rank[p2] += rank[p1] parent[p1] = p2 for i in range(m): for j in range(n): for x,y in ((i,j+1),(i+1,j)): if 0<=x<m and 0<=y<n and grid[i][j]==grid[x][y]: n1,n2 = i*n+j,x*n+y if find(n1)==find(n2): return True else: union(n1,n2) return False
detect-cycles-in-2d-grid
python union find solution | 96.55%
1579901970cg
0
112
detect cycles in 2d grid
1,559
0.48
Medium
23,041
https://leetcode.com/problems/detect-cycles-in-2d-grid/discuss/1694347/Python-simple-memory-efficient-solution-(99-memory)
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: m, n = len(grid), len(grid[0]) def valid(x, y): return x>=0 and x<=m-1 and y>=0 and y<=n-1 def neighbor(p1, p2): x1, y1 = p1 x2, y2 = p2 return valid(x1, y1) and valid(x2, y2) and abs(x1-x2) + abs(y1-y2) == 1 def dfs(p, q): nonlocal grid stack = [(p, q, 1)] val = grid[p][q] while stack: x, y, length = stack.pop() grid[x][y] = "X" if neighbor((x, y), (p, q)) and length >= 4: return True for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]: xi, yi = x+dx, y+dy if valid(xi, yi) and grid[xi][yi] == val and grid[xi][yi] != "X": stack.append((xi, yi, length + 1)) return False for i in range(m): for j in range(n): if i< m-1 and j < n-1 and grid[i][j] == grid[i][j+1] == grid[i+1][j] and grid[i][j] != "X": if dfs(i, j): return True return False
detect-cycles-in-2d-grid
Python simple memory-efficient solution (99% memory)
byuns9334
0
110
detect cycles in 2d grid
1,559
0.48
Medium
23,042
https://leetcode.com/problems/detect-cycles-in-2d-grid/discuss/1613841/Python%3A-short-DFS
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: H,W=len(grid),len(grid[0]) seen=[[False]*W for _ in range(H)] def dfs(old_r,old_c, r,c): if seen[r][c]: return True seen[r][c]=True for nr,nc in (r+1,c),(r-1,c),(r,c+1),(r,c-1): if H>nr>=0<=nc<W and grid[nr][nc]==grid[r][c]: if (nr,nc)!=(old_r,old_c): if dfs(r,c,nr,nc): return True return False return any(dfs(-1,-1,r,c) for r in range(H) for c in range(W) if not seen[r][c])
detect-cycles-in-2d-grid
Python: short DFS
SeraphNiu
0
67
detect cycles in 2d grid
1,559
0.48
Medium
23,043
https://leetcode.com/problems/detect-cycles-in-2d-grid/discuss/1596957/WEEB-DOES-PYTHON-BFS
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: row, col = len(grid), len(grid[0]) visited = set() for x in range(row): for y in range(col): if (x,y) not in visited: queue = deque([(x, y, set([]), None)]) if self.bfs(queue, row, col, grid[x][y], grid, visited): return True return False def bfs(self, queue, row, col, curVal, grid, visited): while queue: x, y, curPath, prev = queue.popleft() visited.add((x,y)) curPath.add((x,y)) for nx, ny in [[x+1,y],[x-1,y],[x,y-1],[x,y+1]]: if 0<=nx<row and 0<=ny<col and grid[nx][ny] == curVal: if (nx,ny) in curPath and (nx,ny) != prev: return True if (nx,ny) not in curPath: queue.append((nx,ny, curPath, (x,y))) return False
detect-cycles-in-2d-grid
WEEB DOES PYTHON BFS
Skywalker5423
0
86
detect cycles in 2d grid
1,559
0.48
Medium
23,044
https://leetcode.com/problems/detect-cycles-in-2d-grid/discuss/1511521/Dictionaries-and-sets-82-speed
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: sets_vals = defaultdict(set) for r, row in enumerate(grid): for c, v in enumerate(row): sets_vals[v].add((r, c)) for _, set_val in sets_vals.items(): while set_val: chain_len = 0 start = set_val.pop() neighbours = {start} chain = {start: (chain_len, tuple())} while neighbours: chain_len += 1 new_neighbours = set() for r, c in neighbours: for new_cell in [(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)]: if (new_cell in chain and new_cell != chain[(r, c)][1] and chain[new_cell][0] + chain_len > 3): return True if new_cell in set_val: chain[new_cell] = (chain_len, (r, c)) new_neighbours.add(new_cell) set_val.remove(new_cell) neighbours = new_neighbours return False
detect-cycles-in-2d-grid
Dictionaries and sets, 82% speed
EvgenySH
0
78
detect cycles in 2d grid
1,559
0.48
Medium
23,045
https://leetcode.com/problems/most-visited-sector-in-a-circular-track/discuss/806738/Python3-2-line
class Solution: def mostVisited(self, n: int, rounds: List[int]) -> List[int]: x, xx = rounds[0], rounds[-1] return list(range(x, xx+1)) if x <= xx else list(range(1, xx+1)) + list(range(x, n+1))
most-visited-sector-in-a-circular-track
[Python3] 2-line
ye15
10
1,200
most visited sector in a circular track
1,560
0.584
Easy
23,046
https://leetcode.com/problems/most-visited-sector-in-a-circular-track/discuss/2551431/Simple-Python-Solution-with-Explanation
class Solution: def mostVisited(self, n: int, rounds: List[int]) -> List[int]: # count the length of distance starting from rounds[0]: distance = 1 for i in range(1, len(rounds)): if rounds[i - 1] < rounds[i]: distance += rounds[i] - rounds[i - 1] else: distance += n - (rounds[i - 1] - rounds[i]) # mapping= {number: frequency} mapping = collections.defaultdict(int) # be careful that the iteration should start from rounds[0] for i in range(rounds[0], rounds[0] + distance): if i % n != 0: mapping[i % n] += 1 else: mapping[n] += 1 # find out the most frequent numbers maxFreq = max(mapping.values()) res = [] for key in mapping: if mapping[key] == maxFreq: res.append(key) # sort the result list and retur return sorted(res)
most-visited-sector-in-a-circular-track
Simple Python Solution with Explanation
WUY97
0
89
most visited sector in a circular track
1,560
0.584
Easy
23,047
https://leetcode.com/problems/most-visited-sector-in-a-circular-track/discuss/2370847/python-O(n*k)
class Solution: def mostVisited(self, n: int, rounds: List[int]) -> List[int]: hash_map = {} for i in range(0 , len(rounds)-1): if i == 0: start = rounds[i] elif rounds[i] == n: start = 1 else: start = rounds[i] + 1 end = rounds[i+1] if start <= end: for i in range(start , end + 1): if i in hash_map: hash_map[i] += 1 else: hash_map[i] = 1 else: for i in range(start , n + 1): if i in hash_map: hash_map[i] += 1 else: hash_map[i] = 1 for i in range(1 , end + 1): if i in hash_map: hash_map[i] += 1 else: hash_map[i] = 1 k = list(hash_map.keys()) v = list(hash_map.values()) ans = [] m = -1 i = 0 j = 0 while i < len(k) and j < len(v): if len(ans) == 0: ans.append(k[i]) m = v[j] elif m < v[j]: ans = [] ans.append(k[i]) m = v[j] elif m == v[j]: ans.append(k[i]) i += 1 j += 1 ans = sorted(ans) return ans
most-visited-sector-in-a-circular-track
python O(n*k)
akashp2001
0
75
most visited sector in a circular track
1,560
0.584
Easy
23,048
https://leetcode.com/problems/most-visited-sector-in-a-circular-track/discuss/1977415/2-Lines-Python-Solution-oror-95-Faster-(40-ms)-oror-Memory-less-than-99
class Solution: def mostVisited(self, n: int, R: List[int]) -> List[int]: if R[0]<=R[-1]: return range(R[0],R[-1]+1) return sorted(set(range(1,n+1)) - set(range(R[-1]+1,R[0])))
most-visited-sector-in-a-circular-track
2-Lines Python Solution || 95% Faster (40 ms) || Memory less than 99%
Taha-C
0
117
most visited sector in a circular track
1,560
0.584
Easy
23,049
https://leetcode.com/problems/most-visited-sector-in-a-circular-track/discuss/1973073/Python-O(N)-Fast-and-Easy-Solution-No-Memory
class Solution: def mostVisited(self, n: int, rounds: List[int]) -> List[int]: start, end = rounds[0], rounds[-1] if start <= end: return range(start, end + 1) else: return list(range(1, end + 1)) + list(range(start, n + 1))
most-visited-sector-in-a-circular-track
Python O(N) Fast and Easy Solution, No Memory
Hejita
0
122
most visited sector in a circular track
1,560
0.584
Easy
23,050
https://leetcode.com/problems/most-visited-sector-in-a-circular-track/discuss/1759060/Python-dollarolution
class Solution: def mostVisited(self, n: int, rounds: List[int]) -> List[int]: for i in range(len(rounds)-1): a, b = rounds[i],rounds[i+1] if a < b: for j in range(a+1,b): rounds.append(j) else: for j in range(a+1,n+1): rounds.append(j) for j in range(1,b): rounds.append(j) m = 0 v = [] d = Counter(rounds) for i in d: if d[i] > m-1: v.append(i) m = d[i] return sorted(v)
most-visited-sector-in-a-circular-track
Python $olution
AakRay
0
145
most visited sector in a circular track
1,560
0.584
Easy
23,051
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/1232262/Python-Simple-Solution
class Solution: def maxCoins(self, piles: List[int]) -> int: piles.sort(reverse=True) sum = 0 for i in range(1,len(piles)-int(len(piles)/3),2): sum += piles[i] print(sum) return sum
maximum-number-of-coins-you-can-get
Python Simple Solution
yashwant_mahawar
2
146
maximum number of coins you can get
1,561
0.786
Medium
23,052
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/2345128/Python-easy-to-read-and-understand
class Solution: def maxCoins(self, piles: List[int]) -> int: piles.sort() n = len(piles) k = n // 3 i, j = 0, 2 ans = 0 while i < k: ans += piles[n-j] j += 2 i +=1 return ans
maximum-number-of-coins-you-can-get
Python easy to read and understand
sanial2001
1
78
maximum number of coins you can get
1,561
0.786
Medium
23,053
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/2101858/Python3-oror-Sorting-oror
class Solution: def maxCoins(self, piles: List[int]) -> int: count = len(piles) // 3 piles.sort() idx = len(piles) - 2 ans = 0 while count > 0: ans += piles[idx] idx -= 2 count -= 1 return ans
maximum-number-of-coins-you-can-get
Python3 || Sorting ||
s_m_d_29
1
56
maximum number of coins you can get
1,561
0.786
Medium
23,054
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/1728839/Python3%3A-Solution-%3A-Greedy
class Solution: def maxCoins(self, piles: List[int]) -> int: piles.sort() res = 0 k = len(piles)//3 i = len(piles)-1 j = 0 while i>0 and j<k: res += piles[i-1] i-=2 j+=1 return res
maximum-number-of-coins-you-can-get
Python3: Solution : Greedy
deleted_user
1
76
maximum number of coins you can get
1,561
0.786
Medium
23,055
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/806780/Python3-sorting-(2-line)
class Solution: def maxCoins(self, piles: List[int]) -> int: piles.sort() return sum(piles[-len(piles)*2//3::2])
maximum-number-of-coins-you-can-get
[Python3] sorting (2-line)
ye15
1
87
maximum number of coins you can get
1,561
0.786
Medium
23,056
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/2797999/Python-simple-sorting-solution-O(NlogN)-time-and-O(N)-space
class Solution: def maxCoins(self, piles: List[int]) -> int: piles.sort(reverse=True) n = len(piles)//3 count = 0 for i in range(1,len(piles)-n+1,2): count+=piles[i] return count
maximum-number-of-coins-you-can-get
Python simple sorting solution O(NlogN) time and O(N) space
Rajeev_varma008
0
2
maximum number of coins you can get
1,561
0.786
Medium
23,057
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/2779736/Python-easy-sorting
class Solution: def maxCoins(self, piles: List[int]) -> int: n= len(piles)//3 i=0 j=1 s=0 piles.sort(reverse= True) while i<n: s= s+ piles[j] j=j+2 i=i+1 return (s)
maximum-number-of-coins-you-can-get
Python- easy sorting
Antarab
0
1
maximum number of coins you can get
1,561
0.786
Medium
23,058
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/2691837/Really-easy-Python-solution-without-deque
class Solution: def maxCoins(self, piles: List[int]) -> int: piles.sort() i=0 j=len(piles)-2 result=0 while i<j: result+=piles[j] i+=1 j-=2 return result
maximum-number-of-coins-you-can-get
Really easy Python solution without deque
guneet100
0
7
maximum number of coins you can get
1,561
0.786
Medium
23,059
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/2671684/python3-Easy-Solution
class Solution: def maxCoins(self, piles: List[int]) -> int: length = len(piles)//3 total = 0 piles.sort() for i in range(length,len(piles),2): total += piles[i] return total
maximum-number-of-coins-you-can-get
python3 Easy Solution
Noisy47
0
8
maximum number of coins you can get
1,561
0.786
Medium
23,060
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/2634097/Simple-oror-sorting-oror-Python
class Solution: def maxCoins(self, piles: List[int]) -> int: piles.sort() j = len(piles)-2 i = 0 ans = 0 while j > i: ans += piles[j] i+=1 j-=2 return ans
maximum-number-of-coins-you-can-get
Simple || sorting || Python
mihirshah0114
0
7
maximum number of coins you can get
1,561
0.786
Medium
23,061
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/2596108/Python-easy-solution
class Solution: def maxCoins(self, piles: List[int]) -> int: myCoin = 0 piles.sort(reverse=1) for i in range(1, len(piles)*2//3, 2): myCoin += piles[i] return myCoin
maximum-number-of-coins-you-can-get
Python easy solution
Jack_Chang
0
17
maximum number of coins you can get
1,561
0.786
Medium
23,062
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/2591703/python3-simple-and-quick-solution-(662ms-92-faster)
class Solution: def maxCoins(self, piles: List[int]) -> int: # decreasingly sorting the list piles.sort(reverse=True) # the last (len(piles)/3) elements will be given to Bob. # Alice and myself will share the first (len(piles)/3*2) elements choice = sum(piles[0:int(len(piles)/3*2)][1::2]) return choice
maximum-number-of-coins-you-can-get
[python3] simple and quick solution (662ms/ 92% faster)
hhlinwork
0
10
maximum number of coins you can get
1,561
0.786
Medium
23,063
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/2554267/Python-or-easy-for-understand
class Solution: def maxCoins(self, piles: List[int]) -> int: max_coins = 0 sorted_piles = sorted(piles) for i in range(len(piles)//3): max_coins+= sorted_piles [len(piles)-2*i-2] return max_coins
maximum-number-of-coins-you-can-get
Python | easy for understand
KateIV
0
24
maximum number of coins you can get
1,561
0.786
Medium
23,064
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/2467038/Faster-than-85.24-of-Python3-online-submissions
class Solution: def maxCoins(self, piles: List[int]) -> int: piles.sort(reverse=True) total = 0 start = 1 length = len(piles) //3 while length != 0: total = total + piles[start] start+= 2 length -= 1 return total
maximum-number-of-coins-you-can-get
Faster than 85.24% of Python3 online submissions
shimul090
0
15
maximum number of coins you can get
1,561
0.786
Medium
23,065
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/2407475/Python3-Solution-with-using-sorting
class Solution: def maxCoins(self, piles: List[int]) -> int: piles.sort() steps_count = len(piles) // 3 cur_pile, res = len(piles) - 2, 0 while steps_count > 0: res += piles[cur_pile] steps_count -= 1 cur_pile -= 2 return res
maximum-number-of-coins-you-can-get
[Python3] Solution with using sorting
maosipov11
0
13
maximum number of coins you can get
1,561
0.786
Medium
23,066
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/2327041/Python-sorted-piles-with-explanation
class Solution: def maxCoins(self, piles: List[int]) -> int: piles = sorted(piles, reverse=True) me = sum([piles[i] for i in range(1, len(piles)//3*2, 2)]) return me
maximum-number-of-coins-you-can-get
Python sorted piles with explanation
Simzalabim
0
35
maximum number of coins you can get
1,561
0.786
Medium
23,067
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/2327041/Python-sorted-piles-with-explanation
class Solution: def maxCoins(self, piles: List[int]) -> int: piles = sorted(piles, reverse=True) me = 0 for i in range(1, len(piles) // 3 * 2, 2): me += piles[i] return me
maximum-number-of-coins-you-can-get
Python sorted piles with explanation
Simzalabim
0
35
maximum number of coins you can get
1,561
0.786
Medium
23,068
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/2263931/easy-python-solution
class Solution: def maxCoins(self, piles: List[int]) -> int: counter, ans, times = 0, 0, len(piles)//3 piles.sort(reverse = True) for i in range(1,len(piles),2) : ans += piles[i] counter += 1 if counter == times : break return ans
maximum-number-of-coins-you-can-get
easy python solution
sghorai
0
16
maximum number of coins you can get
1,561
0.786
Medium
23,069
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/2197221/Simple-Python-Solution
class Solution: def maxCoins(self, piles: List[int]) -> int: piles.sort() res, n = 0, len(piles) for i in range(n//3, n, 2): res+= piles[i] return res
maximum-number-of-coins-you-can-get
Simple Python Solution
SwapnilSinha
0
13
maximum number of coins you can get
1,561
0.786
Medium
23,070
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/2151827/Python-Easy
class Solution: def maxCoins(self, piles: List[int]) -> int: piles.sort() res = 0 for i in range(len(piles) // 3, len(piles), 2): res += piles[i] return res
maximum-number-of-coins-you-can-get
Python - Easy
lokeshsenthilkumar
0
45
maximum number of coins you can get
1,561
0.786
Medium
23,071
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/2099871/python-3-oror-simple-sorting-solution
class Solution: def maxCoins(self, piles: List[int]) -> int: piles.sort(reverse=True) n = len(piles) // 3 return sum(piles[i] for i in range(1, 2*n + 1, 2))
maximum-number-of-coins-you-can-get
python 3 || simple sorting solution
dereky4
0
29
maximum number of coins you can get
1,561
0.786
Medium
23,072
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/2066743/Python-Simple-solution-or-Sorting-Solution
class Solution: def maxCoins(self, piles: List[int]) -> int: piles.sort() ans=0 n = len(piles) # Alice take piles piles[n-1],piles[n-3],... # You take piles piles[n-2],piles[n-5],... # Bob take piles piles[0],piles[1],... for i in range(n - 2, n // 3 - 1, -2): ans += piles[i] return ans
maximum-number-of-coins-you-can-get
[Python] Simple solution | Sorting Solution💥
imjenit
0
34
maximum number of coins you can get
1,561
0.786
Medium
23,073
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/1727442/Python-or-Beginner-Friendly
class Solution: def maxCoins(self, piles: List[int]) -> int: n = len(piles) piles.sort() res = 0 for i in range(n//3, n, 2): res += piles[i] return res
maximum-number-of-coins-you-can-get
Python | Beginner Friendly
jgroszew
0
55
maximum number of coins you can get
1,561
0.786
Medium
23,074
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/1639755/Python3-simple-solution-faster-than-80
class Solution: def maxCoins(self, piles: List[int]) -> int: piles = sorted(piles) x = 0 a = 0 b = len(piles)-1 while b> a: x = x + piles[b-1] b=b-2 a=a+1 return x
maximum-number-of-coins-you-can-get
Python3 simple solution faster than 80%
leoferrer
0
40
maximum number of coins you can get
1,561
0.786
Medium
23,075
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/1631208/Extreme-simple-solution
class Solution: def maxCoins(self, piles: List[int]) -> int: n = len(piles)//3 piles.sort() res = 0 for i in range(n, len(piles), 2): res += piles[i] return res
maximum-number-of-coins-you-can-get
Extreme simple solution
Mason-007
0
21
maximum number of coins you can get
1,561
0.786
Medium
23,076
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/1587638/Python3-Solution-or-1-line-answer-or-O(nlogn)
class Solution: def maxCoins(self, piles: List[int]) -> int: return sum(sorted(piles)[len(piles)//3: :2])
maximum-number-of-coins-you-can-get
Python3 Solution | 1 line answer | O(nlogn)
satyam2001
0
93
maximum number of coins you can get
1,561
0.786
Medium
23,077
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/1525495/Python-Simple-Sorting-Slices-or-95-O(logN)-Time-O(1)-Space
class Solution: def maxCoins(self, piles: List[int]) -> int: #sort->discard Bob's share->find your max share->return piles.sort() piles = piles[len(piles)//3:] piles = piles[::2] return sum(piles)
maximum-number-of-coins-you-can-get
Python - Simple, Sorting, Slices | 95% O(logN) Time O(1) Space
haysal
0
50
maximum number of coins you can get
1,561
0.786
Medium
23,078
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/1506110/Python-3-Simple-solution
class Solution: def maxCoins(self, piles: List[int]) -> int: iterations = len(piles) / 3 piles.sort() ans, ind = 0, -2 while iterations != 0: ans += piles[ind] iterations -= 1 ind -= 2 return ans
maximum-number-of-coins-you-can-get
Python 3 Simple solution
frolovdmn
0
72
maximum number of coins you can get
1,561
0.786
Medium
23,079
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/1367369/WEEB-DOES-PYTHON-BEATS-(98.28)
class Solution: def maxCoins(self, piles: List[int]) -> int: piles = sorted(piles) # Bob takes the first n piles in the sorted array since he takes all the minimum coins return sum(piles[len(piles)//3::2]) # that means, we should start our sum after Bob's n piles, but without taking the max, so skip by 2 to prevent that
maximum-number-of-coins-you-can-get
WEEB DOES PYTHON BEATS (98.28%)
Skywalker5423
0
101
maximum number of coins you can get
1,561
0.786
Medium
23,080
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/1190547/Python-pythonic-wexplanation
class Solution: def maxCoins(self, piles: List[int]) -> int: piles.sort(reverse=True) return sum([i for i in piles[1:len(piles)//3*2:2]])
maximum-number-of-coins-you-can-get
[Python] pythonic w/explanation
cruim
0
42
maximum number of coins you can get
1,561
0.786
Medium
23,081
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/1160047/Python-3-easy-to-understand
class Solution: def maxCoins(self, piles: List[int]) -> int: res=0 piles=sorted(piles) for i in range(len(piles)//3): res+=piles[(-i*2)-2] return res
maximum-number-of-coins-you-can-get
Python 3 easy to understand
lin11116459
0
57
maximum number of coins you can get
1,561
0.786
Medium
23,082
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/1070109/Easy-Python3-Faster-then-9166
class Solution: def maxCoins(self, piles: List[int]) -> int: sort_piles = sorted(piles) final_index = len(piles)-1 value = 0 for i in range(len(piles) // 3): value += sort_piles[final_index-(i*2)-1] return value
maximum-number-of-coins-you-can-get
Easy Python3 - Faster then 91,66%
felipesanchez
0
61
maximum number of coins you can get
1,561
0.786
Medium
23,083
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/824915/Intuitive-approach-by-sorting-piles-and-iteratively-selecting-second-positionh
class Solution: def maxCoins(self, piles: List[int]) -> int: ans = 0 piles = sorted(piles, reverse=True) for i in range(len(piles) // 3): ans += piles[2 * i + 1] return ans
maximum-number-of-coins-you-can-get
Intuitive approach by sorting piles and iteratively selecting second positionh
puremonkey2001
0
29
maximum number of coins you can get
1,561
0.786
Medium
23,084
https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/807229/Python-3-(NlogN)
class Solution: def maxCoins(self, piles: List[int]) -> int: if len(piles) == 0: return 0 piles.sort() len_piles = len(piles) cnt = 0 for i in range(len_piles - 2, len_piles //3 -1, -2): cnt += piles[i] return cnt
maximum-number-of-coins-you-can-get
Python 3 (NlogN)
himanshu0503
0
41
maximum number of coins you can get
1,561
0.786
Medium
23,085
https://leetcode.com/problems/find-latest-group-of-size-m/discuss/809823/Python3-summarizing-two-approaches
class Solution: def findLatestStep(self, arr: List[int], m: int) -> int: span = [0]*(len(arr)+2) freq = [0]*(len(arr)+1) ans = -1 for i, x in enumerate(arr, 1): freq[span[x-1]] -= 1 freq[span[x+1]] -= 1 span[x] = span[x-span[x-1]] = span[x+span[x+1]] = 1 + span[x-1] + span[x+1] freq[span[x]] += 1 if freq[m]: ans = i return ans
find-latest-group-of-size-m
[Python3] summarizing two approaches
ye15
0
57
find latest group of size m
1,562
0.425
Medium
23,086
https://leetcode.com/problems/stone-game-v/discuss/1504994/Python-O(n2)-optimized-solution.-O(n3)-cannot-pass.
class Solution: def stoneGameV(self, stoneValue: List[int]) -> int: length = len(stoneValue) if length == 1: return 0 # Calculate sum s = [0 for _ in range(length)] s[0] = stoneValue[0] for i in range(1, length): s[i] = s[i-1] + stoneValue[i] # dp for best value, best_cut for where is the cut in (i, j), i, j inclusive dp = [[0 for _ in range(length)] for _ in range(length)] best_cut = [[0 for _ in range(length)] for _ in range(length)] for i in range(0, length-1): dp[i][i+1] = min(stoneValue[i], stoneValue[i+1]) best_cut[i][i+1] = i for t in range(2, length): for i in range(0, length-t): tmp_dp = 0 tmp_cut = 0 left_bound = best_cut[i][i+t-1] if left_bound > i: left_bound -= 1 right_bound = best_cut[i+1][i+t] if right_bound < i+t-1: right_bound += 1 for k in range(left_bound, 1+right_bound): s1 = s[k] - s[i-1] if i > 0 else s[k] s2 = s[i+t] - s[k] if s1 < s2: tmp = s1 + dp[i][k] if tmp > tmp_dp: tmp_dp = tmp tmp_cut = k elif s1 > s2: tmp = s2 + dp[k+1][i+t] if tmp > tmp_dp: tmp_dp = tmp tmp_cut = k else: tmp1 = s1 + dp[i][k] tmp2 = s2 + dp[k+1][i+t] if tmp1 > tmp_dp: tmp_dp = tmp1 tmp_cut = k if tmp2 > tmp_dp: tmp_dp = tmp2 tmp_cut = k dp[i][i+t] = tmp_dp best_cut[i][i+t] = tmp_cut return dp[0][length-1]
stone-game-v
Python O(n^2) optimized solution. O(n^3) cannot pass.
pureme
4
202
stone game v
1,563
0.406
Hard
23,087
https://leetcode.com/problems/stone-game-v/discuss/1023888/python-top-down-dp-with-thinking-process
class Solution: def stoneGameV(self, stoneValue: List[int]) -> int: def dfs(start, end): if start >= end: return 0 max_score = 0 # divides the array into [start,cut] and # [cur+1, end] for cut in range(start, end): sum1 = partial_sum[start][cut] sum2 = partial_sum[cut+1][end] # remaing part is [cut+1, end] if sum1 > sum2: score = sum2+dfs(cut+1, end) # remaining part is [start, cut] elif sum1 < sum2: score = sum1+dfs(start, cut) # two rows are equal else: score = sum1+max(dfs(start, cut), dfs(cut+1, end)) max_score = max(score, max_score) return max_score def getPartialSum(): for i in range(n): partial_sum[i][i] = stoneValue[i] for i in range(n): for j in range(i+1, n): partial_sum[i][j] = partial_sum[i][j-1]+stoneValue[j] n = len(stoneValue) partial_sum = [[0]*n for _ in range(n)] getPartialSum() return dfs(0, n-1)
stone-game-v
python top down dp with thinking process
ytb_algorithm
3
336
stone game v
1,563
0.406
Hard
23,088
https://leetcode.com/problems/stone-game-v/discuss/1023888/python-top-down-dp-with-thinking-process
class Solution: def stoneGameV(self, stoneValue: List[int]) -> int: def getPartialSum(): for i in range(n): partial_sum[i][i] = stoneValue[i] for i in range(n): for j in range(i+1, n): partial_sum[i][j] = partial_sum[i][j-1]+stoneValue[j] # (O(n) search) def preCalCutIdx(): # based on the fact that cut index is increasing with k for # partial_sum[start][k] for i in range(n-1): cp = i cut_index[i][i+1] = i for j in range(i+2, n): while cp < j-1 and partial_sum[i][cp] < partial_sum[cp+1][j]: cp += 1 cut_index[i][j] = cp @lru_cache(None) def dfs(start, end): if start >= end: return 0 max_score = 0 # find first cut s.t. left sum >= right sum cut = cut_index[start][end] # we can't find cut s.t. left sum >= right sum if cut == -1: cut = end-1 sum1 = partial_sum[start][cut] sum2 = partial_sum[cut+1][end] if sum1 < sum2: # calcuate left[start][cut] if not yet dfs(start, cut) # the remaining will be the left part for sure, no # matter where the cut is. max_score = left[start][cut] elif sum1 == sum2: dfs(start, cut) dfs(cut+1, end) # if real cut in the range of [cut+1, end], remaining will be the right part # if real cut in the range of [0, cut], remaing will be the left part # if real cut is cut, either can be the remaining. max_score = max(left[start][cut], right[cut+1][end]) else: dfs(cut+1, end) # we are selecting the cut in the range of [cut, end] having # the max score. For cut in that range, the remaining is # the right part of the cut for sure. max_score = right[cut+1][end] if cut > start: dfs(start, cut-1) # we are selecting the cut in the range of [0, cut] having # the max score. The remaining is the left part for sure. max_score = max(max_score, left[start][cut-1]) dfs(start, end-1) dfs(start+1, end) # updating left and right arrays. left[start][end] = max(left[start][end-1], partial_sum[start][end]+max_score) right[start][end] = max(right[start+1][end], partial_sum[start][end]+max_score) return max_score n = len(stoneValue) partial_sum = [[0]*n for _ in range(n)] cut_index = [[-1]*n for _ in range(n)] # left[i][j]: cut in the range of [i, j], max score of left part # right[i][j]: cut in the range of [i, j], max score of right part left = [[0]*n for _ in range(n)] right = [[0]*n for _ in range(n)] for i in range(n): left[i][i] = stoneValue[i] right[i][i] = stoneValue[i] getPartialSum() # for partial_sum[i][j], find cut index between i and j # s.t partial_sum[i][cut_index] >= partial_sum[cut_index+1][j] or # cut_index = j-1 if not exist. preCalCutIdx() return dfs(0, n-1)
stone-game-v
python top down dp with thinking process
ytb_algorithm
3
336
stone game v
1,563
0.406
Hard
23,089
https://leetcode.com/problems/stone-game-v/discuss/806758/Python-DFS-%2B-Memo
class Solution: def stoneGameV(self, stoneValue: List[int]) -> int: n = len(stoneValue) pre = [0] for i in range(n): pre.append(stoneValue[i] + pre[-1]) @lru_cache(None) def dfs(l, r): if r <= l: return 0 res = 0 for i in range(l, r): # [l, i] [i + 1, r] left = pre[i + 1] - pre[l] right = pre[r + 1] - pre[i + 1] if right > left: res = max(res, dfs(l, i) + left) elif left > right: res = max(res, dfs(i + 1, r) + right) else: res = max(res, dfs(l, i) + left) res = max(res, dfs(i + 1, r) + right) return res return dfs(0, n - 1)
stone-game-v
Python DFS + Memo
tomzy
2
279
stone game v
1,563
0.406
Hard
23,090
https://leetcode.com/problems/stone-game-v/discuss/806794/Python3-top-down-dp
class Solution: def stoneGameV(self, stoneValue: List[int]) -> int: # prefix sum prefix = [0] for x in stoneValue: prefix.append(prefix[-1] + x) @lru_cache(None) def fn(lo, hi): """Return the score of arranging values from lo (inclusive) to hi (exclusive). """ if lo+1 == hi: return 0 val = 0 for mid in range(lo+1, hi): lower = prefix[mid] - prefix[lo] upper = prefix[hi] - prefix[mid] if lower < upper: val = max(val, lower + fn(lo, mid)) elif lower > upper: val = max(val, upper + fn(mid, hi)) else: val = max(val, lower + max(fn(lo, mid), fn(mid, hi))) return val return fn(0, len(stoneValue))
stone-game-v
[Python3] top-down dp
ye15
1
180
stone game v
1,563
0.406
Hard
23,091
https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/discuss/1254278/Python3-simple-solution
class Solution: def containsPattern(self, arr: List[int], m: int, k: int) -> bool: for i in range(len(arr)-m+1): count = 1 x = arr[i:i+m] res = 1 for j in range(i+m,len(arr)-m+1,m): if x == arr[j:j+m]: count += 1 else: res = max(res,count) count = 1 x = arr[j:j+m] res = max(res,count) if res >= k: return True return False
detect-pattern-of-length-m-repeated-k-or-more-times
Python3 simple solution
EklavyaJoshi
2
124
detect pattern of length m repeated k or more times
1,566
0.436
Easy
23,092
https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/discuss/1815820/3-Lines-Python-Solution-oror-50-Faster-oror-Memory-less-than-90
class Solution: def containsPattern(self, arr: List[int], m: int, k: int) -> bool: if len(arr) < k*m: return False arr = ''.join([str(x) for x in arr]) return any([ a==a[0:m]*k for a in [arr[i:i+m*k] for i in range(len(arr))] ])
detect-pattern-of-length-m-repeated-k-or-more-times
3-Lines Python Solution || 50% Faster || Memory less than 90%
Taha-C
1
101
detect pattern of length m repeated k or more times
1,566
0.436
Easy
23,093
https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/discuss/1815820/3-Lines-Python-Solution-oror-50-Faster-oror-Memory-less-than-90
class Solution: def containsPattern(self, arr: List[int], m: int, k: int) -> bool: if len(arr) < m*k: return False for i in range(len(arr)-m*k+1): if arr[i:i+m]*k == arr[i:i+m*k]: return True return False
detect-pattern-of-length-m-repeated-k-or-more-times
3-Lines Python Solution || 50% Faster || Memory less than 90%
Taha-C
1
101
detect pattern of length m repeated k or more times
1,566
0.436
Easy
23,094
https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/discuss/819312/Python3-brute-force
class Solution: def containsPattern(self, arr: List[int], m: int, k: int) -> bool: ans = 0 memo = [1]*len(arr) # repetition of pattern ending at i for i in range(len(arr)): if arr[i+1-m:i+1] == arr[i+1-2*m:i+1-m]: memo[i] = 1 + memo[i-m] if memo[i] == k: return True return False
detect-pattern-of-length-m-repeated-k-or-more-times
[Python3] brute-force
ye15
1
136
detect pattern of length m repeated k or more times
1,566
0.436
Easy
23,095
https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/discuss/2847048/Python-Sliding-Window-Approach-For-Beginners
class Solution: def hasPattern(self, start, end, pattern, arr, m): for sub_index in range(start, end + 1, m): if arr[sub_index:sub_index + m] != pattern: return False return True def containsPattern(self, arr: List[int], m: int, k: int) -> bool: window_start = 0 window_end = m * k - 1 length = len(arr) hasPattern = False while window_end < length: pattern = arr[window_start:window_start + m] hasPattern = self.hasPattern(window_start, window_end, pattern, arr, m) if hasPattern: break window_end += 1 window_start += 1 return hasPattern
detect-pattern-of-length-m-repeated-k-or-more-times
Python Sliding Window Approach For Beginners
shtanriverdi
0
1
detect pattern of length m repeated k or more times
1,566
0.436
Easy
23,096
https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/discuss/2837208/Python-sliding-window-solution
class Solution: def containsPattern(self, arr: List[int], m: int, k: int) -> bool: window_len = m * k if len(arr) < window_len: return False def kRepeats(left, right): w0 = arr[left: left + m] for i in range(left + m, right, m): w1 = arr[i: i + m] if w1 != w0: return False return True for window_start in range(0, len(arr) - window_len + 1): window_end = window_start + window_len #window_end is excluded if kRepeats(window_start, window_end): return True return False
detect-pattern-of-length-m-repeated-k-or-more-times
Python sliding window solution
StacyAceIt
0
1
detect pattern of length m repeated k or more times
1,566
0.436
Easy
23,097
https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/discuss/2550189/Python-Solution
class Solution: def containsPattern(self, arr: List[int], m: int, k: int) -> bool: n=len(arr) for i in range(n-m): pattern=arr[i:i+m] count=1 for j in range(i+m, n): # print(arr[j:j+m]) if pattern==arr[j:j+m]: count+=1 else: break print(pattern, count) if count>=k: return True return False
detect-pattern-of-length-m-repeated-k-or-more-times
Python Solution
Siddharth_singh
0
60
detect pattern of length m repeated k or more times
1,566
0.436
Easy
23,098
https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/discuss/2370945/python-O(n*n)
class Solution: def containsPattern(self, arr: List[int], m: int, k: int) -> bool: count = 1 i = 0 while i < len(arr) - m: if arr[i : i + m] == arr[i + m:i + 2*m]: i += m count += 1 if count == k: return True else: count = 1 i += 1 return False
detect-pattern-of-length-m-repeated-k-or-more-times
python O(n*n)
akashp2001
0
60
detect pattern of length m repeated k or more times
1,566
0.436
Easy
23,099