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/baseball-game/discuss/1932484/Python3-Solution-with-using-stack
class Solution: def calPoints(self, ops: List[str]) -> int: stack = [] cur_sum = 0 for op in ops: if op == '+': right = stack.pop() left = stack[-1] stack.append(right) # return right value cur_sum += left + right stack.append(left + right) elif op == 'C': cur_sum -= stack.pop() elif op == 'D': cur_sum += stack[-1] * 2 stack.append(stack[-1] * 2) else: stack.append(int(op)) cur_sum += stack[-1] return cur_sum
baseball-game
[Python3] Solution with using stack
maosipov11
0
20
baseball game
682
0.737
Easy
11,300
https://leetcode.com/problems/baseball-game/discuss/1932413/Python-match-and-Swift-switch
class Solution: def calPoints(self, ops: List[str]) -> int: ans = [] for o in ops: match o: case "D": ans.append(ans[-1] * 2) case "C": ans.pop() case "+": ans.append(ans[-1] + ans[-2]) case _: ans.append(int(o)) return sum(ans)
baseball-game
Python match and Swift switch
blest
0
22
baseball game
682
0.737
Easy
11,301
https://leetcode.com/problems/baseball-game/discuss/1932356/Easy-solution-in-Python-(~20-lines)-with-explanation-(Faster-than-97-submissions)
class Solution: def calPoints(self, ops: List[str]) -> int: score = [] for op in ops: if op == "+": score.append(score[-1] + score[-2]) elif op == "D": score.append(2*score[-1]) elif op == "C": score.pop() else: score.append(int(op)) return sum(score)
baseball-game
Easy solution in Python (~20 lines) with explanation (Faster than 97% submissions)
MrRex_
0
13
baseball game
682
0.737
Easy
11,302
https://leetcode.com/problems/baseball-game/discuss/1932209/Simplest-Solution-of-Baseball-Game
class Solution: def calPoints(self, ops: List[str]) -> int: record = [] for i in ops: try: record.append(int(i)) except: if i == "+": new_score = record[-2] + record[-1] record.append(new_score) elif i == "D": new_score = record[-1] * 2 record.append(new_score) else: record.pop() sum_ = 0 for i in record: sum_ += i return sum_
baseball-game
Simplest Solution of Baseball Game
pratikkumarsingh011
0
7
baseball game
682
0.737
Easy
11,303
https://leetcode.com/problems/baseball-game/discuss/1932146/Python-solution-using-stack-93-faster
class Solution: def calPoints(self, ops: List[str]) -> int: stack = [] for op in ops: if op == "+": stack.append(stack[-1] + stack[-2]) elif op == "D": stack.append(2 * stack[-1]) elif op == "C": stack.pop() else: stack.append(int(op)) return sum(stack)
baseball-game
Python solution using stack 93% faster
pradeep288
0
13
baseball game
682
0.737
Easy
11,304
https://leetcode.com/problems/baseball-game/discuss/1931500/Python-or-O(n)-or-Beats-99.5
class Solution: def calPoints(self, ops: List[str]) -> int: ans = [] for op in ops: match op: case 'C': ans.pop() case 'D': ans.append(ans[-1]*2) case '+': ans.append(sum(ans[-2:])) case _: ans.append(int(op)) return sum(ans)
baseball-game
Python | O(n) | Beats 99.5%
prajyotgurav
0
17
baseball game
682
0.737
Easy
11,305
https://leetcode.com/problems/baseball-game/discuss/1931473/Python-easy-solution-for-beginners
class Solution: def calPoints(self, ops: List[str]) -> int: score = [] for i in ops: if i == "C": score.pop(-1) elif i == "D": score.append(score[-1] * 2) elif i == "+": score.append(score[-1] + score[-2]) else: score.append(int(i)) return sum(score)
baseball-game
Python easy solution for beginners
alishak1999
0
14
baseball game
682
0.737
Easy
11,306
https://leetcode.com/problems/baseball-game/discuss/1930892/Python3-or-Simple
class Solution: def calPoints(self, ops: List[str]) -> int: ans = [] index = 0 for ch in ops: if ch.isdigit(): ans.append(int(ch)) index += 1 elif ch.lstrip("-").isdigit(): ans.append(int(ch)) index += 1 elif ch == "C": ans.pop() index -= 1 elif ch == "D": ans.append(ans[index-1]*2) index += 1 elif ch == "+": ans.append(ans[index-1] + ans[index-2]) index += 1 return sum(ans)
baseball-game
Python3 | Simple
user0270as
0
10
baseball game
682
0.737
Easy
11,307
https://leetcode.com/problems/baseball-game/discuss/1930876/Python-Easy-and-Simple-Solution
class Solution: def calPoints(self, ops: List[str]) -> int: arr = [] for i in ops: if i.isdigit(): arr.append(int(i)) elif i == 'C': arr.pop() elif i == 'D': arr.append(arr[-1] * 2) elif i == '+': arr.append(arr[-1] + arr[-2]) else: arr.append(int(i)) return sum(arr)
baseball-game
Python - Easy and Simple Solution
dayaniravi123
0
19
baseball game
682
0.737
Easy
11,308
https://leetcode.com/problems/baseball-game/discuss/1930750/Python-or-Time-%3A-O(n)-or-Space-%3A-O(n)
class Solution: def calPoints(self, ops: List[str]) -> int: result = [] sum_ = 0 for value in ops: if value == 'C': sum_ -= result.pop() continue elif value == 'D': result.append(result[-1]*2) elif value == '+': result.append(result[-1]+result[-2]) else: result.append(int(value)) sum_ += result[-1] return sum_
baseball-game
Python | Time : O(n) | Space : O(n)
Call-Me-AJ
0
22
baseball game
682
0.737
Easy
11,309
https://leetcode.com/problems/baseball-game/discuss/1930730/python-integer-stack
class Solution: def calPoints(self, ops: List[str]) -> int: st = [] for i in ops: if i == 'C': st.pop() elif i == 'D': st.append(st[-1] * 2) elif i == '+': st.append(st[-1] + st[-2]) else: st.append(int(i)) return sum(st)
baseball-game
python integer stack
user2613C
0
12
baseball game
682
0.737
Easy
11,310
https://leetcode.com/problems/baseball-game/discuss/1930688/Python3-98-faster
class Solution: def calPoints(self, ops: List[str]) -> int: newList = [] for x in ops: if x == 'C': newList = newList[:-1] elif x == 'D': newList.append(newList[-1] * 2) elif x == '+': newList.append(newList[-1] + newList[-2]) else: newList.append(int(x)) return sum(newList)
baseball-game
Python3, 98% faster
cvelazquez322
0
22
baseball game
682
0.737
Easy
11,311
https://leetcode.com/problems/baseball-game/discuss/1930600/Python3-100-or-IF...ELSE-Matching-or-Easy-Implementation
class Solution: def calPoints(self, ops: List[str]) -> int: ans = [] for op in ops: if op == '+': ans.append(ans[-1] + ans[-2]) elif op == 'C': ans.pop() elif op == 'D': ans.append(ans[-1] * 2) else: ans.append(int(op)) return sum(ans)
baseball-game
Python3 100% | IF...ELSE Matching | Easy Implementation
doneowth
0
15
baseball game
682
0.737
Easy
11,312
https://leetcode.com/problems/baseball-game/discuss/1842353/7-Lines-Python-Solution-oror-91-Faster-oror-Memory-less-than-85
class Solution: def calPoints(self, ops: List[str]) -> int: ans=[] for op in ops: if op=='+': ans.append(ans[-1]+ans[-2]) elif op=='D': ans.append(2*ans[-1]) elif op=='C': ans.pop() else: ans.append(int(op)) return sum(ans)
baseball-game
7-Lines Python Solution || 91% Faster || Memory less than 85%
Taha-C
0
34
baseball game
682
0.737
Easy
11,313
https://leetcode.com/problems/baseball-game/discuss/1837957/Python-simple-and-concise!-Match-Case-solution
class Solution: def calPoints(self, ops: List[str]) -> int: record = [] for op in ops: match op: case "+": record.append(record[-1]+record[-2]) case "D": record.append(record[-1]*2) case "C": record.remove(record[-1]) case _: record.append(int(op)) return sum(record)
baseball-game
Python - simple and concise! Match Case solution
domthedeveloper
0
51
baseball game
682
0.737
Easy
11,314
https://leetcode.com/problems/baseball-game/discuss/1837957/Python-simple-and-concise!-Match-Case-solution
class Solution: def calPoints(self, ops: List[str]) -> int: record = deque() for op in ops: match op: case "+": record.append(record[-1]+record[-2]) case "D": record.append(record[-1]*2) case "C": record.pop() case _: record.append(int(op)) return sum(record)
baseball-game
Python - simple and concise! Match Case solution
domthedeveloper
0
51
baseball game
682
0.737
Easy
11,315
https://leetcode.com/problems/baseball-game/discuss/1837957/Python-simple-and-concise!-Match-Case-solution
class Solution: def calPoints(self, ops: List[str]) -> int: record, total = deque(), 0 for op in ops: match op: case "+": record.append(record[-1]+record[-2]) total += record[-1] case "D": record.append(record[-1]*2) total += record[-1] case "C": total -= record.pop() case _: record.append(int(op)) total += record[-1] return total
baseball-game
Python - simple and concise! Match Case solution
domthedeveloper
0
51
baseball game
682
0.737
Easy
11,316
https://leetcode.com/problems/baseball-game/discuss/1461043/One-pass-99-speed
class Solution: def calPoints(self, ops: List[str]) -> int: scores = [] for op in ops: if op == "+": scores.append(scores[-1] + scores[-2]) elif op == "D": scores.append(scores[-1] * 2) elif op == "C": scores.pop() else: scores.append(int(op)) return sum(scores)
baseball-game
One pass, 99% speed
EvgenySH
0
181
baseball game
682
0.737
Easy
11,317
https://leetcode.com/problems/baseball-game/discuss/1372536/Python-Solution
class Solution: def calPoints(self, ops: List[str]) -> int: result = [] for j in ops: if j == '+': result.append(result[-1] + result[-2]) elif j == 'D': result.append(2*result[-1]) elif j == 'C': result.remove(result[-1]) else: result.append(int(j)) return sum(result)
baseball-game
Python Solution
_Mansiii_
0
86
baseball game
682
0.737
Easy
11,318
https://leetcode.com/problems/baseball-game/discuss/1354454/Easy-Python-Code
class Solution: def calPoints(self, ops: List[str]) -> int: temp=[] result=0 for i in range(len(ops)): if ops[i]=="+": temp.append(sum(temp[-2:])) elif ops[i]=="D": temp.append(temp[-1]*2) elif ops[i] == "C": temp.pop() else: temp.append(int(ops[i])) return sum(temp)
baseball-game
Easy Python Code
sangam92
0
26
baseball game
682
0.737
Easy
11,319
https://leetcode.com/problems/baseball-game/discuss/1309058/Python3-dollarolution(89-faster-and-89-better-memory-usage)
class Solution: def calPoints(self, ops: List[str]) -> int: v = [] for i in ops: if i == '+': v.append(v[-1] + v[-2]) elif i == 'D': v.append(v[-1] * 2) elif i == 'C': v.pop() else: v.append(int(i)) return sum(v)
baseball-game
Python3 $olution(89% faster & 89% better memory usage)
AakRay
0
92
baseball game
682
0.737
Easy
11,320
https://leetcode.com/problems/baseball-game/discuss/1291329/Easy-Python-Solution(99.80)
class Solution: def calPoints(self, ops: List[str]) -> int: stack=[] for i in ops: if(i=="C"): stack.pop() elif(i=="D"): stack.append(int(stack[-1])*2) elif(i=="+"): s=int(stack[-1])+int(stack[-2]) stack.append(s) else: stack.append(int(i)) return sum(stack)
baseball-game
Easy Python Solution(99.80%)
Sneh17029
0
213
baseball game
682
0.737
Easy
11,321
https://leetcode.com/problems/baseball-game/discuss/1255487/Straightforward-Python-%3A-Easy-to-understand
class Solution: def calPoints(self, ops: List[str]) -> int: res = [] for i in ops: if i == 'C': res.pop() elif i == 'D': x = res[len(res)-1] res.append(2*x) elif i == '+': x = res[len(res) - 1] y = res[len(res) - 2] res.append(x+y) else: res.append(int(i)) return sum(res)
baseball-game
Straightforward Python : Easy to understand
abhijeetmallick29
0
13
baseball game
682
0.737
Easy
11,322
https://leetcode.com/problems/redundant-connection/discuss/2755933/Python-Union-Find-Easy
class Solution(object): def findRedundantConnection(self, edges): self.parent = dict() for e in edges: f0 = self.find(e[0]) f1 = self.find(e[1]) if f0 == f1: return e self.parent[f0] = f1 def find(self, x): if x not in self.parent: return x return self.find(self.parent[x])
redundant-connection
Python - Union Find - Easy
lokeshsenthilkumar
1
8
redundant connection
684
0.62
Medium
11,323
https://leetcode.com/problems/redundant-connection/discuss/2042957/Solve-by-Adjacency-list-with-concise-code-Python
class Solution: def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: d=defaultdict(lambda:[]) for i in range(len(edges)): d[edges[i][0]].append(edges[i][1]) d[edges[i][1]].append(edges[i][0]) while any([len(v)<2 for v in d.values()]): for k,v in [(k,v) for k, v in d.items() if len(v)<2]: for m in v: d[m].remove(k) del d[k] for e in reversed(edges): if e[0] in d and e[1] in d: return e
redundant-connection
Solve by Adjacency list with concise code [Python]
guankiro
1
88
redundant connection
684
0.62
Medium
11,324
https://leetcode.com/problems/redundant-connection/discuss/2000491/Python3-Runtime%3A-40ms-100-Memory%3A-14.4mb-60.47
class Solution: def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: n = len(edges) parents = [i for i in range(n + 1)] def find(i): if parents[i] != i: parents[i] = find(parents[i]) return parents[i] def union(i,j): parents[i] = j for e in edges: e1 = find(e[0]) e2 = find(e[1]) if e1 == e2: return e union(e1, e2)
redundant-connection
Python3 Runtime: 40ms 100% Memory: 14.4mb 60.47%
arshergon
1
90
redundant connection
684
0.62
Medium
11,325
https://leetcode.com/problems/redundant-connection/discuss/2795260/Python-BFS-Kahn's-algorithm-and-Time-Complexity-O(N)
class Solution: def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: # drop out indegree == 1, and check from the bottom return first indegree==2 n = len(edges) indegree = collections.defaultdict(int) # SC: O(|V|) graph = collections.defaultdict(list) # SC: O(|V|+|E|) for a,b in edges: graph[a].append(b) graph[b].append(a) indegree[a] += 1 indegree[b] += 1 # find indegree == 1 queue = collections.deque([i for i,v in indegree.items() if v==1]) while queue: # TC: O(|V|+|E|), explore all vertices and edges node = queue.popleft() indegree[node] -= 1 for nei in graph[node]: indegree[nei] -= 1 if indegree[nei] == 1: queue.append(nei) # find first indegree == 2 edges from the end for a, b in edges[::-1]: if indegree[a] == 2 and indegree[b]: return [a,b]
redundant-connection
Python BFS, Kahn's algorithm and Time Complexity O(N)
ychanc2104
0
11
redundant connection
684
0.62
Medium
11,326
https://leetcode.com/problems/redundant-connection/discuss/2726910/Python-solution-using-Union-Find-Algorithm
class Solution: def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: # Union Find Algorithm # root = [i for i in range(len(edges)+1)] rank = [1] * (len(edges)+1) def find(x): if x == root[x]: return x root[x] = find(root[x]) return root[x] def union(n1, n2): r1 = find(n1) r2 = find(n2) if r1 == r2: return False if r1 != r2: if rank[r1] > rank[r2]: root[r2] = r1 rank[r1] += 1 else: root[r1] = r2 rank[r2] += 1 return True for u,v in edges: if not union(u,v): return [u,v]
redundant-connection
Python solution using Union Find Algorithm
PythonicLava
0
10
redundant connection
684
0.62
Medium
11,327
https://leetcode.com/problems/redundant-connection/discuss/2346259/Python3-or-14-lines-Union-Find-solution
class Solution: def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: parents = [-1 for _ in range(len(edges) + 1)] def get_root(a:int): while parents[a] != -1: a = parents[a] return a for e in edges: a,b = e root_a = get_root(a) root_b = get_root(b) if root_a == root_b: return e parents[root_a] = root_b
redundant-connection
Python3 | 14 lines Union Find solution
Geazas
0
24
redundant connection
684
0.62
Medium
11,328
https://leetcode.com/problems/redundant-connection/discuss/2341028/python3-easy-fast-solution
class Solution: def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: par = [i for i in range(len(edges) + 1)] rank = [1] * (len(edges) + 1) def find(n): p = par[n] while p != par[p]: par[p] = par[par[p]] p = par[p] return p def union(n1, n2): p1, p2 = find(n1), find(n2) if p1 == p2: return False if rank[p1] > rank[p2]: par[p1] = par[p2] rank[p1] += rank[p2] else: par[p2] = par[p1] rank[p2] += rank[p1] return True for n1,n2 in edges: if not union(n1,n2): return [n1,n2]
redundant-connection
python3 easy fast solution
soumyadexter7
0
55
redundant connection
684
0.62
Medium
11,329
https://leetcode.com/problems/redundant-connection/discuss/2311888/Beats-99.74-Union-Find-Fully-Explained-Path-Compression-%2B-Union-Rank-Optimizations
class Solution: def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: #FIRST UNION METHOD (MOST BASIC), no optimization #if node u is a parent, then we can point this parent to v # 1 and 3 # ^ ^ # | | # 2 4 #if we want to union 1 and 4, we would point the 1 to 4 giving: # 3 # ^ # 4 # ^ # 1 # ^ # 2 #if we want to union 2 and 4, since neither are parents, we (default) point the parent of v to u #parent of 4 is 3 #point 3 to 2 #1 #^ #2 #^ #3 #^ #4 def union1(u, v): #if u is a parent, we can point it if UF[u] < 0: UF[u] = v #if v is a parent, we can point it elif UF[v] < 0: UF[v] = u #default point the parent of v to u else: UF[find(v)] = find(u) #OPTIMIZED UNION METHOD USING UNION RANK, CREATING SHORTER TREES #for example: # 1 and 3 # ^ ^ # | | # 2 4 # ^ # | # 5 #now say we want to union 2 and 5 #instead of having the parent of 2 point to 5 or parent of 5 point to 2, we can optimize it by having the group with the parent 1 become a branch of the group with the parent of 3 #this is because the depth of group 1 is less than the depth of group 3, so we add 1 to 3 (NOT other way around) # 3 <- 1 <- 2 # ^ # | # 4 # ^ # | # 5 #https://www.online-python.com/1QLPFctl4K def union2(u, v): parentU = find(u) parentV = find(v) depthU = UF[parentU] depthV = UF[parentV] #DONT FORGET TO NEGATE THE HEIGHTS (since they are stored as negatives). so the SMALLER value is actually LARGER #since the height of the u group is higher than the v group, we will let the u group be the parent of the union if (depthU < depthV): UF[parentV] = parentU UF[parentU] = min(depthU, depthV - 1) #vice versa else: UF[parentU] = parentV UF[parentV] = min(depthV, depthU - 1) #IMPEMENT PATH COMPRESSION def find(node): #we use a negative number to mark if the node is a parent if UF[node] < 0: return node #path compression, point the current node all the way to its parent UF[node] = find(UF[node]) return UF[node] UF = {} #WE STORE AS NEGATIVE VALUE TO INDICATE IT IS A PARENT AND LET THE NEGATIVE NUMBER ALSO REPRESENT THE DEPTH for i in range(1, len(edges) + 1): UF[i] = -1 for edge in edges: u = edge[0] v = edge[1] #if we found a cycle, we return the edge that caused it if find(u) == find(v): return edge union2(u, v)
redundant-connection
Beats 99.74% Union Find - Fully Explained Path Compression + Union Rank Optimizations
yaahallo
0
66
redundant connection
684
0.62
Medium
11,330
https://leetcode.com/problems/redundant-connection/discuss/1880297/Topo-sort-python3-faster-than-98
class Solution: def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: n = len(edges) s = {x for x in range(1,n+1)} gra = defaultdict(list) for x,y in edges: gra[x].append(y) gra[y].append(x) q = [x for x in range(1,n+1) if len(gra[x]) == 1] cu = 0 while cu < len(q): m = q[cu] cu += 1 s.remove(m) for nei in gra[m]: gra[nei].remove(m) if len(gra[nei]) == 1: q.append(nei) for x,y in reversed(edges): if x in s and y in s: return [x,y]
redundant-connection
Topo sort python3 faster than 98%
nonieno
0
17
redundant connection
684
0.62
Medium
11,331
https://leetcode.com/problems/redundant-connection/discuss/1655921/Python-Easy-Solution-Weighted-union-collapsed-find.-Faster-than-96
class Solution: def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: parent = [-1] * (len(edges)+1) def find_parent(a): # if parent[node] <0, the node itself is the parent if parent[a] < 0 : return a # the parent of the node is updated, so future operations take constant time parent[a] = find_parent(parent[a]) return parent[a] for a,b in edges: pa = find_parent(a) pb = find_parent(b) # if both nodes have the same parent, a cycle is detected if pa == pb: return(a,b) else: # node with greater number of children is selected as parent node while merging. # the number of children in parent node is updated if parent[pa]<parent[pb]: parent[pa] += parent[pb] parent[pb] = pa else: parent[pb] += parent[pa] parent[pa] = pb
redundant-connection
Python Easy Solution Weighted union collapsed find. Faster than 96%
kaustav43
0
83
redundant connection
684
0.62
Medium
11,332
https://leetcode.com/problems/redundant-connection/discuss/1525367/Py3Py-Solution-using-union-find
class Solution: def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: # A function to get nodes def getNodes(edges): nodes = set() for edge in edges: nodes.add(edge[0]) nodes.add(edge[1]) return sorted(list(nodes)) # Init nodes = getNodes(edges) n = len(nodes) parent = [-1] * (n+1) rank = [0] * (n+1) # Find By Compression def findByCompression(node): nonlocal parent if parent[node] == -1: return node parent[node] = findByCompression(parent[node]) return parent[node] # Union By Rank def unionByRank(x,y) -> bool: nonlocal rank nonlocal parent parent_x = findByCompression(x) parent_y = findByCompression(y) if parent_x != parent_y: if rank[parent_x] >= rank[parent_y]: parent[parent_y] = parent_x rank[parent_x] += 1 else: parent[parent_x] = parent_y rank[parent_y] += 1 return True return False # Main Logic candidates = [] for x,y in edges: if not unionByRank(x,y): candidates.append([x,y]) return candidates[-1] # return the last edge which forms cycle
redundant-connection
[Py3/Py] Solution using union-find
ssshukla26
0
97
redundant connection
684
0.62
Medium
11,333
https://leetcode.com/problems/redundant-connection/discuss/1408261/python3-or-Union-find-Solution
class Solution: def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: self.makeset() return self.solve(edges) def makeset(self): self.parent=[i for i in range(10000)] self.rank=[0 for i in range(10000)] def findpar(self,node): if node==self.parent[node]: return node self.parent[node]=self.findpar(self.parent[node]) return self.parent[node] def union(self,node1,node2): node1_par=self.findpar(node1) node2_par=self.findpar(node2) if node1_par==node2_par: return True if self.rank[node1_par]<self.rank[node2_par]: self.parent[node1_par]=node2_par elif self.rank[node1_par]>self.rank[node2_par]: self.parent[node2_par]=node1_par else: self.parent[node2_par]=node1_par self.rank[node1_par]+=1 return False def solve(self,edges): ans=0 for i in range(len(edges)): if self.union(edges[i][0],edges[i][1]): ans=edges[i] return ans
redundant-connection
[python3] | Union find Solution
swapnilsingh421
0
36
redundant connection
684
0.62
Medium
11,334
https://leetcode.com/problems/redundant-connection/discuss/1378043/python-or-simple-or-better-than-99.5or-Union-find
class Solution: def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: dict={} n=len(edges) for i in range(1,n+1): dict[i]=i def find_parent(u): if dict[u]==u: return u else: a=find_parent(dict[u]) dict[u]=a return a for i,j in edges: u=find_parent(i) v=find_parent(j) if u==v: return [i,j] else: dict[v]=u
redundant-connection
python | simple | better than 99.5%| Union find
heisenbarg
0
142
redundant connection
684
0.62
Medium
11,335
https://leetcode.com/problems/repeated-string-match/discuss/330741/Simple-Python3-Solution-(beats-~100)-(my-first-post-on-LeetCode-!!!)
class Solution: def repeatedStringMatch(self, A: str, B: str) -> int: if set(B).issubset(set(A)) == False: return -1 for i in range(1,int(len(B)/len(A))+3): if B in A*i: return i return -1 - Python3 - Junaid Mansuri
repeated-string-match
Simple Python3 Solution (beats ~100%) (my first post on LeetCode !!!)
junaidmansuri
15
1,600
repeated string match
686
0.34
Medium
11,336
https://leetcode.com/problems/repeated-string-match/discuss/358857/Python3-an-alternative-solution-with-details
class Solution: def repeatedStringMatch(self, A: str, B: str) -> int: if len(A) >= len(B): if B in A: return 1 elif B in A*2: return 2 else: return -1 prefix = max(0, B.find(A)) #prefix -- length of A1 repeat, postfix = divmod(len(B)-prefix, len(A)) #postfix -- length of A2 repeat += bool(prefix) + bool(postfix) if B in A * repeat: return repeat else: return -1
repeated-string-match
[Python3] an alternative solution with details
ye15
4
218
repeated string match
686
0.34
Medium
11,337
https://leetcode.com/problems/repeated-string-match/discuss/358857/Python3-an-alternative-solution-with-details
class Solution: def repeatedStringMatch(self, a: str, b: str) -> int: n = ceil(len(b)/len(a)) # ceiling of len(b)/len(a) return next((n+i for i in range(2) if b in (n+i)*a), -1)
repeated-string-match
[Python3] an alternative solution with details
ye15
4
218
repeated string match
686
0.34
Medium
11,338
https://leetcode.com/problems/repeated-string-match/discuss/2818748/Python-oror-Easy-oror-96.76-Faster-oror-O(n)-Solution
class Solution: def repeatedStringMatch(self, a: str, b: str) -> int: if b in a: return 1 c,n=1,len(b) t=a while b!=t and len(t)<=n: c+=1 t=a*c if b in t: return c if b in a*(c+1): return c+1 return -1
repeated-string-match
Python || Easy || 96.76% Faster || O(n) Solution
DareDevil_007
1
55
repeated string match
686
0.34
Medium
11,339
https://leetcode.com/problems/repeated-string-match/discuss/2696409/Python3-Knuth-Morris-Pratt-Algorithm-O(oraor-%2B-orbor)-time-O(orbor)-space
class Solution: def repeatedStringMatch(self, a: str, b: str) -> int: def kmp_failure(pattern): # kmp failure function m = len(pattern) f = [0] * m i = 1 j = 0 while i < m: if pattern[j] == pattern[i]: f[i] = j+1 i += 1 j += 1 elif j > 0: j = f[j-1] else: f[i] = 0 i += 1 return f f = kmp_failure(b) n = len(a) m = len(b) i = 0 j = 0 while i < n + m: # worst case, start of b begins at end of a if b[j] == a[i%n]: if j == m-1: return math.ceil((i+1) / n) i += 1 j += 1 elif j > 0: j = f[j-1] else: i += 1 return -1
repeated-string-match
[Python3] Knuth Morris Pratt Algorithm - O(|a| + |b|) time, O(|b|) space
rt500
1
86
repeated string match
686
0.34
Medium
11,340
https://leetcode.com/problems/repeated-string-match/discuss/1587820/This-line-reduced-my-runtime-by-300-100-fasterany-languageWell-commented%2B-explained
class Solution: def repeatedStringMatch(self, a: str, b: str) -> int: # now this is an amazing thing, kinds works like math.ceil minreps = -(-len(b)//len(a)) # This line reduced my runtime by 300+% 108ms to 24ms # For other languages, here set is removing duplicated from string # set('aaaabbc')={ 'a', 'b', 'c' } if len(a)<=len(b) and set(a)!=set(b): return -1 # Explained above for i in range(minreps,minreps+2): if b in a*i: return i return -1
repeated-string-match
This line reduced my runtime by 300% [100% faster][any language][Well commented+ explained]
DivyanshSood
1
89
repeated string match
686
0.34
Medium
11,341
https://leetcode.com/problems/repeated-string-match/discuss/2299072/KMP-based-solution
class Solution: def repeatedStringMatch(self, a: str, b: str) -> int: if a == b: return 1 # return if a doesnt contain all unique characters of b even once char_a = set() for s in a: if s not in char_a: char_a.add(s) for t in b: if t not in char_a: return -1 org_a = a repeat = 1 n = len(b) # calculate pi for KMP pi = [0 for _ in range(n)] j = 0 for i in range(1, n): while j and b[i] != b[j]: j = pi[j-1] j += (b[i] == b[j]) pi[i] = j # a should be atleast of length b while len(a) < len(b): a += org_a repeat += 1 # KMP string search def strStr(s, t, pi): i = 0; j = 0 while i < len(s): if s[i] == t[j]: i += 1 j += 1 if j == len(t): return True elif j > 0: j = pi[j-1] else: i += 1 return False # keep looking until len(a) <= 2 * len(b) found = strStr(a, b, pi) while not found: if repeat == 1 or len(a) <= 2 * len(b): a += org_a repeat += 1 found = strStr(a, b, pi) continue else: break return repeat if found else -1
repeated-string-match
KMP based solution
sinha_meenu
0
65
repeated string match
686
0.34
Medium
11,342
https://leetcode.com/problems/repeated-string-match/discuss/1904458/Python3-oror-7-line-easy-code-O(1)-time-and-O(1)-space-oror-math
class Solution: def repeatedStringMatch(self, a: str, b: str) -> int: m, n = len(a), len(b) x = n // m inc = [0, 1, 2] for i in inc: if b in a * (x + i): return x + i return -1
repeated-string-match
Python3 || 7-line easy code O(1) time and O(1) space || math
gulugulugulugulu
0
234
repeated string match
686
0.34
Medium
11,343
https://leetcode.com/problems/repeated-string-match/discuss/408701/Easy-Python-Solution
class Solution: def repeatedStringMatch(self, A: str, B: str) -> int: if B in A: return 1 N = (len(B)//len(A))+2 t = A*N try: i = t.index(B) return N-((len(t)-(i+len(B)))//len(A)) except: return -1
repeated-string-match
Easy Python Solution
saffi
-2
417
repeated string match
686
0.34
Medium
11,344
https://leetcode.com/problems/longest-univalue-path/discuss/902315/Python3-dfs-(post-order)
class Solution: def longestUnivaluePath(self, root: TreeNode) -> int: def dfs(node): """Return longest univalue branch and longest univalue path (post-order traversal).""" if not node: return 0, 0 (lx, llup), (rx, rlup) = dfs(node.left), dfs(node.right) if not node.left or node.left.val != node.val: lx = 0 if not node.right or node.right.val != node.val: rx = 0 return 1 + max(lx, rx), max(llup, rlup, 1 + lx + rx) return max(0, dfs(root)[-1]-1)
longest-univalue-path
[Python3] dfs (post order)
ye15
4
215
longest univalue path
687
0.402
Medium
11,345
https://leetcode.com/problems/longest-univalue-path/discuss/902315/Python3-dfs-(post-order)
class Solution: def longestUnivaluePath(self, root: TreeNode) -> int: def dfs(node): """Return longest univalue branch and longest univalue path (post-order traversal).""" nonlocal ans if not node: return 0 lx, rx = dfs(node.left), dfs(node.right) if not node.left or node.left.val != node.val: lx = 0 if not node.right or node.right.val != node.val: rx = 0 ans = max(ans, 1 + lx + rx) return 1 + max(lx, rx) ans = 0 dfs(root) return max(0, ans-1)
longest-univalue-path
[Python3] dfs (post order)
ye15
4
215
longest univalue path
687
0.402
Medium
11,346
https://leetcode.com/problems/longest-univalue-path/discuss/1781613/DFS-best-time-%3A-9934-316-ms
class Solution: def longestUnivaluePath(self, root: Optional[TreeNode]) -> int: max_len = 0 def dfs(node): nonlocal max_len if not node.left and not node.right: # if not node: return 0 wide = 0 current_depth = 0 if node.left: left_depth = dfs(node.left) if node.left.val == node.val: wide += 1 + left_depth current_depth = max(current_depth, 1+left_depth) if node.right: right_depth = dfs(node.right) if node.right.val == node.val: wide += 1 + right_depth current_depth = max(current_depth, 1+right_depth) max_len = max(max_len, wide, current_depth) return current_depth if root: dfs(root) return max_len
longest-univalue-path
DFS best time : 99,34% 316 ms
luischuris14
0
134
longest univalue path
687
0.402
Medium
11,347
https://leetcode.com/problems/longest-univalue-path/discuss/1580412/Pyhton3-Solution
class Solution: def longestUnivaluePath(self, root: Optional[TreeNode]) -> int: self.ans = 0 def longestPath(node,value): if node: left,right = longestPath(node.left,node.val),longestPath(node.right,node.val) self.ans = max(self.ans,left+right) if value == node.val: return max(left,right)+1 return 0 longestPath(root,None) return self.ans
longest-univalue-path
Pyhton3 Solution
satyam2001
0
144
longest univalue path
687
0.402
Medium
11,348
https://leetcode.com/problems/longest-univalue-path/discuss/1506567/Python3-Solution-Faster-than-99.3-of-python-submissions
class Solution: def traverse(self,node): if not node:return 0 if not node.left and not node.right: if self.ans==0:self.ans=1 return 1 l=self.traverse(node.left) r=self.traverse(node.right) if node.left and node.right and node.left.val==node.right.val==node.val: if self.ans<l+r+1:self.ans=l+r+1 return l+1 if l+1>r+1 else r+1 if node.left and node.left.val==node.val: if self.ans<l+1:self.ans=l+1 return l+1 if node.right and node.right.val==node.val: if self.ans<r+1:self.ans=r+1 return r+1 return 1 def longestUnivaluePath(self, root: Optional[TreeNode]) -> int: self.ans=0 self.traverse(root) return self.ans-1 if self.ans>0 else 0
longest-univalue-path
Python3 Solution Faster than 99.3% of python submissions
reaper_27
0
97
longest univalue path
687
0.402
Medium
11,349
https://leetcode.com/problems/longest-univalue-path/discuss/993004/Python-3-Weird-Solution
class Solution: def longestUnivaluePathUtil(self, root: TreeNode, maxCounter) -> int: counter = 0 counterChoose = [0] if root!=None: if root.left!=None: temp = self.longestUnivaluePathUtil(root.left, maxCounter) + 1 if root.val==root.left.val: counterChoose.append(temp) counter+= temp if root.right!=None: temp = self.longestUnivaluePathUtil(root.right, maxCounter) + 1 if root.val==root.right.val: counter+= temp counterChoose.append(temp) maxCounter[0] = max(maxCounter[0], counter) return max(counterChoose) def longestUnivaluePath(self, root: TreeNode) -> int: maxCounter = [0] self.longestUnivaluePathUtil(root, maxCounter) return maxCounter[0]
longest-univalue-path
Python 3 Weird Solution
wildansupernova
0
182
longest univalue path
687
0.402
Medium
11,350
https://leetcode.com/problems/knight-probability-in-chessboard/discuss/2193242/Python3-DFS-with-DP-beats-99-()()-Explained
class Solution: def knightProbability(self, n: int, k: int, row0: int, col0: int) -> float: # precalculate possible moves adj_list = defaultdict(list) d = ((-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2), (-1, -2)) for row in range(n): for col in range(n): for dx, dy in d: pos = (row + dx, col + dy) if 0 <= pos[0] < n and 0 <= pos[1] < n: adj_list[(row, col)].append(pos) @cache def get_leafs_num(pos, h): if h == k: return 1 res = 0 for next_pos in adj_list[pos]: res += get_leafs_num(next_pos, h + 1) return res leafs_num = get_leafs_num((row0, col0), 0) return leafs_num / 8**k
knight-probability-in-chessboard
✔️ [Python3] DFS with DP, beats 99% ٩(๑・ิᴗ・ิ)۶٩(・ิᴗ・ิ๑)۶, Explained
artod
6
164
knight probability in chessboard
688
0.521
Medium
11,351
https://leetcode.com/problems/knight-probability-in-chessboard/discuss/1198319/Python-Solution-with-comments-Easy-to-understand-Runtime%3A-200-ms-Memory%3A-14.2-MB
class Solution: def knightProbability(self, n: int, k: int, row: int, column: int) -> float: # Define two states, current and next current = [[0 for _ in range(n)] for _ in range(n)] next1 = [[0 for _ in range(n)] for _ in range(n)] current[row][column] = 1 # Mark all possible moves of a knight in chessboard all_pos = [(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2),(2,-1),(1,-2)] for _ in range(k): # K moves for i in range(n): # board of size n * n for j in range(n): # start from cell [0,0] and check if current value is non-zero if current[i][j] != 0: for pos in all_pos: # For each valid moves from all_pos, add values to next steps temp_x = i + pos[0] temp_y = j + pos[1] if 0 <= temp_x < n and 0 <= temp_y < n: # If the knight is inside the board, then add current value divide by 8. next1[temp_x][temp_y] += (current[i][j] / 8) # We divided it by 8 as there are total 8 possibilities current, next1 = next1, [[0 for _ in range(n)] for _ in range(n)] # Assign next as current and redefine next as empty array. Now, we'll again fill this next array with values of current # Find total probability of the last state. That'll be current as we just swapped current &amp; next!! total_sum = 0 for item in current: total_sum += sum(item) return total_sum
knight-probability-in-chessboard
Python Solution with comments Easy to understand Runtime: 200 ms Memory: 14.2 MB
dakshal33
3
187
knight probability in chessboard
688
0.521
Medium
11,352
https://leetcode.com/problems/knight-probability-in-chessboard/discuss/902373/Python3-top-down-dp
class Solution: def knightProbability(self, N: int, K: int, r: int, c: int) -> float: @lru_cache(None) def fn(k, i, j): """Return probability in chessboard at (i, j) with k moves left.""" if not (0 <= i < N and 0 <= j < N): return 0 if k == 0: return 1 return 1/8*sum(fn(k-1, i+ii, j+jj) for ii, jj in ((-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1))) return fn(K, r, c)
knight-probability-in-chessboard
[Python3] top-down dp
ye15
2
58
knight probability in chessboard
688
0.521
Medium
11,353
https://leetcode.com/problems/knight-probability-in-chessboard/discuss/2846873/Yet-another-top-down-DP-with-an-%22extension%22
class Solution: def knightProbability(self, n: int, k: int, row: int, column: int) -> float: def oob(i, j): oox = i < 0 or i >= n ooy = j < 0 or j >= n return oox or ooy steps = [ (2, 1), (-2, 1), (2, -1), (-2, -1), (1, 2), (-1, 2), (1, -2), (-1, -2), ] @cache def dp(i, j, k): if oob(i, j): return (0, 1) if k == 0: return (1, 0) total = [0, 0] for dx, dy in steps: x, y = i + dx, j + dy success, failure = dp(x, y, k - 1) total[0] += success total[1] += failure return total success, failure = dp(row, column, k) return success / float(8 ** k)
knight-probability-in-chessboard
Yet another top-down DP, with an "extension"
kqf
0
2
knight probability in chessboard
688
0.521
Medium
11,354
https://leetcode.com/problems/knight-probability-in-chessboard/discuss/2821663/Python-(Simple-DP)
class Solution: @lru_cache(None) def knightProbability(self, n, k, row, column): if row < 0 or row > n-1 or column < 0 or column > n-1: return 0 if k == 0: return 1 directions = [(1,2),(1,-2),(-1,2),(-1,-2),(2,1),(2,-1),(-2,1),(-2,-1)] total = 0 for d in directions: total += (1/8)*self.knightProbability(n,k-1,row+d[0],column+d[1]) return total
knight-probability-in-chessboard
Python (Simple DP)
rnotappl
0
1
knight probability in chessboard
688
0.521
Medium
11,355
https://leetcode.com/problems/knight-probability-in-chessboard/discuss/2808392/PYTHON-DFS%2BMEMO-EASY-TO-UNDERSTAND
class Solution: def knightProbability(self, n: int, k: int, row: int, column: int) -> float: moveSet = ((-1,-2),(-2,-1),(-2,1),(-1,2),(1,2),(2,1),(2,-1),(1,-2)) @cache def dfs(currentRow,currentCol,movesLeft): # Return 0 if out of chess board if not (0 <= currentRow < n) or not (0 <= currentCol < n): return 0 # If remaining moves is 0: # since we know that current position is inside chess board from the if statement above, return 1 if movesLeft == 0: return 1 result = 0 # Try all possible moves for rowOffset,colOffset in moveSet: dfsResult = dfs(currentRow+rowOffset, currentCol+colOffset, movesLeft-1) result += dfsResult return result # ans / 8**k because there are 8**k possible moves ans = dfs(row,column,k) return ans/8**k
knight-probability-in-chessboard
PYTHON DFS+MEMO EASY TO UNDERSTAND
tupsr
0
2
knight probability in chessboard
688
0.521
Medium
11,356
https://leetcode.com/problems/knight-probability-in-chessboard/discuss/2786599/An-interesting-way-to-represent-the-directions.
class Solution: def knightProbability(self, n: int, k: int, row: int, column: int) -> float: # directions = [ # (-2, -1), (-1, -2), # (-2, 1), (-1, 2), # (1, -2), (2, -1), # (1, 2), (2, 1) # ] directions = [-1, -2, 1, 2, 1, -2, -1, 2, -1] @cache def helper(i, j, k): if k == 0: return 1 if 0 <= i < n and 0 <= j < n else 0 if i < 0 or i >= n or j < 0 or j >= n: return 0 mul = 1 / 8 ans = 0 for z in range(8): x, y = i + directions[z], j + directions[z + 1] ans += mul * helper(x, y, k - 1) return ans return helper(row, column, k)
knight-probability-in-chessboard
An interesting way to represent the directions.
yiming999
0
1
knight probability in chessboard
688
0.521
Medium
11,357
https://leetcode.com/problems/knight-probability-in-chessboard/discuss/2757883/Berkeley-computer-science-honor-society-solution-Dynamic-programming
class Solution: def knightProbability(self, n: int, k: int, row: int, column: int) -> float: """ let p[i][j][k] be the probability that our night remains on the chessboard from move k onwards. Then p[i][j][k] = sum over all reachable u, v 1/ 8 * p[u][v][k + 1] """ p = [[1]*n for _ in range(n)] for i in range(k - 1, -1, -1): new = [[0] * n for _ in range(n)] for u in range(n): for v in range(n): for r, c in [(u +1, v + 2), (u + 2, v + 1), (u - 1, v + 2), (u - 2, v + 1), (u + 1, v - 2), (u + 2, v - 1), (u - 2, v - 1), (u - 1, v - 2)]: if not ((0 <= r < n) and (0 <= c < n)): continue new[u][v] += p[r][c] * 1/8 p = new return p[row][column]
knight-probability-in-chessboard
Berkeley computer science honor society solution — Dynamic programming
berkeley_upe
0
5
knight probability in chessboard
688
0.521
Medium
11,358
https://leetcode.com/problems/knight-probability-in-chessboard/discuss/2408527/python-dp-with-hashtable
class Solution: def knightProbability(self, n: int, k: int, row: int, column: int) -> float: ht = {(row,column):1} for _ in range(k): nht = defaultdict(int) for (r,c),p in ht.items(): for dr,dc in [(1,2),(2,1),(-1,2),(2,-1),(1,-2),(-2,1),(-1,-2),(-2,-1)]: if 0<=r+dr<n and 0<=c+dc<n: nht[(r+dr,c+dc)] += p/8 ht = nht return sum(ht.values())
knight-probability-in-chessboard
python dp with hashtable
li87o
0
13
knight probability in chessboard
688
0.521
Medium
11,359
https://leetcode.com/problems/knight-probability-in-chessboard/discuss/1974591/DFS-with-built-in-functools'-cache-111ms-100.
class Solution: def knightProbability(self, n: int, k: int, r: int, c: int) -> float: '''moves definitions...''' return moves(r, c, k)/(8**k)
knight-probability-in-chessboard
DFS with built-in functools' cache, 111ms 100%.
Blueleaf
0
52
knight probability in chessboard
688
0.521
Medium
11,360
https://leetcode.com/problems/knight-probability-in-chessboard/discuss/1786608/Python-easy-to-read-and-understand-or-Memoization
class Solution: def dfs(self, n, row, col, moves): if row < 0 or col < 0 or row >= m or col >= n: return 0 if moves == 0: return 1 x1 = self.dfs(n, row - 2, col - 1, moves - 1) x2 = self.dfs(n, row - 1, col - 2, moves - 1) x3 = self.dfs(n, row + 1, col - 2, moves - 1) x4 = self.dfs(n, row + 2, col - 1, moves - 1) x5 = self.dfs(n, row + 2, col + 1, moves - 1) x6 = self.dfs(n, row + 1, col + 2, moves - 1) x7 = self.dfs(n, row - 1, col + 2, moves - 1) x8 = self.dfs(n, row - 2, col + 1, moves - 1) return (x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8) / 8 def knightProbability(self, n: int, k: int, row: int, column: int) -> float: return self.dfs(n, row, column, k)
knight-probability-in-chessboard
Python easy to read and understand | Memoization
sanial2001
0
107
knight probability in chessboard
688
0.521
Medium
11,361
https://leetcode.com/problems/knight-probability-in-chessboard/discuss/1786608/Python-easy-to-read-and-understand-or-Memoization
class Solution: def dfs(self, n, row, col, moves): if row < 0 or col < 0 or row >= n or col >= n: return 0 if moves == 0: return 1 if (row, col, moves) in self.dp: return self.dp[(row, col, moves)] x1 = self.dfs(n, row-2, col-1, moves-1) x2 = self.dfs(n, row-1, col-2, moves-1) x3 = self.dfs(n, row+1, col-2, moves-1) x4 = self.dfs(n, row+2, col-1, moves-1) x5 = self.dfs(n, row+2, col+1, moves-1) x6 = self.dfs(n, row+1, col+2, moves-1) x7 = self.dfs(n, row-1, col+2, moves-1) x8 = self.dfs(n, row-2, col+1, moves-1) self.dp[(row, col, moves)] = (x1+x2+x3+x4+x5+x6+x7+x8)/8 return self.dp[(row, col, moves)] def knightProbability(self, n: int, k: int, row: int, column: int) -> float: self.dp = {} return self.dfs(n, row, column, k)
knight-probability-in-chessboard
Python easy to read and understand | Memoization
sanial2001
0
107
knight probability in chessboard
688
0.521
Medium
11,362
https://leetcode.com/problems/knight-probability-in-chessboard/discuss/1592156/Easy-Python-or-100-Speed-or-Smart-Memoization-or-Input-Normalization
class Solution: def knightProbability(self, n, k, row, column): possible = (-2,-1,1,2) all_di_dj = tuple([ (di,dj) for di in possible for dj in possible if abs(di)+abs(dj)==3]) n1 = n-1 memo = {} def dfs(i,j,m): i = min(i,n1-i) j = min(j,n1-j) if j>i: i,j = j,i if (i,j,m) in memo: return memo[i,j,m] if not (0<=i<n and 0<=j<n): result = 0 elif m == 0: result = 1 else: result = sum( dfs(i+di,j+dj,m-1) for di,dj in all_di_dj )/8. memo[i,j,m] = result return result return dfs(row,column,k)
knight-probability-in-chessboard
Easy Python | 100% Speed | Smart Memoization | Input Normalization
Aragorn_
0
157
knight probability in chessboard
688
0.521
Medium
11,363
https://leetcode.com/problems/knight-probability-in-chessboard/discuss/1269498/Python-Memoization-Solution-Easy-to-Understand
class Solution: def knightProbability(self, n: int, k: int, row: int, column: int) -> float: memo = {} def dp(remaining_moves, curr_r, curr_c): # Check whether we have encountered the same sitaution before key = (remaining_moves, curr_r, curr_c) if key in memo: return memo[key] # When it goes out of board, we return 0 if curr_r < 0 or curr_r >= n or curr_c < 0 or curr_c >= n: return 0 # If we are still on the board, we have hound one possible way elif remaining_moves == 0: return 1 to_return = 0 for i in [-1, 1]: for j in [-2, 2]: to_return += dp(remaining_moves-1, curr_r+i, curr_c+j) for i in [-2, 2]: for j in [-1, 1]: to_return += dp(remaining_moves-1, curr_r+i, curr_c+j) # These two for loops can be merged as one by going through all the possibilities at one time, but it's easier to comprehend this way memo[key] = to_return # Memoize the solution return to_return # Total number of valid moves / Total number of ways to move the knight return dp(k, row, column)/(8**k)
knight-probability-in-chessboard
Python - Memoization Solution - Easy to Understand
yashjain039
0
103
knight probability in chessboard
688
0.521
Medium
11,364
https://leetcode.com/problems/knight-probability-in-chessboard/discuss/1208729/Simplest-Python3-top-down-DP-solution
class Solution: def knightProbability(self, n: int, k: int, r: int, c: int) -> float: dims = [[1, 2], [2, 1], [-1, 2], [-2, 1], [2, -1], [1, -2], [-1, -2], [-2, -1]] @cache def dp(r, c, k): if r < 0 or c < 0 or r >= n or c >= n: return 0 if k == 0: return 1 return sum(dp(r + i, c + j, k - 1) for i, j in dims) return dp(r, c, k) / (8 ** k)
knight-probability-in-chessboard
Simplest Python3 top-down DP solution
bharadwaj6
0
50
knight probability in chessboard
688
0.521
Medium
11,365
https://leetcode.com/problems/knight-probability-in-chessboard/discuss/820683/Python3-or-simple-solution-or-dynamic-programming
class Solution: def __init__(self): self.possibleMoves = [(-2,1),(-1,2),(1,2),(2,1),(2,-1),(1,-2),(-1,-2),(-2,-1)] self.mem = dict() def isInside(self, r, c, N): if r < 0 or c < 0 or r >= N or c >= N: return False return True def Util(self, N, K, r, c): if K == 0: return 1 if (K, r, c) in self.mem: return self.mem[(K, r, c)] total = 0 for i, j in self.possibleMoves: if self.isInside(r + i, c + j, N): corMoves = self.Util(N, K - 1, r + i, c + j) total += corMoves self.mem[(K, r, c)] = total return total def knightProbability(self, N: int, K: int, r: int, c: int) -> float: totalPossible = self.Util(N, K, r, c) return totalPossible / 8 ** K
knight-probability-in-chessboard
Python3 | simple solution | dynamic programming
_YASH_
0
61
knight probability in chessboard
688
0.521
Medium
11,366
https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/discuss/1342651/Python3-dp
class Solution: def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]: prefix = [0] for x in nums: prefix.append(prefix[-1] + x) @cache def fn(i, n): """Return max sum of 3 non-overlapping subarrays.""" if n == 0: return [] if i+k >= len(prefix): return [] return max([i] + fn(i+k, n-1), fn(i+1, n), key=lambda x: sum(prefix[xx+k] - prefix[xx] for xx in x)) return fn(0, 3)
maximum-sum-of-3-non-overlapping-subarrays
[Python3] dp
ye15
1
73
maximum sum of 3 non overlapping subarrays
689
0.489
Hard
11,367
https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/discuss/1342651/Python3-dp
class Solution: def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]: rs0, rs1, rs2 = sum(nums[:k]), sum(nums[k:2*k]), sum(nums[2*k:3*k]) m0, m1, m2 = rs0, rs0 + rs1, rs0 + rs1 + rs2 i0, i1, i2 = [0], [0, k], [0, k, 2*k] for i in range(len(nums)-3*k): rs0 += nums[i+k] - nums[i] rs1 += nums[i+2*k] - nums[i+k] rs2 += nums[i+3*k] - nums[i+2*k] if rs0 > m0: m0, i0 = rs0, [i+1] if m0 + rs1 > m1: m1, i1 = m0 + rs1, i0 + [i+k+1] if m1 + rs2 > m2: m2, i2 = m1 + rs2, i1 + [i+2*k+1] return i2
maximum-sum-of-3-non-overlapping-subarrays
[Python3] dp
ye15
1
73
maximum sum of 3 non overlapping subarrays
689
0.489
Hard
11,368
https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/discuss/2826582/python-solution-with-comments
class Solution: def maxSumOfThreeSubarrays(self,nums, k): n=len(nums) left=[0]*n right=[0]*n p_sum=[0]*n sum=0 #this is calculating the left sum of k-subarray #and saving the max(sum of subarray , sum of prev subarray) for i in range(len(nums)): if i<k: sum+=nums[i] left[i]=sum else: sum=sum+nums[i]-nums[i-k] left[i]=max(sum , left[i-1]) sum=0 #this is calculating the right sum of k-subarray #and saving the max(sum of subarray , sum of prev subarray) for i in range(n-1 , -1 , -1): if i+k >=n: sum+=nums[i] right[i]=sum else: sum=sum-nums[i+k]+nums[i] right[i]=max(sum , right[i+1]) #this is calculating the prefix_sum for i in range(n): if i==0: p_sum[i]=nums[i] else: p_sum[i]=p_sum[i-1]+nums[i] # print(left , right , p_sum , left_ind, right_ind) res_tot=0 res_ind=[] left_sum=0 left_ind=-1 right_sum=0 right_ind=-1 mid_ind=-1 #here we are trying to find the middle sub-array max((mid -array using prefix-sum) + max-left-array(from our left array)+right(from our right array)) and saving the values of left , right and middle for i in range(k , len(nums)-2*k+1): t=max(res_tot,left[i-1] + (p_sum[i+k-1]-p_sum[i-1]) + right[i+k]) if t!=res_tot: res_tot=t left_sum=left[i-1] right_sum=right[i+k] mid_sum= (p_sum[i+k-1]-p_sum[i-1]) # while( r>i+k): # print('index' , r) # if right_ind[r]==right_ind[r-1]: # r=r-1 # else: # break # print(left_sum ,mid_sum , right_sum) # print(left , right , p_sum) #now using our prefix sum again we are finding the indexes of the values in left , mid and right while checking for non-overlaping indexes using contraints like {abs(k-i-1)>=mid_ind+k and abs(k-i-1)>=left_ind+k} for i in range(k-1 , len( p_sum)): if k-i-1==0: prev_sum=0 else: prev_sum=p_sum[i-k] if p_sum[i]-prev_sum==left_sum and left_ind==-1: left_ind=abs(k-i-1) elif p_sum[i]-prev_sum==mid_sum and mid_ind==-1 and abs(k-i-1)>=left_ind+k: mid_ind=abs(k-i-1) elif p_sum[i]-prev_sum==right_sum and right_ind==-1 and abs(k-i-1)>=mid_ind+k and abs(k-i-1)>=left_ind+k: right_ind=abs(k-i-1) # print(i , left_ind ,mid_ind ,right_ind) res_ind= [left_ind , mid_ind , right_ind] return res_ind
maximum-sum-of-3-non-overlapping-subarrays
python solution with comments
sintin1310
0
3
maximum sum of 3 non overlapping subarrays
689
0.489
Hard
11,369
https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/discuss/2750571/Python-3-One-Pass-O(1)-Space-Solution
class Solution: def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]: n = len(nums) s0 = sum(nums[:k]) # sum of the first subarray r0 = [s0, 0] # max of the first subarray and its starting index s1 = sum(nums[k:(2*k)]) # sum of the second subarray r1 = [r0[0]+s1, 0, k] # max of the sum of the first two subarrays and their starting indices s2 = sum(nums[(2*k):(3*k)]) # sum of the third subarray r2 = [r1[0]+s2, 0, k, 2*k] # max of the sum of all three subarrays and their starting indices idx = [1, k+1, 2*k+1] while idx[2] < n-k+1: # using a sliding window approach s0 += nums[idx[0]+k-1] - nums[idx[0]-1] # find the max of the first one, two, three subarrays by turn if s0 > r0[0]: r0 = [s0, idx[0]] s1 += nums[idx[1]+k-1] - nums[idx[1]-1] if s1 + r0[0] > r1[0]: r1 = [s1+r0[0], r0[1], idx[1]] s2 += nums[idx[2]+k-1] - nums[idx[2]-1] if s2 + r1[0] > r2[0]: r2 = [s2+r1[0], r1[1], r1[2], idx[2]] idx[0] += 1 idx[1] += 1 idx[2] += 1 return [r2[1], r2[2], r2[3]]
maximum-sum-of-3-non-overlapping-subarrays
Python 3 One Pass O(1) Space Solution
Rinnegan_Sep
0
7
maximum sum of 3 non overlapping subarrays
689
0.489
Hard
11,370
https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/discuss/2750100/easy-and-intuitive-solution-to-maxSumOfThreeSubarray-using-kadens-algo
class Solution: def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]: ans = 0 n = len(nums) #stores the sum of maximum sum subarray of lenght k for starting dp1 = [0]*len(nums) #stores the sum of maximum sum subarray of lenght k for ending dp2 = [0]*len(nums) sum2 = 0 for i in range(len(nums)): if i < k: sum2 += nums[i] dp1[i] = sum2 else: sum2 += nums[i] - nums[i-k] dp1[i] = max(dp1[i-1],sum2) sum1 = 0 for j in range(n-1,-1,-1): if j+k >= n: sum1 += nums[j] dp2[j] = sum1 else: sum1 += nums[j] - nums[j+k] dp2[j] = max(dp2[j+1],sum1) left = -1 middle = -1 right = -1 for i in range(k,n-2*k+1): if dp1[i-1] + sum(nums[i:i+k]) + dp2[i+k] > ans: ans = dp1[i-1] + sum(nums[i:i+k]) + dp2[i+k] leftsum = dp1[i-1] rightsum = dp2[i+k] middle = i for i in range(n): if sum(nums[i:i+k])== leftsum: left = i break for j in range(middle+k,n): if sum(nums[j:j+k]) == rightsum: right = j break return [left,middle,right]
maximum-sum-of-3-non-overlapping-subarrays
easy and intuitive solution to maxSumOfThreeSubarray using kadens algo
neeshumaini55
0
6
maximum sum of 3 non overlapping subarrays
689
0.489
Hard
11,371
https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/discuss/300968/python3-solution-with-comment
class Solution: def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]: n = len(nums) curr = sum(nums[:k]) # groups of sum-k g = [0]*n for i in range(n-k+1): g[i] = curr if i+k < n: curr += nums[i+k] - nums[i] # pre[i]: the previous group index with maximum sum when i is the center group pre = [0]*n for i in range(k+1, n-2*k+1): pre[i] = pre[i-1] if g[pre[i-1]] >= g[i-k] else i-k # after[i]: the next group index with maximum sum when i is the center group after = [n-k]*n for i in range(n-2*k, k-1, -1): after[i] = after[i+1] if g[after[i+1]] > g[i+k] else i+k # Final iteration: find the maximum total sum with their group index ans = [] S = 0 for i in range(k, n-2*k+1): curr = g[pre[i]] + g[i] + g[after[i]] if curr > S: S = curr ans = [pre[i], i, after[i]] return ans
maximum-sum-of-3-non-overlapping-subarrays
python3 solution with comment
dengl11
0
189
maximum sum of 3 non overlapping subarrays
689
0.489
Hard
11,372
https://leetcode.com/problems/employee-importance/discuss/332600/Iterative-Python-beats-99.73
class Solution: def getImportance(self, employees, id): """ :type employees: Employee :type id: int :rtype: int """ id_to_emp = {employee.id: employee for employee in employees} importance = 0 stack = [id_to_emp[id]] while stack: cur_emp = stack.pop() importance += cur_emp.importance stack.extend([id_to_emp[new_emp] for new_emp in cur_emp.subordinates]) return importance
employee-importance
Iterative Python, beats 99.73%
hgrsd
5
962
employee importance
690
0.652
Medium
11,373
https://leetcode.com/problems/employee-importance/discuss/1724402/Simple-Python-solution-using-deque-(BFS)
class Solution: def getImportance(self, employees: List['Employee'], id: int) -> int: emap = {e.id: e for e in employees} q=deque([id]) ans=0 while q: emp_id=q.popleft() ans+=emap[emp_id].importance for sub in emap[emp_id].subordinates: q.append(sub) return ans
employee-importance
Simple Python 🐍 solution using deque (BFS)
InjySarhan
3
109
employee importance
690
0.652
Medium
11,374
https://leetcode.com/problems/employee-importance/discuss/1262245/Python-solution
class Solution: def getImportance(self, employees: List['Employee'], id: int) -> int: s = {} for employee in employees: s[employee.id] = employee queue = [id] value = 0 while queue: employee_id = queue.pop() employee = s[employee_id] value += employee.importance queue.extend(employee.subordinates) return value
employee-importance
Python solution
5tigerjelly
3
197
employee importance
690
0.652
Medium
11,375
https://leetcode.com/problems/employee-importance/discuss/544773/Python-simple-solution-148-ms-13.1-MB-O(n)-complexity
class Solution(object): def getImportance(self, employees, id): """ :type employees: List[Employee] :type id: int :rtype: int """ employee_dict = dict() for employee in employees: employee_dict[employee.id] = [employee.importance, employee.subordinates] if employee.id == id: subordinates = employee.subordinates importance = employee.importance return self.count_importance(employee_dict, subordinates) + importance def count_importance(self, employee_dict, subordinates): importance = 0 for i in subordinates: importance += employee_dict[i][0] new_subordinates = employee_dict[i][1] if new_subordinates > 0: importance += self.count_importance(employee_dict, new_subordinates) return importance
employee-importance
Python simple solution 148 ms, 13.1 MB, O(n) complexity
hemina
2
300
employee importance
690
0.652
Medium
11,376
https://leetcode.com/problems/employee-importance/discuss/404945/Easy-to-understand-python3-beats-92.78-(hashmap-%2B-bfs)
class Solution: def getImportance(self, employees, id): employee_dict = dict() queue = [id] importance_sum = 0 for employee in employees: employee_dict[employee.id] = employee while(queue): employee_index = queue.pop(0) employee = employee_dict[employee_index] importance_sum += employee.importance queue.extend(employee.subordinates) return importance_sum
employee-importance
Easy to understand python3, beats 92.78% (hashmap + bfs)
eva_hiew
2
316
employee importance
690
0.652
Medium
11,377
https://leetcode.com/problems/employee-importance/discuss/1418982/Python-hash-map-faster-than-84
class Solution: def getImportance(self, employees: List['Employee'], id: int) -> int: emap = {} for employee in employees: emap[employee.id] = employee def helper(id): e = emap[id] total = e.importance for id in e.subordinates: total += helper(id) return total return helper(id)
employee-importance
Python hash map faster than 84%
rohanahire88
1
40
employee importance
690
0.652
Medium
11,378
https://leetcode.com/problems/employee-importance/discuss/551903/Python3-solution-using-recursion
class Solution: def getImportance(self, employees: List['Employee'], id: int) -> int: for person in employees: if person.id == id: if len(person.subordinates) == 0: return person.importance else: result = 0 for num in person.subordinates: result += self.getImportance(employees, num) return person.importance + result
employee-importance
Python3 solution using recursion
altareen
1
95
employee importance
690
0.652
Medium
11,379
https://leetcode.com/problems/employee-importance/discuss/533605/Easy-Python3-DFS-solution-faster-than-88-with-comments
class Solution: def getImportance(self, employees: List['Employee'], id: int, emps={}) -> int: # Populate the dictionary mapping id to employee if not emps: emps = {emp.id: emp for emp in employees} # Add the total value of every subordinate to the current employee for sub in emps[id].subordinates: emps[id].importance += self.getImportance(employees, sub, emps) # Return the total value of the current employee return emps[id].importance
employee-importance
Easy Python3 DFS solution, faster than 88%, with comments
jhacker
1
269
employee importance
690
0.652
Medium
11,380
https://leetcode.com/problems/employee-importance/discuss/359396/Python3-BFS-and-iterative-DFS
class Solution: def getImportance(self, employees, id): employees = {employee.id: employee for employee in employees} importance = 0 queue = [id] #id queue for id in queue: employee = employees[id] importance += employee.importance queue += employee.subordinates return importance
employee-importance
[Python3] BFS & iterative DFS
ye15
1
102
employee importance
690
0.652
Medium
11,381
https://leetcode.com/problems/employee-importance/discuss/359396/Python3-BFS-and-iterative-DFS
class Solution: def getImportance(self, employees: List['Employee'], id: int) -> int: mp = {x.id: x for x in employees} ans = 0 stack = [id] while stack: x = stack.pop() ans += mp[x].importance stack.extend(mp[x].subordinates) return ans
employee-importance
[Python3] BFS & iterative DFS
ye15
1
102
employee importance
690
0.652
Medium
11,382
https://leetcode.com/problems/employee-importance/discuss/2838828/Python-recursive-solution
class Solution: def getImportance(self, employees: List['Employee'], id: int) -> int: # convert list to dictonary id-->employee O(n) # search the id in list O(1) # itrate all subtrees and accumulate importance O(n) id_to_emp = {e.id: e for e in employees} def get_importnace(id): curr_emp = id_to_emp.get(id) curr_importance = curr_emp.importance for id in curr_emp.subordinates: curr_importance += get_importnace(id) return curr_importance return get_importnace(id)
employee-importance
Python recursive solution
sharonhadar2
0
1
employee importance
690
0.652
Medium
11,383
https://leetcode.com/problems/employee-importance/discuss/1416203/Python-3-Simple-and-Fast-Recursive-Solution-Using-Cache
class Solution: def getImportance(self, employees: List['Employee'], id: int) -> int: self.cache = dict([(emp.id, emp) for emp in employees]) return self.helper(id) def helper(self, id): employee = self.cache[id] importance = employee.importance if len(employee.subordinates) == 0: return importance for emp_id in employee.subordinates: importance += self.helper(emp_id) return importance
employee-importance
[Python 3] Simple and Fast Recursive Solution Using Cache
thecleancoder2061
0
33
employee importance
690
0.652
Medium
11,384
https://leetcode.com/problems/employee-importance/discuss/1309662/Python3-dollarolution-(memory-usage-95-better)
class Solution: def getImportance(self, employees: List['Employee'], id: int) -> int: v, s = [id], 0 while v != []: for i in employees: if i.id == v[0]: v += i.subordinates v = v[1:] s += i.importance break return s
employee-importance
Python3 $olution (memory usage 95% better)
AakRay
0
122
employee importance
690
0.652
Medium
11,385
https://leetcode.com/problems/employee-importance/discuss/660346/python-bfs-solution-faster-than-86.53
class Solution: def getImportance(self, employees: List['Employee'], id: int) -> int: employee_subordinate_map = {} employee_importance_map = {} importance = 0 for employee in employees: employee_subordinate_map[employee.id] = employee.subordinates employee_importance_map[employee.id] = employee.importance visited_employees = set() queue = [id] while queue: employee = queue.pop(0) importance += employee_importance_map[employee] visited_employees.add(employee) for i in employee_subordinate_map.get(employee): if i not in visited_employees: queue.append(i) return importance
employee-importance
python bfs solution faster than 86.53%
darshan_22
0
92
employee importance
690
0.652
Medium
11,386
https://leetcode.com/problems/employee-importance/discuss/297134/Python-faster-than-95-156-ms
class Solution(object): def getImportance(self, employees, id): """ :type employees: Employee :type id: int :rtype: int """ d = dict() for node in employees: d[node.id] = node def Importance(node): if len(node.subordinates)==0: return node.importance else: S = node.importance for _id in node.subordinates: S += Importance(d[_id]) return S return Importance(d[id])
employee-importance
Python - faster than 95%, 156 ms
il_buono
0
323
employee importance
690
0.652
Medium
11,387
https://leetcode.com/problems/stickers-to-spell-word/discuss/1366983/Python3-dp
class Solution: def minStickers(self, stickers: List[str], target: str) -> int: freqs = [Counter(x) for x in stickers] @cache def fn(x): """Return min sticks to give x.""" if not x: return 0 ans = inf freq = Counter(x) for cnt in freqs: if x[0] in cnt: xx = "".join(k*v for k, v in (freq - cnt).items()) ans = min(ans, 1 + fn(xx)) return ans ans = fn(target) return ans if ans < inf else -1
stickers-to-spell-word
[Python3] dp
ye15
4
234
stickers to spell word
691
0.463
Hard
11,388
https://leetcode.com/problems/stickers-to-spell-word/discuss/2396941/faster-than-100.00-or-python
class Solution: def minStickers(self, stickers: List[str], target: str) -> int: tcount = Counter(target) def getScore(s): temp = dict(tcount) sdict = defaultdict(int) res = 0 for c in s: if c in temp and temp[c] > 0: temp[c] -= 1 res += 1 sdict[c] += 1 return (res, sdict) stickers = [getScore(s) for s in stickers] stickers.sort(key = lambda x: x[0], reverse = True) stickers = [x[1] for x in stickers if x[0] > 0] opt = [stickers[0]] for i in range(1, len(stickers)): if opt[-1].keys() == stickers[i].keys() : continue opt.append(stickers[i]) stickers = opt[:] seen = set() q = deque([target]) step = 0 while q: n = len(q) step += 1 for i in range(n): cur = q.popleft() if cur in seen: continue seen.add(cur) for stick in stickers: if cur[0] not in stick: continue new = str(cur) for s in stick: new = new.replace(s,'', stick[s]) if new == "": return step if new not in seen: q.append(new) return -1
stickers-to-spell-word
faster than 100.00% | python
vimla_kushwaha
3
428
stickers to spell word
691
0.463
Hard
11,389
https://leetcode.com/problems/stickers-to-spell-word/discuss/2415514/Python-or-BFS-solution
class Solution: @staticmethod def substract(c1, c2): # remove intersection of c1 and c2 from c2 and encode the c1 to string remove_keys = [] result = "" for k in c1.keys(): if k in c2: c1[k] -= c2[k] if c1[k] <= 0: remove_keys.append(k) if c1[k] > 0: result += k + str(c1[k]) for key in remove_keys: c1.pop(key, None) return c1, result def minStickers(self, stickers: List[str], target: str) -> int: # count all letters in target target_count = Counter(target) stickers_counter = [] s1 = set(target_count.keys()) s2 = set() # count all letters which are exist in target for every sticker for i in range(len(stickers)): sticker = stickers[i] sticker_counter = defaultdict(int) for letter in sticker: if letter in target_count: sticker_counter[letter] += 1 stickers_counter.append(sticker_counter) s2.update(sticker_counter.keys()) if s2 != s1: return -1 total_letters = sum(target_count.values()) counter = 0 q = deque([target_count]) visited = set() # BFS loop to find the shortest path to get empty target dict while q: q_size = len(q) for _ in range(q_size): target_count = q.popleft() for sticker in stickers_counter: tmp, encoded = self.substract(target_count.copy(), sticker) if sum(tmp.values()) == 0: return counter+1 if encoded not in visited: q.append(tmp) visited.add(encoded) counter += 1 return -1
stickers-to-spell-word
Python | BFS solution
pivovar3al
1
209
stickers to spell word
691
0.463
Hard
11,390
https://leetcode.com/problems/stickers-to-spell-word/discuss/2396935/python-or-beats-99.33-or-moderate-solution
class Solution: def minStickers(self, stickers: List[str], target: str) -> int: tf={} for c in target: if c not in tf: tf[c]=0 tf[c]+=1 w2f={} for word in stickers: w2f[word]={} for c in word: if c in tf: if c not in w2f[word]: w2f[word][c]=0 w2f[word][c]+=1 res=float('inf') ## remove dominated words def dominate(a,b): for c in w2f[b]: if c in w2f[a] and w2f[a][c]>=w2f[b][c]: continue else: return False return True for w in stickers: if w not in w2f:continue for w2 in stickers: if w2!=w and w2 in w2f and dominate(w2,w): del w2f[w] break def helper(ct, charhas, i): nonlocal res if ct>=res: return if i==len(target): res=min(res,ct) return ch=target[i] if charhas[ch]>0: charhas[ch]-=1 helper(ct,charhas,i+1) charhas[ch]+=1 else: for w in w2f: if ch not in w:continue for c in w2f[w]: charhas[c]+=w2f[w][c] helper(ct+1,charhas,i) for c in w2f[w]: charhas[c]-=w2f[w][c] return helper(0,defaultdict(int),0) return res if res<float('inf') else -1
stickers-to-spell-word
python | beats 99.33% | moderate solution
vimla_kushwaha
1
121
stickers to spell word
691
0.463
Hard
11,391
https://leetcode.com/problems/stickers-to-spell-word/discuss/2816656/From-recursion-to-memoized
class Solution: def minStickers(self, stickers: List[str], target: str) -> int: stickers = [Counter(s) for s in stickers if set(s)&amp;set(target)] def generate(target): if not target: return 0 target_counter = Counter(target) res = float("inf") for sticker in stickers: if sticker[target[0]] == 0: continue tmp = 1 + generate("".join([letter*count for letter,count in (target_counter-sticker).items()])) res = min(res,tmp) return res res = generate(target) return -1 if res == float("inf") else res
stickers-to-spell-word
From recursion to memoized
shriyansnaik
0
6
stickers to spell word
691
0.463
Hard
11,392
https://leetcode.com/problems/stickers-to-spell-word/discuss/2816656/From-recursion-to-memoized
class Solution: def minStickers(self, stickers: List[str], target: str) -> int: stickers = [Counter(s) for s in stickers if set(s)&amp;set(target)] dp = {} def generate(target): if not target: return 0 if target in dp: return dp[target] target_counter = Counter(target) res = float("inf") for sticker in stickers: if sticker[target[0]] == 0: continue tmp = 1 + generate("".join([letter*count for letter,count in (target_counter-sticker).items()])) res = min(res,tmp) dp[target] = res return res res = generate(target) return -1 if res == float("inf") else res
stickers-to-spell-word
From recursion to memoized
shriyansnaik
0
6
stickers to spell word
691
0.463
Hard
11,393
https://leetcode.com/problems/top-k-frequent-words/discuss/1657648/Simple-or-4-lines-or-using-heap-or-With-explanation
class Solution: def topKFrequent(self, words: List[str], k: int) -> List[str]: #Have a dict of word and its freq counts = collections.Counter(words) #get a array wchich will have a tuple of word and count heap = [(-count, word) for word, count in counts.items()] #as default heap structure in python min heap and we want max heap # to get top frequent word, we will do a make the counter negative #so that the topmost element will come up (i.e -8 < -2 so in min heap -8 will come up wich is actually 8) heapq.heapify(heap) #creating heap in place #by deualt it will sort by fre then word return [heapq.heappop(heap)[1] for _ in range(k)]
top-k-frequent-words
Simple | 4 lines | using heap | With explanation
shraddhapp
25
2,000
top k frequent words
692
0.569
Medium
11,394
https://leetcode.com/problems/top-k-frequent-words/discuss/1648996/Python-3-oror-4-liner-oror-hashmap
class Solution: def topKFrequent(self, words, k): dicktionary = defaultdict(int) for i in words: dicktionary[i] += 1 sorted_dick = sorted(dicktionary.items(), key=lambda x: (-x[1], x[0])) return [i[0] for i in sorted_dick][:k]
top-k-frequent-words
Python-3 || 4-liner || hashmap
samek571
6
408
top k frequent words
692
0.569
Medium
11,395
https://leetcode.com/problems/top-k-frequent-words/discuss/2720472/Short-and-sweet-solution.-Beats-97-space-82-time
class Solution: def topKFrequent(self, words: List[str], k: int) -> List[str]: d = {} for word in words: d[word] = d.get(word, 0) + 1 res = sorted(d, key=lambda word: (-d[word], word)) return res[:k]
top-k-frequent-words
Short and sweet solution. Beats 97% space, 82% time
sukumar-satapathy
4
379
top k frequent words
692
0.569
Medium
11,396
https://leetcode.com/problems/top-k-frequent-words/discuss/2721136/Python-Solution-oror-10-lines-of-code-oror-Easy-to-Understand
class Solution: def topKFrequent(self, words: List[str], k: int) -> List[str]: counts={} for word in words: counts[word]=counts.get(word,0)+1 s_dict = {val[0] : val[1] for val in sorted(counts.items(), key = lambda x: (-x[1], x[0]))} # print(s_dict) lst=[] x=0 for i,j in s_dict.items(): if(x<k): lst.append(i) x+=1 return lst
top-k-frequent-words
Python Solution🔥 || 10 lines of code✅ || Easy to Understand✌️
jhadevansh0809
3
455
top k frequent words
692
0.569
Medium
11,397
https://leetcode.com/problems/top-k-frequent-words/discuss/404646/Python-3-(one-line)
class Solution: def topKFrequent(self, W: List[str], k: int) -> List[str]: C = collections.Counter(W) S = sorted(C.keys(), key = lambda x: [-C[x],x]) return S[:k]
top-k-frequent-words
Python 3 (one line)
junaidmansuri
3
774
top k frequent words
692
0.569
Medium
11,398
https://leetcode.com/problems/top-k-frequent-words/discuss/404646/Python-3-(one-line)
class Solution: def topKFrequent(self, W: List[str], k: int) -> List[str]: return list(zip(*collections.Counter(sorted(W)).most_common(k)))[0] - Junaid Mansuri
top-k-frequent-words
Python 3 (one line)
junaidmansuri
3
774
top k frequent words
692
0.569
Medium
11,399