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 ...
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...
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 o...
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) ...
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() ...
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:])...
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]) ...
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)) ...
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 == '+': ...
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)) ...
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: ...
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] + ne...
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: ...
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":...
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...
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": ...
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() ...
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...
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": ...
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.appe...
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]) st...
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] ...
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 ...
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()]): f...
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] de...
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|+|...
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 ...
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 ...
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]] ...
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 # ^ ^ # | | ...
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 c...
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...
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 sort...
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[no...
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: ...
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)) #postf...
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 -...
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]: ...
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 ...
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: ...
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) ...
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) ...
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 ...
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) ...
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==...
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: ...
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): ...
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 al...
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 ...
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),...
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 ...
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 ...
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] ...
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 _ ...
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),(-...
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...
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...
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...
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...
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: ...
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, ...
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 [] ...
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): r...
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)): ...
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...
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 ...
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] #...
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: cu...
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].su...
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[e...
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.subordin...
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) employ...
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...
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 ...
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 ...
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 += emplo...
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) ret...
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_i...
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(emplo...
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 ...
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_im...
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.subor...
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...
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: ...
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: ...
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...
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") ...
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] targe...
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()] ...
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=[] ...
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