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/rotate-function/discuss/1947965/python-3-oror-simple-O(n)O(1)
class Solution: def maxRotateFunction(self, nums: List[int]) -> int: f = res = sum(i * num for i, num in enumerate(nums)) n, s = len(nums), sum(nums) for i in range(n - 1, 0, -1): f += s - n*nums[i] res = max(res, f) return res
rotate-function
python 3 || simple O(n)/O(1)
dereky4
0
116
rotate function
396
0.404
Medium
6,900
https://leetcode.com/problems/rotate-function/discuss/704425/Python3-math-solution-Rotate-Function
class Solution: def maxRotateFunction(self, A: List[int]) -> int: total = sum(A) ans = cur = sum(i * n for i, n in enumerate(A)) for i in range(len(A)-1, 0, -1): cur += total - len(A) * A[i] ans = max(ans, cur) return ans
rotate-function
Python3 math solution - Rotate Function
r0bertz
0
296
rotate function
396
0.404
Medium
6,901
https://leetcode.com/problems/integer-replacement/discuss/663134/Two-solution-in-Python
class Solution: def integerReplacement(self, n: int) -> int: cnt = 0 while n != 1: if n%2 == 0: n//=2 elif n%4 == 1 or n == 3: n -= 1 else: n += 1 cnt += 1 return cnt
integer-replacement
Two solution in Python
realslimshady
4
351
integer replacement
397
0.352
Medium
6,902
https://leetcode.com/problems/integer-replacement/discuss/663134/Two-solution-in-Python
class Solution: def integerReplacement(self, n: int) -> int: def helper(n, memo): if n in memo: return memo[n] elif n%2: memo[n] = 1 + min(helper(n-1,memo), helper(n+1,memo)) return memo[n] else: memo[n] = 1 ...
integer-replacement
Two solution in Python
realslimshady
4
351
integer replacement
397
0.352
Medium
6,903
https://leetcode.com/problems/integer-replacement/discuss/2644141/Easy-understand-python-solution-with-explanation-oror-Beats-91-of-the-python-solution.
class Solution: def integerReplacement(self, n: int) -> int: dp={} dp[0]=0 dp[1]=0 moves=0 def recur(n): if n in dp: return dp[n] if n%2==0: dp[n]=1+recur(n//2) else: dp[n]=1+min(recur(n-1),re...
integer-replacement
Easy understand python solution with explanation || Beats 91 % of the python solution.
code_is_in_my_veins
2
137
integer replacement
397
0.352
Medium
6,904
https://leetcode.com/problems/integer-replacement/discuss/706015/Python3-O(n)-solution-Integer-Replacement
class Solution: def integerReplacement(self, n: int) -> int: ans = 0 while n > 1: if n % 2: if n > 3 and n & 1 == 1 and (n >> 1) & 1 == 1: n += 1 else: n -= 1 ans += 1 n //= 2 ...
integer-replacement
Python3 O(n) solution - Integer Replacement
r0bertz
2
239
integer replacement
397
0.352
Medium
6,905
https://leetcode.com/problems/integer-replacement/discuss/706015/Python3-O(n)-solution-Integer-Replacement
class Solution: def integerReplacement(self, n: int) -> int: ans = 0 groups = [[k, len(list(g))] for k, g in itertools.groupby(map(int, bin(n)[2:]))] for i in range(len(groups)-1, 0, -1): k, glen = groups[i] if not glen: continue if not k: ...
integer-replacement
Python3 O(n) solution - Integer Replacement
r0bertz
2
239
integer replacement
397
0.352
Medium
6,906
https://leetcode.com/problems/integer-replacement/discuss/1546192/Python-fast-recursive-solution
class Solution: def integerReplacement(self, n: int) -> int: if n <= 3: return n - 1 if n % 2: if (n - 1) % 4: return 1 + self.integerReplacement(n + 1) return 1 + self.integerReplacement(n - 1) return 1 + self.integerReplac...
integer-replacement
Python fast recursive solution
dereky4
1
143
integer replacement
397
0.352
Medium
6,907
https://leetcode.com/problems/integer-replacement/discuss/407631/Python-Simple-Solution
class Solution: def integerReplacement(self, n: int) -> int: count = 0 while(n!=1): if n==3: count+=2 return count while(n%2!=0): if n%4==3: n+=1 else: n-=1 count+=1 while(n%2==0): n=n/2 count+=1 return count
integer-replacement
Python Simple Solution
saffi
1
254
integer replacement
397
0.352
Medium
6,908
https://leetcode.com/problems/integer-replacement/discuss/2844471/Simple-python-O(n)-DP-solution
class Solution: def find(self, i, d): if i not in d: if i % 2 == 0: d[i] = self.find(i//2, d)+1 else: d[i] = min(self.find(i-1, d)+1, self.find(i//2+1, d)+2) return d[i] def integerReplacement(self, n: int) -> int: d = {1: 0} ...
integer-replacement
Simple python O(n) DP solution
juroberttyb
0
1
integer replacement
397
0.352
Medium
6,909
https://leetcode.com/problems/integer-replacement/discuss/2805435/Python-(Simple-Dynamic-Programming)
class Solution: def dfs(self, n, dict1): if n in dict1: return dict1[n] if n%2 == 1: dict1[n] = 1 + min(self.dfs(n-1,dict1),self.dfs(n+1,dict1)) else: dict1[n] = 1 + self.dfs(n//2,dict1) return dict1[n] def integerReplacement(self, n): ...
integer-replacement
Python (Simple Dynamic Programming)
rnotappl
0
2
integer replacement
397
0.352
Medium
6,910
https://leetcode.com/problems/integer-replacement/discuss/2804480/Python3-or-397.-Integer-Replacement
class Solution: def integerReplacement(self, n: int, cache = {}) -> int: if n == 1: return 0 if not n in cache: if n % 2 == 0: cache[n] = self.integerReplacement(n // 2, cache) + 1 else: cache[n]= min(self.integerReplacemen...
integer-replacement
Python3 | 397. Integer Replacement
AndrewMitchell25
0
6
integer replacement
397
0.352
Medium
6,911
https://leetcode.com/problems/integer-replacement/discuss/2509092/Python-Verbose-DP-solution-with-Memoization-Readable
class Solution: def __init__(self): self.twos = {2**n: n for n in range(31)} def integerReplacement(self, n: int) -> int: # this should be a dynamic programming problem # we could just go from top down and memoize the intermediate numbers # make the dict to...
integer-replacement
[Python] - Verbose DP solution with Memoization - Readable
Lucew
0
68
integer replacement
397
0.352
Medium
6,912
https://leetcode.com/problems/integer-replacement/discuss/2456292/Simple-python-solution-with-Memoization-and-Recursion
class Solution: def integerReplacement(self, n: int) -> int: dp = {} def memoize(n, dp): if n == 1: return 0 if n in dp: return dp[n] if n % 2 == 0: dp[n] = 1 + m...
integer-replacement
Simple python solution with Memoization and Recursion
Gilbert770
0
75
integer replacement
397
0.352
Medium
6,913
https://leetcode.com/problems/integer-replacement/discuss/1930198/Python-easy-to-read-and-understand-or-memoization
class Solution: def solve(self, n): if n == 1: return 0 if n in self.d: return self.d[n] if n%2 == 0: self.d[n] = 1 + self.solve(n//2) return self.d[n] else: self.d[n] = 1 + min(self.solve(n-1), self.solve(n+1)) ...
integer-replacement
Python easy to read and understand | memoization
sanial2001
0
106
integer replacement
397
0.352
Medium
6,914
https://leetcode.com/problems/integer-replacement/discuss/1755146/Python-O(logn)-Easy-to-understand
class Solution: def integerReplacement(self, n: int) -> int: count = 0 while n != 1: if n < 4: return count + n-1 if n % 2 == 0: n //= 2 else: if n % 4 == 3: n += 1 else: ...
integer-replacement
[Python] O(logn) Easy to understand
dargudear
0
78
integer replacement
397
0.352
Medium
6,915
https://leetcode.com/problems/integer-replacement/discuss/1668677/Python3C%2B%2B-Solution
class Solution: def integerReplacement(self, n: int) -> int: ans = 0 while n != 1: ans += 1 if n&amp;1 == 0: n >>= 1 elif n == 3 or (n>>1)&amp;1 == 0: n -= 1 else: n += 1 return ans
integer-replacement
Python3/C++ Solution
satyam2001
0
77
integer replacement
397
0.352
Medium
6,916
https://leetcode.com/problems/integer-replacement/discuss/1650335/Python3-BFS-SOLUTION
class Solution: def integerReplacement(self, n: int) -> int: if n==1: return 0 s=set() s.add(n) res=0 while s: temp=set() for val in s: if val==1: return res if val%2==0: ...
integer-replacement
Python3 BFS SOLUTION
Karna61814
0
44
integer replacement
397
0.352
Medium
6,917
https://leetcode.com/problems/integer-replacement/discuss/827198/Python3-dp-and-bfs
class Solution: def integerReplacement(self, n: int) -> int: @lru_cache(None) def fn(n): """Return """ if n == 1: return 0 if not n&amp;1: return 1 + fn(n//2) return 1 + min(fn(n+1), fn(n-1)) return fn(n)
integer-replacement
[Python3] dp & bfs
ye15
0
97
integer replacement
397
0.352
Medium
6,918
https://leetcode.com/problems/integer-replacement/discuss/827198/Python3-dp-and-bfs
class Solution: def integerReplacement(self, n: int) -> int: def bfs(n): """Return numbers of steps to reach 1 via bfs.""" queue = [n] seen = set() ans = 0 while queue: tmp = [] for n in queue: ...
integer-replacement
[Python3] dp & bfs
ye15
0
97
integer replacement
397
0.352
Medium
6,919
https://leetcode.com/problems/integer-replacement/discuss/827198/Python3-dp-and-bfs
class Solution: def integerReplacement(self, n: int) -> int: ans = 0 while n > 1: ans += 1 if n&amp;1 == 0: n //= 2 elif n % 4 == 1 or n == 3: n -= 1 else: n += 1 return ans
integer-replacement
[Python3] dp & bfs
ye15
0
97
integer replacement
397
0.352
Medium
6,920
https://leetcode.com/problems/integer-replacement/discuss/514533/Python3-simple-3-lines-code
class Solution: def integerReplacement(self, n: int) -> int: if n==1: return 0 if n%2==0: return self.integerReplacement(n//2) + 1 return min(self.integerReplacement(n-1),self.integerReplacement(n+1))+1
integer-replacement
Python3 simple 3-lines code
jb07
0
92
integer replacement
397
0.352
Medium
6,921
https://leetcode.com/problems/random-pick-index/discuss/1671979/Python-3-Reservoir-Sampling-O(n)-Time-and-O(1)-Space
class Solution: def __init__(self, nums: List[int]): # Reservoir Sampling (which can handle the linked list with unknown size), time complexity O(n) (init: O(1), pick: O(n)), space complextiy O(1) self.nums = nums def pick(self, target: int) -> int: # https://docs.python.org/3/library/...
random-pick-index
Python 3 Reservoir Sampling, O(n) Time & O(1) Space
xil899
6
453
random pick index
398
0.628
Medium
6,922
https://leetcode.com/problems/random-pick-index/discuss/1003770/Python-two-methods%3A-reservoir-sampling-and-using-a-dictonary
class Solution: def __init__(self, nums: List[int]): self.nums = nums def pick(self, target: int) -> int: count = 0 for i, n in enumerate(self.nums): if n == target: count += 1 if random.randrange(count) == 0: picke...
random-pick-index
Python, two methods: reservoir sampling and using a dictonary
blue_sky5
3
211
random pick index
398
0.628
Medium
6,923
https://leetcode.com/problems/random-pick-index/discuss/1003770/Python-two-methods%3A-reservoir-sampling-and-using-a-dictonary
class Solution: def __init__(self, nums: List[int]): self.indices = defaultdict(list) for i, n in enumerate(nums): self.indices[n].append(i) def pick(self, target: int) -> int: indices = self.indices[target] idx = random.randrange(len(indices)) return indices...
random-pick-index
Python, two methods: reservoir sampling and using a dictonary
blue_sky5
3
211
random pick index
398
0.628
Medium
6,924
https://leetcode.com/problems/random-pick-index/discuss/1426612/Python3-solution-two-approaches
class Solution: def __init__(self, nums: List[int]): self.d = {} self.c = {} for i,j in enumerate(nums): self.d[j] = self.d.get(j,[]) + [i] def pick(self, target: int) -> int: self.c[target] = self.c.get(target,0) + 1 return self.d[target][self.c[target]%len(...
random-pick-index
Python3 solution two approaches
EklavyaJoshi
2
206
random pick index
398
0.628
Medium
6,925
https://leetcode.com/problems/random-pick-index/discuss/1914063/Python-easy-understanding-solution.-O(1)-time-when-picking.
class Solution: def __init__(self, nums: List[int]): self.dict = collections.defaultdict(list) # self.dict record: {unique num: [indices]} for i, n in enumerate(nums): self.dict[n].append(i) def pick(self, target: int) -> int: return random.choice(self.dict[target]) ...
random-pick-index
Python easy - understanding solution. O(1) time when picking.
byroncharly3
1
193
random pick index
398
0.628
Medium
6,926
https://leetcode.com/problems/random-pick-index/discuss/422307/Python-Solution-or-Hash-Table-or-Time-greater-Const-O(n)-pick-O(1)-or-Space-greater-O(n)
class Solution: # store nums as a hash def __init__(self, nums: List[int]): self.numsHash = collections.defaultdict(collections.deque) for i, num in enumerate(nums): self.numsHash[num].append(i) # Random choice def pick(self, target: int) -> int: r...
random-pick-index
Python Solution | Hash Table | Time -> Const O(n), pick O(1) | Space -> O(n)
tolujimoh
1
529
random pick index
398
0.628
Medium
6,927
https://leetcode.com/problems/random-pick-index/discuss/2807081/using-dict
class Solution: def __init__(self, nums: List[int]): # O(n), O(n) self.d = collections.defaultdict(list) for idx, num in enumerate(nums): self.d[num].append(idx) def pick(self, target: int) -> int: return random.choice(self.d[target]) # Your Solu...
random-pick-index
using dict
sahilkumar158
0
5
random pick index
398
0.628
Medium
6,928
https://leetcode.com/problems/random-pick-index/discuss/2731547/python-solution-oror-random.randint-oror-dictionary
class Solution: def __init__(self, nums: List[int]): self.dict={} for i in range(len(nums)): if(self.dict.get(nums[i])!=None): self.dict[nums[i]].append(i) else: self.dict[nums[i]]=[i] def pick(self, target: int) -> int: answerlist...
random-pick-index
python solution || random.randint || dictionary
RA2011050010037
0
16
random pick index
398
0.628
Medium
6,929
https://leetcode.com/problems/random-pick-index/discuss/2728300/Concise-Python-and-Golang-Solution
class Solution: def __init__(self, nums: List[int]): self.cache = {} self.set_up(nums) def set_up(self, numbers: List[int]): for i, number in enumerate(numbers): if number in self.cache.keys(): self.cache[number].append(i) else: self.cache[number] = [i] def pick(self, tar...
random-pick-index
Concise Python and Golang Solution
namashin
0
4
random pick index
398
0.628
Medium
6,930
https://leetcode.com/problems/random-pick-index/discuss/2120924/Python-dictionary-with-list-as-values-and-random.choice
class Solution: def __init__(self, nums: List[int]): self.hmap = defaultdict(list) for index, val in enumerate(nums): self.hmap[val].append(index) def pick(self, target: int) -> int: return random.choice(self.hmap[target])
random-pick-index
Python dictionary with list as values and random.choice
asymptoticbound
0
61
random pick index
398
0.628
Medium
6,931
https://leetcode.com/problems/random-pick-index/discuss/1894651/python3-solution-for-random-pick
class Solution: def __init__(self, nums: List[int]): self.nums = nums def pick(self, target: int) -> int: target_indices = [] for i, x in enumerate(self.nums): if target == x: target_indices.append(i) return random.choice(target_indices)
random-pick-index
python3 solution for random pick
HashRay
0
72
random pick index
398
0.628
Medium
6,932
https://leetcode.com/problems/random-pick-index/discuss/1673294/Simple-python-code-with-comments
class Solution: def __init__(self, nums: List[int]): # instanciate and populate the map required self.hmap = self.populate(nums) def populate(self, nums): hmap = collections.defaultdict(list) # append the index if a number is already in the map for i, num in enumerate...
random-pick-index
Simple python code with comments
asdnakdn
0
67
random pick index
398
0.628
Medium
6,933
https://leetcode.com/problems/random-pick-index/discuss/1417970/Easy-%2B-Clean-Python-Reservoir-Sampling-beats-99
class Solution: def __init__(self, nums: List[int]): self.nums = nums def pick(self, target: int) -> int: idx = None cnt = 0 for i, n in enumerate(self.nums): if n == target: cnt += 1 prob = 1 / (cnt) if random.random(...
random-pick-index
Easy + Clean Python Reservoir Sampling beats 99%
Pythagoras_the_3rd
0
187
random pick index
398
0.628
Medium
6,934
https://leetcode.com/problems/random-pick-index/discuss/811609/Python3-reservoir-sampling
class Solution: def __init__(self, nums: List[int]): self.nums = nums # store nums def pick(self, target: int) -> int: """Sample index of target via resevoir sampling.""" ans = None cnt = 0 for i, x in enumerate(self.nums): if x == target: cnt +=...
random-pick-index
[Python3] reservoir sampling
ye15
0
211
random pick index
398
0.628
Medium
6,935
https://leetcode.com/problems/random-pick-index/discuss/514530/Python3-super-simple-4-lines-code
class Solution: def __init__(self, nums: List[int]): self.ht=collections.defaultdict(list) for i in range(len(nums)): self.ht[nums[i]].append(i) def pick(self, target: int) -> int: import random return self.ht[target][random.randint(0,len(self.ht[target])-1)] # Yo...
random-pick-index
Python3 super simple 4-lines code
jb07
0
200
random pick index
398
0.628
Medium
6,936
https://leetcode.com/problems/random-pick-index/discuss/1808198/Simple-python-solution-time%3A-Init-O(n)-and-Pick-O(1)
class Solution: def __init__(self, nums: List[int]): self.val_index = collections.defaultdict(list) for i, num in enumerate(nums): self.val_index[num].append(i) def pick(self, target: int) -> int: return random.choice(self.val_index[target])
random-pick-index
Simple python solution - time: Init O(n) and Pick O(1)
GeneBelcher
-1
100
random pick index
398
0.628
Medium
6,937
https://leetcode.com/problems/evaluate-division/discuss/827506/Python3-dfs-and-union-find
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: graph = {} for (u, v), w in zip(equations, values): graph.setdefault(u, []).append((v, 1/w)) graph.setdefault(v, []).append((u, w)) def ...
evaluate-division
[Python3] dfs & union-find
ye15
8
489
evaluate division
399
0.596
Medium
6,938
https://leetcode.com/problems/evaluate-division/discuss/827506/Python3-dfs-and-union-find
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: # directed graph as adjacency list digraph = {} for (u, v), w in zip(equations, values): digraph.setdefault(u, []).append((v, w)) digra...
evaluate-division
[Python3] dfs & union-find
ye15
8
489
evaluate division
399
0.596
Medium
6,939
https://leetcode.com/problems/evaluate-division/discuss/1994865/Python3-or-Simple-BFS-Solution
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: def bfs(source, target, value): queue = [[source, value]] visited = set() while queue: node, val = q...
evaluate-division
Python3 | Simple BFS Solution
Crimsoncad3
7
462
evaluate division
399
0.596
Medium
6,940
https://leetcode.com/problems/evaluate-division/discuss/2086218/Python-or-Floyd-Warshall-or-O(n3)-time-O(n)-space
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: def buildGraph(): graph = defaultdict(dict) for (a, b), v in zip(equations, values): # zip into two tuples graph[a][b] = v ...
evaluate-division
Python | Floyd Warshall | O(n^3) time O(n) space
Kiyomi_
3
51
evaluate division
399
0.596
Medium
6,941
https://leetcode.com/problems/evaluate-division/discuss/515098/Python3-super-simple-solution-using-collections.defaultdict(list)
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: def find_path(query): if query[0] not in graph or query[1] not in graph: return -1 temp,visited=[(query[0],1)],set() while temp: ...
evaluate-division
Python3 super simple solution using collections.defaultdict(list)
jb07
2
125
evaluate division
399
0.596
Medium
6,942
https://leetcode.com/problems/evaluate-division/discuss/248841/Python3-UnionFind-Solution.
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: parents = {} ratio = {} def find(x): if parents[x] != x: ratio[x] *= ratio[parents[x]] parents[x] = find(pare...
evaluate-division
Python3 UnionFind Solution.
jinjiren
2
338
evaluate division
399
0.596
Medium
6,943
https://leetcode.com/problems/evaluate-division/discuss/242234/Commented-Python3-BFS-solution-in-28-ms-(beats-100)
class Solution: def calcEquation(self, equations: 'List[List[str]]', values: 'List[float]', queries: 'List[List[str]]') -> 'List[float]': # Transform the input into an adjacency list representing a graph. # The nodes are the variables, and the edges between them are associated with weights that repr...
evaluate-division
Commented Python3 BFS solution in 28 ms (beats 100%)
kvjqxz
2
185
evaluate division
399
0.596
Medium
6,944
https://leetcode.com/problems/evaluate-division/discuss/2719846/Python-Simple-DFS-Straightforward
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: graph = dict() for (n, d), v in zip(equations, values): if n not in graph: graph[n] = [] if d not in graph: ...
evaluate-division
Python Simple DFS Straightforward
user5061Gb
1
29
evaluate division
399
0.596
Medium
6,945
https://leetcode.com/problems/evaluate-division/discuss/2030057/Python3-or-BFS
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: reldict = defaultdict(dict) for eq,v in zip(equations, values): reldict[eq[0]][eq[1]] = v reldict[eq[1]][eq[0]] = 1/v print(reldict) ...
evaluate-division
Python3 | BFS
saad147
1
61
evaluate division
399
0.596
Medium
6,946
https://leetcode.com/problems/evaluate-division/discuss/2830188/18-Line-Python-or-Union-Find-or-1-level-Trees-or-Much-Cleaner-Code-or-Beats-99.14
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: # key is node name; value is [root_name, node/root] nodes = {} def find(a, b): if a not in nodes: nodes[a] = (a, 1) if b ...
evaluate-division
18-Line Python | Union-Find | 1-level Trees | Much Cleaner Code | Beats 99.14%
GregHuang
0
3
evaluate division
399
0.596
Medium
6,947
https://leetcode.com/problems/evaluate-division/discuss/2733996/BFS
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: res = [-1.0 for i in range(len(queries))] graph = collections.defaultdict(list) for source, dest in equations: graph[source].append(dest) ...
evaluate-division
BFS
ngnhatnam188
0
6
evaluate division
399
0.596
Medium
6,948
https://leetcode.com/problems/evaluate-division/discuss/2658775/Python-Solution-with-easy-Understanding-or-bfs-or
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: graph = self.Graph(equations, values) output = [] # find answer for queries... for query in queries: u, v = query # deal with bou...
evaluate-division
Python Solution with easy Understanding | bfs |
quarnstric_
0
8
evaluate division
399
0.596
Medium
6,949
https://leetcode.com/problems/evaluate-division/discuss/2568009/Easy-to-understand-or-DFS-or-With-description-or-Python
class Solution(object): def calcEquation(self, equations, values, queries): """ :type equations: List[List[str]] :type values: List[float] :type queries: List[List[str]] :rtype: List[float] """ dict_n_d={} eq_val=zip(equations,values) ...
evaluate-division
Easy to understand | DFS | With description | Python
ankush_A2U8C
0
31
evaluate division
399
0.596
Medium
6,950
https://leetcode.com/problems/evaluate-division/discuss/2516013/Python-3-using-graph-and-recursion
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: graph = defaultdict(set) # construct a graph to store all connectivities quotient_dic = {} # quotient_dic to store all quotients for [i, j], quot...
evaluate-division
Python 3 using graph and recursion
JiaxuLi
0
35
evaluate division
399
0.596
Medium
6,951
https://leetcode.com/problems/evaluate-division/discuss/2472958/Python-template-for-BFS-and-DFS-with-Explaination
class Solution: def dfs(self,start, dest, visited,graph): if start == dest and graph[start]: return 1 visited.add(start) for node, distance in graph[start]: if node in visited: continue currentVal = self.dfs(node, ...
evaluate-division
Python template for BFS and DFS with Explaination
mrPython
0
52
evaluate division
399
0.596
Medium
6,952
https://leetcode.com/problems/evaluate-division/discuss/2302221/Intuitive-BFS-Solution
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: operationMap = defaultdict(list) costMap = defaultdict(list) for eq, val in zip(equations, values): n, d = eq ...
evaluate-division
Intuitive BFS Solution
tohbaino
0
61
evaluate division
399
0.596
Medium
6,953
https://leetcode.com/problems/evaluate-division/discuss/1997214/python-3-simple-solution.
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: self.res=-1; adj=defaultdict(list); for (a,x),y in zip(equations,values): adj[a].append([x,y]); adj[x].append([a,1/y]); d...
evaluate-division
python 3 simple solution.
cubz01
0
23
evaluate division
399
0.596
Medium
6,954
https://leetcode.com/problems/evaluate-division/discuss/1994325/Python3-Basic-DFS-Long-Descriptive-Code
class Solution: def calcEquation(self, equations: list[list[str]], values: list[float], queries: list[list[str]]) -> list[float]: diction={} for index,i in enumerate(equations): if i[0] not in diction: diction[i[0]]=[] if i[1] not in diction: d...
evaluate-division
Python3 Basic DFS Long Descriptive Code
ComicCoder023
0
31
evaluate division
399
0.596
Medium
6,955
https://leetcode.com/problems/evaluate-division/discuss/1993732/Python3-Solution-with-using-dfs
class Solution: def build_graph(self, equations, values): g = collections.defaultdict(list) for idx in range(len(equations)): src, dst = equations[idx] g[src].append((dst, values[idx])) g[dst].append((src, 1 / values[idx])) r...
evaluate-division
[Python3] Solution with using dfs
maosipov11
0
29
evaluate division
399
0.596
Medium
6,956
https://leetcode.com/problems/evaluate-division/discuss/1993306/Python3-BFS-solution
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: graph = defaultdict(list) ans = [] for i,(u,v) in enumerate(equations): graph[u] += [[v,values[i]]] graph[v] += [[u,1/values[i...
evaluate-division
Python3 BFS solution
avshet_a01
0
44
evaluate division
399
0.596
Medium
6,957
https://leetcode.com/problems/evaluate-division/discuss/1993267/Python3-bfs
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: import collections le = len(equations) start2adj = collections.defaultdict(list) #start: list of [adj, cost] for i in range(le): a, b...
evaluate-division
[Python3] bfs
sshinyy
0
12
evaluate division
399
0.596
Medium
6,958
https://leetcode.com/problems/evaluate-division/discuss/1992986/python-oror-BFS
class Solution: def bfs(self,u,v,graph,vis,parent): qu=[] qu.append(u) vis.add(u) while len(qu): x=qu.pop(0) for node,wt in graph[x]: if node==v: ...
evaluate-division
python || BFS
akshat12199
0
15
evaluate division
399
0.596
Medium
6,959
https://leetcode.com/problems/evaluate-division/discuss/1910678/Python-solution-DFSorDPorDict
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: # x = 2/b and x = 3/c # {x : {(2,b),(3,c)}} vars = {} # {{(a,b) : 2} # {(b,a) : 0.5}} eqs = {} # var : (eq_var, pos) # {x : [(b,...
evaluate-division
Python solution DFS|DP|Dict
sannidhya
0
60
evaluate division
399
0.596
Medium
6,960
https://leetcode.com/problems/evaluate-division/discuss/1870561/Python3-Union-find-solution
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: tokens = {} # char: parent_char, multiplicator def get(ch): # main function to get char parent and its multiplicator par_ch, mul = tokens[ch] ...
evaluate-division
[Python3] - Union find solution
timetoai
0
94
evaluate division
399
0.596
Medium
6,961
https://leetcode.com/problems/evaluate-division/discuss/1814275/Python-UnionFind-Disjoint-Set
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: # store the root and divison to root # if two variables are connected we can find the divison else return -1 class UnionFind: def __init__(se...
evaluate-division
[Python] UnionFind / Disjoint Set
haydarevren
0
69
evaluate division
399
0.596
Medium
6,962
https://leetcode.com/problems/evaluate-division/discuss/1682563/Python3-Union-Find-BFS-implementation
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: def find(u, v=1): if parent[u] != u: parent[u], v = find(parent[u], memo[(parent[u], u)] * v) return parent[u], v def union(...
evaluate-division
[Python3] Union Find / BFS implementation
sam8899
0
169
evaluate division
399
0.596
Medium
6,963
https://leetcode.com/problems/evaluate-division/discuss/1682563/Python3-Union-Find-BFS-implementation
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: def bfs(start, target): if start not in hash_map or target not in hash_map: return -1 if (start, target) in memo: ...
evaluate-division
[Python3] Union Find / BFS implementation
sam8899
0
169
evaluate division
399
0.596
Medium
6,964
https://leetcode.com/problems/evaluate-division/discuss/1466351/Python-LC-solution-with-more-precise-explanation
class Solution: # dfs def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: graph = defaultdict(defaultdict) for (d1, d2), value in zip(equations, values): graph[d1][d2] = value graph[d2][d1] = 1/value ...
evaluate-division
Python LC solution with more precise explanation
SleeplessChallenger
0
136
evaluate division
399
0.596
Medium
6,965
https://leetcode.com/problems/evaluate-division/discuss/1088463/My-python-solution
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: """ Build a graph mapping numerator -> [(denominator, value), ...], and vice versa """ global graph graph = collections.d...
evaluate-division
My python solution
dev-josh
0
109
evaluate division
399
0.596
Medium
6,966
https://leetcode.com/problems/evaluate-division/discuss/868192/Python-DFS-Solution-with-Explanation
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: self.adj_list = {} # Initialize adjacency list with empty lists for start, end in equations: self.adj_list[start] = [] self.adj_l...
evaluate-division
[Python] DFS Solution with Explanation
ehdwn1212
0
59
evaluate division
399
0.596
Medium
6,967
https://leetcode.com/problems/evaluate-division/discuss/867827/Python3-DFS-thinking-process
class Solution: def add(self, graph, a, b, val): if a not in graph: graph[a] = {} if b not in graph[a]: graph[a][b] = val if b not in graph: graph[b] = {} if a not in graph[b]: graph[b][a] = 1 / val if val e...
evaluate-division
Python3 DFS thinking process
ethuoaiesec
0
54
evaluate division
399
0.596
Medium
6,968
https://leetcode.com/problems/evaluate-division/discuss/462659/28ms-python3
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: vars = {} for i in equations: if i[0] not in vars: vars[i[0]] = len(vars) if i[1] not in vars: vars[i[1]] = len(va...
evaluate-division
28ms python3
felicia1994
0
80
evaluate division
399
0.596
Medium
6,969
https://leetcode.com/problems/evaluate-division/discuss/379179/Solution-in-Python-3-(beats-100.0-)-(five-lines)-(Math-Solution)
class Solution: def calcEquation(self, e: List[List[str]], v: List[float], q: List[List[str]]) -> List[float]: V, e, k = {j: False for i in q for j in i}, sorted(i[0]+[i[1]] for i in zip(e,v)), 0 for i,[n,d,v] in enumerate(e): if not (V[n] or V[d]): V[n], k = [1,k], k+1 [V[n],V[d]] = [V[n],[V[...
evaluate-division
Solution in Python 3 (beats 100.0 %) (five lines) (Math Solution)
junaidmansuri
-2
303
evaluate division
399
0.596
Medium
6,970
https://leetcode.com/problems/nth-digit/discuss/828924/Python3-O(logN)-solution
class Solution: def findNthDigit(self, n: int) -> int: digit = base = 1 # starting from 1 digit while n > 9*base*digit: # upper limit of d digits n -= 9*base*digit digit += 1 base *= 10 q, r = divmod(n-1, digit) return int(str(base + q)[r])
nth-digit
[Python3] O(logN) solution
ye15
25
2,100
nth digit
400
0.341
Medium
6,971
https://leetcode.com/problems/nth-digit/discuss/2271490/Python3-with-math
class Solution: def findNthDigit(self, n: int) -> int: """ imagine the number you need to find have 4 digit so you need to go throught all num have 1 digit, 2 digit, 3 digit number have 1 digit: 10 ** 1 - 1 = 9 => 9 * 1 = 9 digit number have 2 digit: 10 ** 2 - 1 = 90 => 90 ...
nth-digit
Python3 with math
tienanh2k1409
1
222
nth digit
400
0.341
Medium
6,972
https://leetcode.com/problems/nth-digit/discuss/931355/Easy-understand-python-solution
class Solution: def findNthDigit(self, n: int) -> int: # integer digit, 1~9 integer digits is 1, 10~19 integer digits is 2 d = 1 # total digits at a integer level, base = 9*10**(d-1)*d base = 0 while n > 9*10**(d-1)*d + base: ...
nth-digit
Easy understand python solution
GNKR
1
742
nth digit
400
0.341
Medium
6,973
https://leetcode.com/problems/nth-digit/discuss/356845/Legible-Python3-solution-with-no-string-conversion
class Solution: def numKDigitNumbers(self, k): """ Auxiliary/helper function to return a count of the number of k digit numbers This would be 10**k - 10**(k-1) but with some algebra it reduces to the formula below """ # optimized alternative to 10**k - 10**(k-1) # = 10**([1 + k-1]) - 10*...
nth-digit
Legible Python3 solution with no string conversion
kortemaki
1
667
nth digit
400
0.341
Medium
6,974
https://leetcode.com/problems/nth-digit/discuss/2751231/Python-Innovative-Solution
class Solution: def findNthDigit(self, n: int) -> int: if len(str(n))==1: return n c=1 while n>=9*(10**(c-1))*c: n-=9*(10**(c-1))*c c+=1 if n==0: return 9 a=10**(c-1)-1 a+=n//c if n%c!=0: a+=1 ...
nth-digit
Python Innovative Solution
Kunalbmd
0
27
nth digit
400
0.341
Medium
6,975
https://leetcode.com/problems/nth-digit/discuss/2733964/Python-solution-with-detail-explanation.-Just-Math!
class Solution: def findNthDigit(self, n: int) -> int: # remember this one: 10987654321 * 9 # 1-9: 9 * 10^0, 9 * 0 + 1 to 9 * 1 # 10 - 99: 9 * 10 ^ 1 * (1+ 1) , from 9 * 1 + 1 to 9 * 21 # 100 - 999: 9 * 10^2 * (2 + 1), from 9 * 21 + 1 to 9 * 321 # 1000 - 9999: 9 * 10^3 * (3 ...
nth-digit
Python solution with detail explanation. Just Math!
jackson-cmd
0
16
nth digit
400
0.341
Medium
6,976
https://leetcode.com/problems/nth-digit/discuss/1120095/Python-90-solution
class Solution: def findNthDigit(self, n: int) -> int: if n < 10: return n # find the digit of n digit = 0 tmp = 0 pre = 0 while tmp < n: pre = tmp digit += 1 tmp += (9*(10**(digit-1)))*digit # find where it belo...
nth-digit
Python 90% solution
dionysus326
0
771
nth digit
400
0.341
Medium
6,977
https://leetcode.com/problems/nth-digit/discuss/342390/Solution-in-Python-3
class Solution: def findNthDigit(self, n: int) -> int: s, d = 0, 0 while s < n: s += (d+1)*9*10**d d += 1 n -= s-d*9*10**(d-1) r, s = n % d, 10**(d-1)+n//d return str(s)[r-1] if r > 0 else str(s-1)[-1] - Python 3 - Junaid Mansuri
nth-digit
Solution in Python 3
junaidmansuri
0
1,100
nth digit
400
0.341
Medium
6,978
https://leetcode.com/problems/binary-watch/discuss/371775/Solution-in-Python-3-(beats-~98)-(one-line)
class Solution: def readBinaryWatch(self, n: int) -> List[str]: return [str(h)+':'+'0'*(m<10)+str(m) for h in range(12) for m in range(60) if (bin(m)+bin(h)).count('1') == n]
binary-watch
Solution in Python 3 (beats ~98%) (one line)
junaidmansuri
10
1,600
binary watch
401
0.517
Easy
6,979
https://leetcode.com/problems/binary-watch/discuss/1228064/Python3-simple-solution-%22One-liner%22
class Solution: def readBinaryWatch(self, turnedOn): return ['{}:{}'.format(i,str(j).zfill(2)) for i in range(12) for j in range(60) if bin(i)[2:].count('1') + bin(j)[2:].count('1') == turnedOn]
binary-watch
Python3 simple solution "One-liner"
EklavyaJoshi
4
223
binary watch
401
0.517
Easy
6,980
https://leetcode.com/problems/binary-watch/discuss/1076038/strainght-forward-solution-using-basics-python
class Solution: def readBinaryWatch(self, num: int) -> List[str]: res=[] for hour in range(12): for minutes in range(60): if bin(hour)[2:].count('1')+bin(minutes)[2:].count('1') ==num: y= '{}:{}'.format(hour,str(minutes).zfill(2)) ...
binary-watch
strainght-forward solution using basics python
yashwanthreddz
3
312
binary watch
401
0.517
Easy
6,981
https://leetcode.com/problems/binary-watch/discuss/335057/Easy-Python3-solution
class Solution: def readBinaryWatch(self, num: int) -> List[str]: if num < 0 or num > 10: return [] result = [] for hour in range(0, 12): for minute in range(0, 60): if bin(hour).count('1') + bin(minute).count('1') == num: ...
binary-watch
Easy Python3 solution
ultrablue
2
468
binary watch
401
0.517
Easy
6,982
https://leetcode.com/problems/binary-watch/discuss/2541698/Very-simple-python-solution
class Solution: def readBinaryWatch(self, turnedOn: int) -> List[str]: # for example: # 2 1 (3 min) - two leds on, bin: 11 # 2 (2 min) - one led on, bin: 10 # 1 (1 min) - one led on, bin: 1 def bit_counter(n): s = bin(n)[2:] temp = 0 ...
binary-watch
Very simple python solution
manualmsdos
1
113
binary watch
401
0.517
Easy
6,983
https://leetcode.com/problems/binary-watch/discuss/1969790/5-Lines-Python-Solution-oror-85-Faster-oror-Memory-less-than-75
class Solution: def readBinaryWatch(self, n: int) -> List[str]: H=[1,2,4,8] ; M=[1,2,4,8,16,32] ; ans=[] for i in range(n+1): for x,y in product(combinations(H,i),combinations(M,n-i)): if sum(x)<12 and sum(y)<60: ans.append(str(sum(x))+':'+str(sum(y)).zfill(2)) re...
binary-watch
5-Lines Python Solution || 85% Faster || Memory less than 75%
Taha-C
1
187
binary watch
401
0.517
Easy
6,984
https://leetcode.com/problems/binary-watch/discuss/1484138/Python-easy-to-understand-(no-dfs-no-backtracking)
class Solution: def readBinaryWatch(self, t: int) -> List[str]: res = [] ## number of '1' in bin(m) def needed(m): if m == 0: return 0 elif m == 1: return 1 elif m %2 ==0: return needed(m//2) e...
binary-watch
Python easy to understand (no dfs, no backtracking)
byuns9334
1
213
binary watch
401
0.517
Easy
6,985
https://leetcode.com/problems/binary-watch/discuss/1474969/1-line-in-Python-3
class Solution: def readBinaryWatch(self, turnedOn: int) -> List[str]: return [f"{h}:{m:02}" for h in range(12) for m in range(60) if f"{h:b}{m:b}".count('1') == turnedOn]
binary-watch
1-line in Python 3
mousun224
1
162
binary watch
401
0.517
Easy
6,986
https://leetcode.com/problems/binary-watch/discuss/1071527/Python-Simple-Backtracking
class Solution: def readBinaryWatch(self, num: int) -> List[str]: def helper(current, comb, left, right): if current==0: h, m = int(comb[0:4], 2), int(comb[4:], 2) if h<12 and m<60: self.req.append(f'{h}:{m:02d}') return ...
binary-watch
Python Simple Backtracking
eastwoodsamuel4
1
327
binary watch
401
0.517
Easy
6,987
https://leetcode.com/problems/binary-watch/discuss/2848598/python3
class Solution: def readBinaryWatch(self, n: int) -> List[str]: if n > 8: return [] ans = [] for h in range(12): for m in range(60): if(bin(h).count("1") + bin(m).count("1") == n): ans.append(f"{str(h)}:{str(m).rjust(2, '0')}") ...
binary-watch
python3
wduf
0
1
binary watch
401
0.517
Easy
6,988
https://leetcode.com/problems/binary-watch/discuss/2793361/Map-on-Initialize-%3A-Python3
class Solution: def __init__(self) : self.combination_dictionary = dict() # loop the turnedOn statuses. 11 so we include 10. for turnedOn in range(11) : # at each status, make a combination list combinations = [] # loop each hour for hour...
binary-watch
Map on Initialize : Python3
laichbr
0
6
binary watch
401
0.517
Easy
6,989
https://leetcode.com/problems/binary-watch/discuss/2474202/Python3-or-Recursion-%2B-Backtracking-Exhaustive-Manner-And-Keeping-Track-Using-a-Set
class Solution: def readBinaryWatch(self, turnedOn: int) -> List[str]: ans = set() m_so_far = 0 h_so_far = 0 #hashmap tells the possible hr and min values we can recurse on! hashmap = {} hashmap["hr"] = [1, 2, 4, 8] hashmap["min"] = [1, 2, 4, 8, 16, 32] ...
binary-watch
Python3 | Recursion + Backtracking Exhaustive Manner And Keeping Track Using a Set
JOON1234
0
54
binary watch
401
0.517
Easy
6,990
https://leetcode.com/problems/binary-watch/discuss/2123540/Python-DFS-solution
class Solution: def readBinaryWatch(self, turnedOn: int) -> List[str]: led = [0]*10 i = 0 res = [] def dfs(index: int, led: List[int], turnedOn: int)->None: if turnedOn==0: time = pattern(led) if time: ...
binary-watch
Python DFS solution
grsb
0
73
binary watch
401
0.517
Easy
6,991
https://leetcode.com/problems/binary-watch/discuss/1611859/Python-Simple-backtracking-imporved
class Solution: def readBinaryWatch(self, turnedOn: int) -> List[str]: self.res = [] led = [8, 4, 2, 1, 32, 16, 8, 4, 2, 1] # how many digits are still on def dfs(h, m, idx, n): if h > 11 or m > 59: return if n == 0: ...
binary-watch
[Python] Simple backtracking imporved
songz2
0
251
binary watch
401
0.517
Easy
6,992
https://leetcode.com/problems/binary-watch/discuss/1411158/Python-Backtracking
class Solution: def readBinaryWatch(self, turnedOn: int) -> List[str]: def helper(res,time,led,start): if led == 0: # res.append(str(time[0]) + (":0" if time[1]<10 else ":") + str(time[1])) res.append("{}:{:02}".format(time[0], time[1])) return ...
binary-watch
Python Backtracking
Mihir64
0
170
binary watch
401
0.517
Easy
6,993
https://leetcode.com/problems/binary-watch/discuss/1122128/Python-bit-masks-beats-9296
class Solution: def readBinaryWatch(self, num: int) -> List[str]: def formatTime(h: str, m: str) -> str: return f"{h}:{'0' if m < 10 else ''}{m}" def generateBitMasks(n: int, offset: int) -> List[str]: masks = {} for i in range(2 ** n): ...
binary-watch
Python bit-masks, beats 92/96
borodayev
0
210
binary watch
401
0.517
Easy
6,994
https://leetcode.com/problems/binary-watch/discuss/636256/Intuitive-approach-by-using-generator-for-permutation
class Solution: def readBinaryWatch(self, num: int) -> List[str]: def ten_digit(num_of_one): def digit_gen(digits, num_of_one): if len(digits) == 10 or num_of_one == 0: for _ in range(10 - len(digits)): digits.append('0') ...
binary-watch
Intuitive approach by using generator for permutation
puremonkey2001
0
128
binary watch
401
0.517
Easy
6,995
https://leetcode.com/problems/binary-watch/discuss/613794/Beats-99-easy-python-combination-solution
class Solution: def binary_comb(self, n, k): """Select k elements out of 1, ..., 2^{n-1} and return a list of all possible sums.""" if k == 0: return [0] elif k == 1: return [2**i for i in range(n)] elif k >= n: return [2**n-1] result = sel...
binary-watch
Beats 99% easy python combination solution
usualwitch
0
386
binary watch
401
0.517
Easy
6,996
https://leetcode.com/problems/binary-watch/discuss/471455/Python3-simple-solution-using-for()-loop
class Solution: def readBinaryWatch(self, num: int) -> List[str]: # if num == 0: return ["00:00"] res = [] for i in range(12): for j in range(60): if ((bin(i)+bin(j)).count("1") == num): h = str(int(bin(i),2)) m = "0"+str(int(bin(j),2)) if len(str(int(bin(j),2)))==1 else str(int(bin(j),2)) ...
binary-watch
Python3 simple solution using for() loop
jb07
0
373
binary watch
401
0.517
Easy
6,997
https://leetcode.com/problems/remove-k-digits/discuss/1779520/Python3-MONOTONIC-STACK-(oo)-Explained
class Solution: def removeKdigits(self, num: str, k: int) -> str: st = list() for n in num: while st and k and st[-1] > n: st.pop() k -= 1 if st or n is not '0': # prevent leading zeros st.append(n) ...
remove-k-digits
✔️ [Python3] MONOTONIC STACK (o^^o)♪, Explained
artod
121
7,900
remove k digits
402
0.305
Medium
6,998
https://leetcode.com/problems/remove-k-digits/discuss/1780248/Python-Solution-oror-Monotonic-Stack-oror-O(n)-time
class Solution: def removeKdigits(self, num: str, k: int) -> str: st = [] for i in num: while k and len(st) > 0 and st[-1] > i: k -= 1 st.pop() st.append(i) while k: k -= 1 st.pop() st = "".join(st).lstri...
remove-k-digits
Python Solution || Monotonic Stack || O(n) time
cherrysri1997
11
612
remove k digits
402
0.305
Medium
6,999