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 + helper(n//2, memo)
return memo[n]
memo = {1:0}
return helper(n, memo) | 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),recur(n+1))
return dp[n]
return recur(n) | 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
ans += 1
return ans | 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:
ans += glen
elif glen == 1:
ans += 2
else:
if groups[i-1][1] == 1:
ans += glen + 1
groups[i-1][1] = 0
groups[i-2][1] += 1
else:
ans += glen + 2
if groups[0][1] == 1:
return ans
return ans + groups[0][1] + int(groups[0][1] > 2) | 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.integerReplacement(n // 2) | 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}
return self.find(n, d) | 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):
dict1 = {1:0}
return self.dfs(n,dict1) | 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.integerReplacement(n + 1, cache), self.integerReplacement(n - 1, cache)) + 1
return cache[n] | 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 memoize values
memo = {}
self.dp(n, 0, memo)
return memo[1]
def dp(self, number, steps, memo):
# now check whether we have lesser steps for current number
if number in memo:
# we found a shorter path
if memo[number] > steps:
memo[number] = steps
# a shorter or equal path has already been found
# and we can stop here
else:
return
else:
memo[number] = steps
# check whether we are one
if number == 1:
return
# check whether we are potential of two
# in this we can immediately recurse to 1
if number in self.twos:
self.dp(1, steps + self.twos[number], memo)
# now check how we need to go on
new, res = divmod(number, 2)
if res:
self.dp(number+1, steps+1, memo)
self.dp(number-1, steps+1, memo)
else:
self.dp(new, steps+1, memo)
return | 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 + memoize(n//2, dp)
return dp[n]
else:
dp[n] = 1 + min(memoize(n-1, dp), memoize(n+1, dp))
return dp[n]
return memoize(n, dp) | 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))
return self.d[n]
def integerReplacement(self, n: int) -> int:
self.d = {}
return self.solve(n) | 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:
n -= 1
count += 1
return count | 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&1 == 0: n >>= 1
elif n == 3 or (n>>1)&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:
temp.add(val//2)
else:
temp.add(val+1)
temp.add(val-1)
res+=1
s=temp
return -1 | 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&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:
if n in seen: continue
seen.add(n)
if n == 1: return ans
if n&1 == 0: tmp.append(n//2)
else: tmp.extend([n-1, n+1])
ans += 1
queue = tmp
return bfs(n) | 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&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.html
count = 0
chosen_index = None
for i in range(len(self.nums)):
if self.nums[i] != target:
continue
count += 1
if count == 1:
chosen_index = i
elif random.random() < 1 / count:
chosen_index = i
return chosen_index | 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:
picked = i
return picked | 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[idx] | 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(self.d[target])] | 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 from list is O(1) | 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:
return random.choice(self.numsHash[target]) | 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 Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target) | 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=self.dict[target]
return answerlist[random.randint(0,len(answerlist)-1)]
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target) | 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, target: int) -> int:
target_indexes = self.cache.get(target)
return random.choice(target_indexes) | 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(nums):
if num in hmap:
hmap[num].append(i)
else:
hmap[num] = [i] # create a new key in the map with index as value
return hmap
def pick(self, target: int) -> int:
# check if target in map and return random index
if target in self.hmap:
index = self.hmap[target]
return random.choice(index)
else:
return null | 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() < prob:
idx = i
return idx | 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 += 1
if randint(1, cnt) == cnt: ans = i # prob 1/cnt
return ans | 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)]
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target) | 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 dfs(n, g, val=1):
"""Depth-first traverse the graph."""
if n in vals: return
vals[n] = val, g
for nn, w in graph.get(n, []): dfs(nn, g, w*val)
vals = dict()
for i, n in enumerate(graph): dfs(n, i)
ans = []
for u, v in queries:
if u in vals and v in vals and vals[u][1] == vals[v][1]: ans.append(vals[u][0]/vals[v][0])
else: ans.append(-1)
return ans | 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))
digraph.setdefault(v, []).append((u, 1/w))
# query
def dfs(u, v, w=1):
"""Return division via dfs."""
if u not in digraph: return -1
if u == v: return w
seen.add(u)
for uu, ww in digraph.get(u, []):
if uu not in seen and (ans := dfs(uu, v, w*ww)) != -1: return ans
return -1
ans = []
for u, v in queries:
seen = set()
ans.append(dfs(u, v))
return ans | 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 = queue.pop(0)
if node == target:
return val
if node in visited:
continue
visited.add(node)
for baju_wala in graph[node]:
if baju_wala not in visited:
new_val = val * graph[node][baju_wala]
queue.append([baju_wala, new_val])
return float(-1)
graph = {}
for i in range(len(values)):
u, v = equations[i]
value = values[i]
rev_value = 1 / value
if u in graph:
graph[u][v] = value
else:
graph[u] = {v: value}
if v in graph:
graph[v][u] = rev_value
else:
graph[v] = {u: rev_value}
result = []
for a, b in queries:
if a not in graph or b not in graph:
result.append(float(-1))
else:
res = bfs(a, b, 1)
result.append(res)
return result | 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
graph[b][a] = 1/v
return graph
graph = buildGraph() # build given relationship
# build all other relationship using floyd
for k in graph: # k: intermediate vertext
for i in graph:
for j in graph: # i, j : one matrix at a time
if k in graph[i] and j in graph[k]:
graph[i][j] = graph[i][k] * graph[k][j]
return [graph[a][b] if b in graph[a] else -1.00000 for a, b in queries] | 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:
node,current_product=temp.pop(0)
if node==query[1]: return current_product
visited.add(node)
for neighbor,value in graph[node]:
if neighbor not in visited:
temp.append((neighbor,value*current_product))
return -1
graph=collections.defaultdict(list)
for i in range(len(equations)):
graph[equations[i][0]].append((equations[i][1],values[i]))
graph[equations[i][1]].append((equations[i][0],1/values[i]))
return [find_path(q) for q in queries] | 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(parents[x])
return parents[x]
def union(x, y, k):
rx = find(x)
ry = find(y)
if rx != ry:
parents[rx] = ry
ratio[rx] = k * (ratio[y] / ratio[x])
for (A, B), k in zip(equations, values):
if A not in parents and B not in parents:
parents[A] = B
parents[B] = B
ratio[A] = k
ratio[B] = 1.0
elif A in parents and B in parents:
union(A, B, k)
elif A in parents and B not in parents:
ra = find(A)
parents[B] = ra
ratio[B] = 1 / k * ratio[A]
elif A not in parents and B in parents:
rb = find(B)
parents[A] = rb
ratio[A] = k * ratio[B]
res = []
for x, y in queries:
if x not in parents or y not in parents:
res.append(-1.0)
continue
rx = find(x)
ry = find(y)
if rx != ry:
res.append(-1.0)
else:
res.append(ratio[x] / ratio[y])
return res | 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 represent the values.
adj = {}
for index, variables in enumerate(equations):
if variables[0] not in adj:
adj[variables[0]] = []
if variables[1] not in adj:
adj[variables[1]] = []
adj[variables[0]].append([variables[1], values[index]])
adj[variables[1]].append([variables[0], 1.0/values[index]])
# Initialize the output list.
output = []
# Iterate through the queries and process them.
for query in queries:
# If a variable does not exist in our graph, return -1.0.
if (query[0] not in adj) or (query[1] not in adj):
output.append(-1.0)
# If the query divides a variable by itself, return 1.0.
elif(query[0] == query[1]):
output.append(1.0)
# Perform a BFS to find the result of the query.
else:
output.append(self.bfs(adj, query[0], query[1]))
return output
def bfs(self, graph, start, end):
# Maintain a queue of nodes to visit and the value computed so far.
# Start with the first variable.
queue = [(start, 1.0)]
# Keep track of which nodes we've already seen.
seen = set()
while queue:
curr_node, val = queue.pop(0)
seen.add(curr_node)
# If we've found the other variable, return the calculated value.
if curr_node == end:
return val
# Compute the new value for each previously unseen neighbor.
for neighbor in graph[curr_node]:
next_node, weight = neighbor
if next_node not in seen:
queue.append((next_node, val*weight))
# If there's no way to calculate the answer (ie. underdetermined system), return -1.0.
return -1.0 | 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:
graph[d] = []
graph[n].append((d, v))
graph[d].append((n, 1/v))
def dfs(node, target, product, visited):
if n not in graph or d not in graph:
return -1
if node == target:
return product
visited.add(node)
for neighbor, quotient in graph[node]:
if neighbor not in visited:
soln = dfs(neighbor, target, product * quotient, visited)
if soln != -1:
return soln
return -1
solns = []
for n, d in queries:
solns.append(dfs(n, d, 1, set()))
return solns | 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)
sol = []
for que in queries:
if que[0] not in reldict or que[1] not in reldict:
sol.append(-1.0)
continue
else:
if que[1] in reldict[que[0]]:
sol.append(reldict[que[0]][que[1]])
continue
queue = [(que[0], 1)]
found = False
seen = [que[0]]
while queue:
var, ans = queue.pop(0)
if var == que[1]:
sol.append(ans)
found = True
break
for k,v in reldict[var].items():
if k not in seen:
queue.append((k,ans*v))
seen.append(k)
if not found:
sol.append(-1.0)
return sol | 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 not in nodes:
nodes[b] = (b, 1)
return nodes[a][0] == nodes[b][0]
def union(a, b, v):
if find(a, b):
return
# move group a into b
(a_root, va), (b_root, vb) = nodes[a], nodes[b]
for x in nodes:
if nodes[x][0] == a_root:
nodes[x] = (b_root, nodes[x][1] / va * v * vb)
for (a, b), v in zip(equations, values):
union(a, b, v)
return [nodes[a][1]/nodes[b][1] if (a in nodes and b in nodes and nodes[a][0] == nodes[b][0]) else -1 for a, b in queries] | 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)
graph[dest].append(source)
hashmap = {tuple(equations[i]) : values[i] for i in range(len(equations))}
hashmapRev = {tuple([equations[i][1],equations[i][0]]) : 1.0/values[i] for i in range(len(equations))}
hashmap.update(hashmapRev)
for i,q in enumerate(queries):
q = tuple(q)
if q in hashmap:
res[i] = hashmap[q]
else:
source, dest = q
if source not in graph:
res[i] = -1
continue
visited = set()
visited.add(source)
queue = collections.deque()
queue.append((source,1))
while queue:
removed, div = queue.popleft()
if removed == dest:
res[i] = div
break
for child in graph[removed]:
if child not in visited:
visited.add(child)
queue.append((child,div*hashmap[(removed,child)]))
return res | 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 boundry cases..
if u not in graph or v not in graph:
output.append(-1.0)
else:
# write algorithm for valid cases..
# evalute value of v and u is 1 assumed by bfs call..
eval = self.bfs(u, v, graph)
output.append(1/eval) # value of ratio..
return output
def bfs(self, start, end, graph):
queue = deque()
seen = set() # visited nodes set..
# add start node to queue and let val 1 for node..
queue.append( (start, 1) )
# traverse graph for end value..
while queue:
node, val = queue.popleft()
# check if end node is found..
if node == end:
return val
# go to neighbors of graph..
for neigh in graph[node]:
neigh_node, ratio = neigh
if neigh_node not in seen:
queue.append( (neigh_node, val/ratio) )
# add current node to visited set...
seen.add(node)
# still doesn't return anything..
return -1.0
# weighted graph..
def Graph(self, equations, values):
adj_list = {}
for ind, equation in enumerate(equations):
u, v = equation
if u in adj_list:
adj_list[u].append( (v, values[ind]) )
if v in adj_list:
adj_list[v].append( (u, 1/values[ind]) )
else:
adj_list[v] = [(u, 1/values[ind])]
else:
adj_list[u] = [(v, values[ind])]
if v in adj_list:
adj_list[v].append( (u, 1/values[ind]) )
else:
adj_list[v] = [(u, 1/values[ind])]
return adj_list | 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)
for eq,v in eq_val:
n=eq[0]
d=eq[1]
if n not in dict_n_d:
dict_n_d[n]=[[n,1]]
if d not in dict_n_d:
dict_n_d[d]=[[d,1]]
dict_n_d[n].append([d,v])
dict_n_d[d].append([n,float(1/v)])
def dfs(root,target,val,visited):
if target==root:
return val
if root in visited:
return -1
temp=-1
visited.add(root)
for u,v in dict_n_d[root]:
temp=dfs(u,target,val*v,visited)
if temp!=-1:
break
return temp
ans=[]
for n_u,d_v in queries:
if n_u not in dict_n_d or d_v not in dict_n_d:
ans.append(-1)
continue
ans.append(dfs(n_u,d_v,1,set()))
return ans | 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], quotient in zip(equations, values):
graph[i].add(j)
graph[j].add(i)
quotient_dic[(i, j)] = quotient
quotient_dic[(j, i)] = 1 / quotient
all_nums = list(graph.keys())
groups = {} # {num1: (group_id1, weight1), ....}
group_id = 0
while all_nums: # place all the numbers into groups
group_id += 1
def dp(val, weight): # dp should reach all nodes in the graph if they are connected
groups[val] = (group_id, weight)
all_nums.remove(val)
for neib in list(graph[val]): # check all neighbours
if neib not in groups:
quotient = quotient_dic[(neib, val)]
dp(neib, quotient * weight)
dp(all_nums[0], 1) # initial weight is chosen as 1, can be any other number
out = []
for x, y in queries:
if x not in groups or y not in groups:
out.append(-1)
continue
g1, val1 = groups[x]
g2, val2 = groups[y]
if g1 != g2:
out.append(-1)
else:
out.append(val1/val2)
return out | 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, dest,visited,graph)
if currentVal != -1:
return currentVal * distance
return -1
def bfs(self,start, dest, visited,graph):
queue = collections.deque([(start,1)])
while queue:
st, dt = queue.popleft()
if st == dest and graph[st]:
return dt
for node,distance in graph[st]:
if node in visited:
continue
queue.append((node,distance*dt))
visited.add(node)
return -1
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
visited = set()
graph = defaultdict(list)
output = []
for i, j in zip(equations, values):
graph[i[0]].append([i[1],j])
graph[i[1]].append([i[0],1/j])
for i in queries:
output.append(self.bfs(i[0],i[1], visited, graph))
visited = set()
return output | 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
operationMap[n].append(d)
costMap[n].append(val)
operationMap[d].append(n)
costMap[d].append(1/val)
res = []
for start, dest in queries:
if start not in operationMap or dest not in operationMap:
res.append(-1)
continue
deq = deque([(start, 1)])
seen = False
visited = set([start])
while deq:
cur, cost = deq.popleft()
if cur == dest:
seen = True
res.append(cost)
break
for i, nxt in enumerate(operationMap[cur]):
if nxt in visited:
continue
tmp = cost*costMap[cur][i]
deq.append((nxt, tmp))
visited.add(nxt)
if not seen:
res.append(-1)
return res | 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]);
def dfs(s,e,p,vis):
if(s==e and s not in vis):
self.res=p;
return;
else:
vis.add(s);
for ne,val in adj[s]:
if ne not in vis:
dfs(ne,e,p*val,vis);
ans=[]
for q in queries:
m,n=q;
if(m not in adj.keys() or n not in adj.keys()):
ans.append(-1);
elif (m==n):
ans.append(1);
else:
product=1;
vis=set()
self.res=-1
dfs(m,n,product,vis);
ans.append(self.res)
return ans; | 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:
diction[i[1]]=[]
diction[i[0]].append([i[1],values[index]])
diction[i[1]].append([i[0],1/values[index]])
def dfs(edges,start,end,passed):
stack=[]
if start in edges:
for num,value in edges[start]:
if num in passed:
continue
stack.append([num,value])
temp=1
while stack:
num,value=stack.pop()
temp=value
if num in passed:
continue
if num==end:
return [True,temp]
flag,retvalue=dfs(edges,num,end,passed+[num])
if not flag:
continue
return [flag,temp*retvalue]
return [False,-1]
res=[]
for a,b in queries:
if a not in diction or b not in diction:
res.append(-1)
continue
if a==b:
res.append(1)
continue
flag,answer=dfs(diction,a,b,[a])
if flag:
diction[a].append([b,answer])
diction[b].append([a,1/answer])
res.append(answer)
continue
return res | 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]))
return g
def get_path_weight(self, g, visited, src, dst):
# if src not in graph = > we cant find path
if src not in g:
return -1.0
# mb two adjacent vertices (the only edge between them)
for neigb, weight in g[src]:
if neigb == dst:
return weight
visited.add(src)
for neigb, weight in g[src]:
if neigb not in visited:
prev_weight = self.get_path_weight(g, visited, neigb, dst) # weight from previous iterations
if prev_weight != -1.0:
return prev_weight * weight
return -1.0
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
"""
build directed weighted graph:
["a", "b"] and value = 2.0 = > a --> b (where the edge has weight 2.0)/ b --> a (where the edge has weight 0.5)
"""
g = self.build_graph(equations, values)
res = []
for query in queries:
res.append(self.get_path_weight(g, set(), query[0], query[1]))
return res | 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]]]
def compute(s,e):
queue = deque([[s,1]])
visited = set()
while queue:
nextqueue = deque()
for [node,w] in queue:
if node == e and e in graph:
return w
visited.add(node)
for [neig,weig] in graph[node]:
if neig not in visited:
nextqueue.append([neig,weig*w])
queue = nextqueue
return float(-1)
for (start,end) in queries:
ans.append(compute(start,end))
return ans | 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 = equations[i]
v = values[i]
start2adj[a].append([b, v])
start2adj[b].append([a, 1/v])
ans = list()
for start, end in queries:
if start not in start2adj or end not in start2adj:
ans.append(-1)
continue
queue = collections.deque([[start, 1]]) #[node, cost from start to node]
visited = set()
ans_found = False
while queue:
cur, acc_cost = queue.popleft()
if cur == end:
ans.append(acc_cost)
ans_found = True
break
if cur in visited: #prevent revisit
continue
visited.add(cur)
for next_node, next_cost in start2adj[cur]:
queue.append([next_node, acc_cost * next_cost])
if not ans_found:
ans.append(-1)
return ans | 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:
parent[node].append((x,wt))
print(parent)
return True
if node not in vis:
vis.add(node)
parent[node].append((x,wt))
qu.append(node)
return False
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
graph=defaultdict(list)
ans=[]
for i in range(len(values)):
x,y=equations[i]
graph[x].append((y,values[i]))
graph[y].append((x,1/values[i]))
for i in range(len(queries)):
u,v=queries[i]
if u not in graph: #if there is no node
ans.append(-1)
continue
elif u==v: #if there is self-loop
ans.append(1)
else: #otherwise need to trace the path and back track the answer
vis=set()
parent=defaultdict(list) #for back tracing
# by running a BFS we can check whether there is path from u->v.
#if it returns True that means there is a path we only need to backtrace the path to get the ans.
if self.bfs(u,v,graph,vis,parent):
#back tracing
qu=[]
qu.append(v)
res=1
while len(qu):
x=qu.pop(0)
for node,wt in parent[x]:
res*=wt
qu.append(node)
ans.append(res)
else:
ans.append(-1)
return ans | 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,1),(c,1)]}
dp = {}
memo = {}
res = []
for i,equation in enumerate(equations):
eqs[tuple(equation)] = values[i]
eqs[tuple(equation[::-1])] = 1/values[i]
if vars.get(equation[0],-1) == -1:
vars.setdefault(equation[0],set()).add((equation[1],1/values[i]))
dp.setdefault(equation[0],set()).add(equation[1])
else:
vars[equation[0]].add((equation[1],1/values[i]))
dp[equation[0]].add(equation[1])
if vars.get(equation[1],-1) == -1:
vars.setdefault(equation[1],set()).add((equation[0],values[i]))
dp.setdefault(equation[1],set()).add(equation[0])
else:
vars[equation[1]].add((equation[0],values[i]))
dp[equation[1]].add(equation[0])
#print(dp)
#print(eqs)
def check_for_indirect_conn(src,target,path):
if memo.get((src,target),-1) != -1:
path+=memo.get((src,target),-1)
return 1,path
if src in visited:
return None,path
visited.add(src)
#print(src)
if target in dp.get(src):
path.append(target)
return 1,path
else:
for i in list(dp.get(src)):
x,path = check_for_indirect_conn(i,target,path)
if x == 1:
memo.setdefault((i,target),path.copy())
path.append(i)
return 1,path
return 0,path
def calcPath(path):
myPath = path[::-1]
div = 1
for i in range(0,len(path)-1):
div*=eqs.get((myPath[i],myPath[i+1]))
return div
def calcQuery(query):
path = []
if query[1] == query[0] and vars.get(query[0],-1) != -1:
return 1
if vars.get(query[1],-1) == -1 or vars.get(query[0],-1) == -1:
return -1
if eqs.get((query[0],query[1]),-1) != -1:
return eqs.get((query[0],query[1]))
x,path = check_for_indirect_conn(query[0],query[1],[])
if x == 0:
return -1.0
path.append(query[0])
#print(path)
return calcPath(path)
for query in queries:
visited = set()
res.append(calcQuery(query))
return res | 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]
if par_ch != ch:
ppar_ch, pmul = get(par_ch)
tokens[ch] = (ppar_ch, pmul * mul)
return tokens[ch]
for (ch1, ch2), val in zip(equations, values):
# 4 cases of adding chars, all considered below
if ch1 in tokens:
pch1, mul1 = get(ch1)
if ch2 in tokens:
pch2, mul2 = get(ch2)
if pch1 != pch2:
# pch1 / ch1 = mul1 |
# pch2 / ch2 = mul2 | what we have
# ch1 / ch2 = val |
#
# pch2 / pch1 * val = mul2 / mul1
# pch1 / pch2 = mul1 / mul2 * val | what we need
tokens[pch2] = (pch1, mul1 / mul2 * val)
else:
tokens[ch2] = (pch1, mul1 * val)
elif ch2 in tokens:
pch2, mul2 = get(ch2)
tokens[ch1] = (pch2, mul2 / val)
else:
tokens[ch1] = (ch1, 1)
tokens[ch2] = (ch1, val)
ret = []
for ch1, ch2 in queries:
if ch1 not in tokens or ch2 not in tokens:
ret.append(- 1)
continue
pch1, mul1 = get(ch1)
pch2, mul2 = get(ch2)
if pch1 != pch2:
ret.append(- 1)
else:
ret.append(mul2 / mul1)
return ret | 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__(self):
self.root = {}
self.rank = {}
def findroot(self,x):
if x not in self.root:
self.root[x] = (x,1)
self.rank[x] = 1
if x == self.root[x][0]:
return (x,1)
# path compression
rootX, px = self.findroot(self.root[x][0])
self.root[x] = (rootX,self.root[x][1]*px)
return self.root[x]
def union(self,x,y,val):
rootX, px = self.findroot(x)
rootY, py = self.findroot(y)
# union by rank
if rootX != rootY:
multp = px/py*val #this is the trickiest part
if self.rank[rootX]>self.rank[rootY]:
self.root[rootY] = (rootX, multp)
elif self.rank[rootX]<self.rank[rootY]:
self.root[rootX] = (rootY, 1/multp)
else:
self.root[rootY] = (rootX, multp)
self.rank[rootX] +=1
def calculate(self,x,y):
if x not in self.root or y not in self.root:
return -1
rootX, px = self.findroot(x)
rootY, py = self.findroot(y)
if rootX != rootY: return -1
return 1/px*py
graph = UnionFind()
for (a,b),n in zip(equations,values):
graph.union(a,b,n)
return [graph.calculate(a,b) for a,b in queries] | 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(a, b, v):
"""
a / b = v
va = ra / a
vb = rb / b
va / vb = (ra / rb) * (b / a)
ra / rb = va / vb * (a / b) = va / vb * v
"""
(ra, va), (rb, vb) = find(a), find(b)
if ra == rb:
return
if rank[ra] < rank[rb]:
parent[ra] = rb
elif rank[ra] > rank[rb]:
parent[rb] = ra
else:
parent[rb] = ra
rank[ra] += 1
num = va / vb * v
memo[(ra, rb)] = num
memo[(rb, ra)] = 1. / num
parent = defaultdict(str)
rank = defaultdict(int)
memo = defaultdict(int)
for (a, b), v in zip(equations, values):
if a not in parent:
parent[a] = a
if b not in parent:
parent[b] = b
union(a, b, v)
ans = []
for a, b in queries:
if a not in parent or b not in parent:
ans.append(-1)
continue
if (a, b) in memo:
ans.append(memo[(a, b)])
else:
(ra, va), (rb, vb) = find(a), find(b)
if ra != rb:
# since root of a and b is not the same
# there is no relation betweem a and b
ans.append(-1)
else:
# va = ra / a
# vb = rb / b
# since ra == rb
# a / b = vb / va
num = vb / va
ans.append(num)
memo[(a, b)] = num
memo[(b, a)] = 1. / num
return ans | 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:
return memo[(start, target)]
if start == target:
return 1
Q = deque([(start, 1.)])
visit = set()
visit.add(start)
while Q:
size = len(Q)
while size:
c, num = Q.popleft()
for d, v in hash_map[c]:
if d not in visit:
nxtNum = num * v
if d == target:
memo[(start, target)] = nxtNum
memo[(target, start)] = 1. / nxtNum
return nxtNum
visit.add(d)
Q.append((d, nxtNum))
size -= 1
return -1
hash_map = defaultdict(list)
memo = defaultdict(int)
ans = []
for (a, b), v in zip(equations, values):
hash_map[a].append((b, v))
hash_map[b].append((a, 1. / v))
memo[(a, b)] = v
memo[(b, a)] = 1. / v
for a, b in queries:
ans.append(bfs(a, b))
return ans | 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
def dfs(explored, v1, v2, val):
explored.add(v1)
adjacent = graph[v1]
result = -1.0
if v2 in adjacent:
result = val * adjacent[v2]
else:
for k, v in adjacent.items():
if k in explored:
continue
# we need to mult `val` as we're
# traversing node
result = dfs(explored, k, v2, val * v)
if result != -1.0:
break
explored.remove(v1)
return result
total = []
for q1, q2 in queries:
if q1 not in graph or q2 not in graph:
result = -1.0
elif q1 == q2:
result = 1.0
else:
visited = set()
result = dfs(visited, q1, q2, 1)
total.append(result)
return total | 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.defaultdict(list)
for (a, b), v in zip(equations, values):
graph[a].append((b, v))
graph[b].append((a, 1/v))
"""
Hop through the graph!
"""
def compute_query(a, b):
global graph
if a not in graph or b not in graph:
return -1.0
if a == b:
return 1.0
seen = set()
def dfs(x):
if x in seen:
return -float('inf')
if x == b:
return 1.0
seen.add(x)
result = max([v*dfs(y) for y, v in graph[x]])
seen.remove(x)
return result
result = dfs(a)
return result if result != -float('inf') else -1.0
"""
Compute all the queries!
"""
result = []
for a, b in queries:
result += [compute_query(a, b)]
return result | 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_list[end] = []
# Build undirected graph
for index, (start, end) in enumerate(equations):
value = values[index]
self.adj_list[start].append((end, value))
self.adj_list[end].append((start, 1 / value))
# Get answer for each query
return [self.dfs(start, end, 1, set()) for start, end in queries]
def dfs(self, start, end, product, visited):
# Exit early if value is not part of adjancey list or have visited before
if not start in self.adj_list or start in visited:
return -1.0
visited.add(start)
# Check all possible paths from all current nodes
for node, value in self.adj_list[start]:
# Found a valid path
if node == end:
return value * product
potential_answer = self.dfs(node, end, product * value, visited)
# Return if answer is found
if potential_answer > 0:
return potential_answer
visited.remove(start)
return -1.0 | 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 else 0
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
graph = {}
for i in range(len(values)):
a, b = equations[i]
val = values[i]
self.add(graph, a, b, val)
print(graph)
res = []
for a, b in queries:
if a not in graph and b not in graph:
#no need to look for path
res.append(-1.0)
continue
# visited set is important! We don't want to search path like a->b->a->b...
visited = set([a])
ans = self.dfs(a, b, graph, visited)
if ans is None:
res.append(-1.0)
else:
res.append(ans)
#without adding this new edge, the code will still work, but the performance will not as good.
if b not in graph[a]:
self.add(graph, a, b, ans)
return res
def dfs(self, cur, target, graph, visited):
if cur == target:
return 1
if cur not in graph:
return None
for child in graph[cur]:
if child in visited:
continue
visited.add(child)
ans = self.dfs(child, target, graph, visited)
if ans is not None:
return ans * graph[cur][child]
visited.remove(child)
return None | 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(vars)
mat = [['unknown' for _ in range(len(vars))] for _ in range(len(vars))]
for i in range(len(vars)):
mat[i][i] = 1
for i,j in enumerate(equations):
mat[vars[j[0]]][vars[j[1]]] = values[i]
mat[vars[j[1]]][vars[j[0]]] = 1/values[i]
count = True
while count:
count = False
for i in range(len(vars)):
for j in range(i+1,len(vars)):
if mat[i][j]=='unknown':
for k in range(len(vars)):
if mat[i][k]!='unknown' and mat[k][j]!='unknown':
mat[i][j] = mat[i][k]*mat[k][j]
mat[j][i] = 1/(mat[i][k]*mat[k][j])
count = True
break
res = []
for i in queries:
if (i[0] in vars) and (i[1] in vars):
if mat[vars[i[0]]][vars[i[1]]]!='unknown':
res.append(mat[vars[i[0]]][vars[i[1]]])
else:
res.append(-1.0)
else:
res.append(-1.0)
return res | 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[n][0]/v,k-1]] if V[n] else [[V[d][0]*v,k-1],V[d]]
return [-1 if not (V[n] and V[d] and V[n][1] == V[d][1]) else V[n][0]/V[d][0] for [n,d] in q]
- Junaid Mansuri
(LeetCode ID)@hotmail.com | 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 * 2 = 180 digit
number have 3 digit: 10 ** 3 - 1 = 900 => 900 * 3 = 2700 digit
...
just subtract until you find how many digit of the number you need to find
when you got the number of digit
"""
if n < 10:
return n
number_of_digit = 0 # check how many digit of the number you need to find
while n > 0:
number_of_digit += 1
n -= 9 * 10 ** ((number_of_digit - 1)) * number_of_digit
n += 9 * 10 ** ((number_of_digit - 1)) * number_of_digit
"""
print(n , number_of_digit) if you dont understand
after subtract you will find number of digit
all you need to do now is find exactly number by just a little bit of math
"""
tmp_num = 0
if n % number_of_digit == 0:
n //= number_of_digit
tmp_num += 10 ** ((number_of_digit - 1)) - 1
return int(str(tmp_num + n)[-1])
else:
n /= number_of_digit
digit = int((n * number_of_digit) % number_of_digit)
tmp_num += 10 ** ((number_of_digit - 1)) - 1
return int(str(int(tmp_num + n) + 1)[digit - 1]) | 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:
base += 9*10**(d-1)*d
d+=1
# closest number for nth digits
number = (10**(d-1) - 1) + (n-base)//d
number = int(number)
# remainder
rmd = (n-base)%d
if rmd == 0:
return int(str(number)[-1])
else:
return int(str(number+1)[rmd-1]) | 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**(k-1)
# = [10*(10**(k-1)] - [1*(10**(k-1))]
# = [10-1]*(10**(k-1))
return 9*(10**(k-1))
def findNthDigit(self, n: int) -> int:
"""
Find the nth digit in the series 123456789101112...
We start by determining what portion of the series n lives in (i.e. what size of k for k digit numbers)
Then we determine which k-digit number n and which digit i of the number to return
Then we isolate and return that digit
"""
k = 1
while n>k*self.numKDigitNumbers(k):
# n is big enough to bypass the k-digit numbers
n -= k*self.numKDigitNumbers(k)
k += 1
# digit appears in a k-digit number
# get the ith digit of the nth k-digit number
n -= 1 # to simplify modular arithmetic
n, i = n//k, n%k # find i and n-1
n += 10**(k-1) # n is now the nth k-digit number
n //= 10**(k-i-1) # get rid of all digits after the ith
return n % 10 # return the ith digit | 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
if n%c==0:
return int(str(a)[-1])
else:
return int(str(a)[(n%c)-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 + 1), from 9 * 321 + 1 to 9 * 4321
# n between 9 * a(a-1)..1 + 1 to 9 * (a+1)n(a-1)...1
# begin number is 10^a, every number has (a+1) digits
tmp = [i for i in range(1, 11, 1)]
cur = 1
bound = [0, 1]
for i in range(1, len(tmp)):
cur = cur + tmp[i] * 10**i
bound.append(cur)
bound = [i * 9 for i in bound]
print(bound)
# get the lower bound
lower = 0
for i in range(len(bound)):
if n < bound[i]:
lower = i - 1
break
# get the a which is lower
start_number = 10**lower
remain = n - bound[lower]
digit = lower + 1
# write down number, and then easy to understand
if remain % digit == 0:
number = start_number + remain // digit - 1
return (int)(str(number)[-1])
else:
number = start_number + remain // digit
index = remain - remain // digit * (digit)
return (int)(str(number)[index-1]) | 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 belongs
n -= pre
num = 10**(digit-1) + ((n-1)//digit)
# find the index
index = (n-1)%digit
return num//(10**(digit-index-1))%10 | 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))
res.append(y)
return res | 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:
result.append('{:d}:{:02d}'.format(hour, minute))
return result | 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
for i in s:
if i == '1':
temp += 1
return temp
result = []
for h in range(12):
for m in range(60):
if bit_counter(h) + bit_counter(m) == turnedOn:
result.append(f'{h}:{m:02}')
return result | 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))
return ans | 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)
else: #m %2 ==1
return 1+needed((m-1)//2)
for h in range(12):
for m in range(60):
if needed(h) + needed(m) == t:
if m < 10:
res.append(str(h)+":"+str(0)+str(m))
else:
res.append(str(h)+":"+str(m))
return res | 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
for i in range(left, right):
helper(current-1, comb[:i]+'1'+comb[i+1:], i+1, right)
self.req = []
comb = '0'*10 #4 and 6
helper(num, comb, 0, len(comb))
return self.req | 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')}")
return ans | 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 in range(12) :
# loop each minute
for minute in range(60) :
# if binary combination counts match
if (bin(hour) + bin(minute)).count('1') == turnedOn :
# make the time string followwing format
time_string = '%d:%02d' % (hour, minute)
# add to combinations
combinations.append(time_string)
# map combinations to the turnedOn status
self.combination_dictionary[turnedOn] = combinations
def readBinaryWatch(self, turnedOn: int) -> List[str]:
# return the mapped status
return self.combination_dictionary[turnedOn] | 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]
#Paramters:
#1. LEDS -> tell number of LEDS turned on so far!
#2. hr_set -> set of all hour values that are already used and not available!
#3. min_set -> similar idea as hr_set!
def helper(LEDS, hr_set, min_set):
nonlocal m_so_far, h_so_far, ans, turnedOn, hashmap
#check if m_so_far or h_so_far is out of range -> invalid time!
if(m_so_far > 59 or h_so_far > 11):
return
#base case: LEDS == input: number of turnedOn!
#we used all LEDs and current time is valid! So we need to record it!
if(LEDS == turnedOn):
m_string = ""
#if minute is single digit, we need a leading zero!
if(0<= m_so_far <= 9):
m_string = m_string + "0" + str(m_so_far)
else:
m_string = str(m_so_far)
#no leading zero for hour!
res = str(h_so_far) + ":" + m_string
ans.add(res)
return
#otherwise, we can recurse over all 4 hour values nad 6 minutes values and
#use them only if they are not already in set!
for hour in hashmap["hr"]:
if(hour in hr_set):
continue
hr_set.add(hour)
#update the hour count and add to set before recursing!
h_so_far += hour
helper(LEDS + 1, hr_set, min_set)
#once rec. call returns, update the count of hours as well as state of hr!
h_so_far -= hour
hr_set.remove(hour)
for minute in hashmap["min"]:
if(minute in min_set):
continue
min_set.add(minute)
m_so_far += minute
helper(LEDS + 1, hr_set, min_set)
m_so_far -= minute
min_set.remove(minute)
helper(0, set(), set())
return list(ans) | 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:
res.append(time)
else:
for i in range(index, len(led)):
dfs(i+1, led[:i]+[1]+led[i+1:], turnedOn-1)
dfs(0, led, turnedOn)
return res
def pattern(led: List[int])->str:
h, m = 0, 0
for i in range(4):
h += led[i]*(2**(3-i))
for i in range(4,10):
m += led[i]*(2**(9-i))
leading_zero = '0' if m<10 else ''
time = str(h) + ':' + leading_zero + str(m)
return None if h>=12 or m>=60 else 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:
self.res.append("{:d}:{:02d}".format(h, m))
return
for i in range(idx, len(led)): # <- right here, we can just iterate through the options we have
if i <= 3:
dfs(h + led[i], m, i + 1, n - 1)
elif i < len(led):
dfs(h, m + led[i], i + 1, n - 1)
dfs(0, 0, 0, turnedOn)
return self.res | 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
for i in range(start,len(hour)+len(minute)):
if i < len(hour):
time[0] += hour[i]
if time[0] < 12: helper(res,time,led-1,i+1)
time[0] -= hour[i]
else:
time[1] += minute[i-len(hour)]
if time[1] < 60: helper(res,time,led-1,i+1)
time[1] -= minute[i-len(hour)]
hour, minute, res = [1,2,4,8], [1,2,4,8,16,32], []
helper(res,[0,0],turnedOn,0)
return res | 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):
mask = bin(i | offset << n)[n:]
masks[mask] = mask.count('1')
return masks
hoursMasks = generateBitMasks(4,2)
minutesMasks = generateBitMasks(6,8)
result = [];
for h in hoursMasks:
for m in minutesMasks:
if hoursMasks[h] + minutesMasks[m] == num:
decimalHours = int(h, 2)
decimalMinutes = int(m, 2)
if decimalHours < 12 and decimalMinutes < 60:
result.append(formatTime(decimalHours, decimalMinutes))
return result | 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')
yield digits
else:
if num_of_one < 10 - len(digits):
new_digits = digits.copy()
new_digits.append('0')
yield from digit_gen(new_digits, num_of_one)
new_digits = digits.copy()
new_digits.append('1')
yield from digit_gen(new_digits, num_of_one - 1)
return digit_gen([], num_of_one)
results = []
for digits in ten_digit(num):
hr = int(''.join(digits[:4]), 2)
mn = int(''.join(digits[4:]), 2)
if hr > 11 or mn > 59:
continue
results.append("{:01}:{:02}".format(hr, mn))
return results | 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 = self.binary_comb(n-1, k)
result.extend(e + 2**(n-1) for e in self.binary_comb(n-1, k-1))
return result
def readBinaryWatch(self, num: int):
result = []
for h_count in range(num+1):
m_count = num - h_count
hours = [hour for hour in self.binary_comb(4, h_count) if hour < 12]
minutes = [minute for minute in self.binary_comb(6, m_count) if minute < 60]
result.extend(f'{hour}:{str(minute).zfill(2)}' for hour in hours for minute in minutes)
return result | 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))
res.append(h+":"+m)
return res | 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)
if k: # not fully spent
st = st[0:-k]
return ''.join(st) or '0' | 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).lstrip("0")
return st if st else "0" | remove-k-digits | Python Solution || Monotonic Stack || O(n) time | cherrysri1997 | 11 | 612 | remove k digits | 402 | 0.305 | Medium | 6,999 |
Subsets and Splits