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/find-the-highest-altitude/discuss/1680106/Python-Code-or-Beginner-Friendly-or-Easy-and-Simple
class Solution: def largestAltitude(self, gain: List[int]) -> int: res=0 lst=[] lst.insert(0,0) for i in gain: lst.append(res+i) res=res+i return max(lst)
find-the-highest-altitude
Python Code | Beginner Friendly | Easy and Simple
harie22
0
57
find the highest altitude
1,732
0.787
Easy
25,000
https://leetcode.com/problems/find-the-highest-altitude/discuss/1652572/easy-to-understand
class Solution: def largestAltitude(self, gain: List[int]) -> int: l = [0 for i in range(0,len(gain)+1)] for i in range(1,len(l)): l[i] = l[i-1] + gain[i-1] return max(l)
find-the-highest-altitude
easy to understand
MB16biwas
0
30
find the highest altitude
1,732
0.787
Easy
25,001
https://leetcode.com/problems/find-the-highest-altitude/discuss/1591172/simple-solution-or-python
class Solution: def largestAltitude(self, gain: List[int]) -> int: # basic idea is that altitude == gain + previous altitude idx, altitudes = 1, [0] gain.insert(0,0) while idx < len(gain): altitudes.append(gain[idx]+altitudes[idx-1]) idx += 1 return max(altitudes)
find-the-highest-altitude
simple solution | python
anandanshul001
0
59
find the highest altitude
1,732
0.787
Easy
25,002
https://leetcode.com/problems/find-the-highest-altitude/discuss/1428137/Python-Solution%3A-95.36-efficient-and-89.05-better-in-memory
class Solution: def largestAltitude(self, gain: List[int]) -> int: maximum = [0] for height in gain: maximum.append(maximum[-1] + height) return max(maximum)
find-the-highest-altitude
Python Solution: 95.36% efficient and 89.05% better in memory
sayantani_s
0
105
find the highest altitude
1,732
0.787
Easy
25,003
https://leetcode.com/problems/find-the-highest-altitude/discuss/1370987/Python3-Solution
class Solution: def largestAltitude(self, gain: List[int]) -> int: currentAlt = 0 maxAlt = 0 for x in range(0, len(gain)): currentAlt += gain[x] maxAlt = max(maxAlt, currentAlt) return maxAlt
find-the-highest-altitude
Python3 Solution
RobertObrochta
0
44
find the highest altitude
1,732
0.787
Easy
25,004
https://leetcode.com/problems/find-the-highest-altitude/discuss/1276614/Easy-Python-Solution
class Solution: def largestAltitude(self, gain: List[int]) -> int: n=len(gain) ans=[0]*(n+1) mx=0 for i in range(n): ans[i+1]=gain[i]+ans[i] return max(ans)
find-the-highest-altitude
Easy Python Solution
sakshigoel123
0
105
find the highest altitude
1,732
0.787
Easy
25,005
https://leetcode.com/problems/find-the-highest-altitude/discuss/1176852/Python3-simple-solution-beats-90-users
class Solution: def largestAltitude(self, gain: List[int]) -> int: l = [0] for i in range(len(gain)): l.append(l[-1]+gain[i]) return max(l)
find-the-highest-altitude
Python3 simple solution beats 90% users
EklavyaJoshi
0
53
find the highest altitude
1,732
0.787
Easy
25,006
https://leetcode.com/problems/find-the-highest-altitude/discuss/1112974/Python3-solution-88-fast-98-lite
class Solution: def largestAltitude(self, gain: List[int]) -> int: high = 0 temp = 0 for i in gain: temp = temp + i if temp > high: high = temp return high
find-the-highest-altitude
Python3 solution 88% fast, 98% lite
rikeshkamra97
0
127
find the highest altitude
1,732
0.787
Easy
25,007
https://leetcode.com/problems/find-the-highest-altitude/discuss/1067126/Python3-solution
class Solution: def largestAltitude(self, gain: List[int]) -> int: curr_max, curr_alt = 0, 0 for i in range(len(gain)): curr_alt = curr_alt + gain[i] if curr_alt > curr_max: curr_max = curr_alt return curr_max
find-the-highest-altitude
Python3 solution
shreyasdamle2017
0
55
find the highest altitude
1,732
0.787
Easy
25,008
https://leetcode.com/problems/find-the-highest-altitude/discuss/1041203/Python-faster-than-97.-Linear-time-O(n)-and-const-memory-O(1)-%2B-explain.
class Solution: def largestAltitude(self, gain: List[int]) -> int: current_val = max_val = 0 for x in gain: current_val += x max_val = current_val if current_val > max_val else max_val return max_val
find-the-highest-altitude
Python faster than 97%. Linear time O(n) and const memory O(1) + explain.
dezintegro
0
90
find the highest altitude
1,732
0.787
Easy
25,009
https://leetcode.com/problems/find-the-highest-altitude/discuss/1036429/Python3-prefix-sum
class Solution: def largestAltitude(self, gain: List[int]) -> int: ans = prefix = 0 for x in gain: prefix += x ans = max(ans, prefix) return ans
find-the-highest-altitude
[Python3] prefix sum
ye15
0
30
find the highest altitude
1,732
0.787
Easy
25,010
https://leetcode.com/problems/find-the-highest-altitude/discuss/1033011/100-time-and-Space-without-using-library-function-or-12ms-Runtime-or-Python3
class Solution: def largestAltitude(self, gain: List[int]) -> int: last_gain = max_gain = 0 for n in gain: last_gain += n if last_gain > max_gain: max_gain = last_gain return max_gain
find-the-highest-altitude
100% time and Space without using library function | 12ms Runtime | Python[3]
hotassun
0
38
find the highest altitude
1,732
0.787
Easy
25,011
https://leetcode.com/problems/find-the-highest-altitude/discuss/1031708/Python3-clean-solution
class Solution: def largestAltitude(self, gain: List[int]) -> int: anchor, res = 0, 0 for g in gain: anchor += g res = max(res, anchor) return res
find-the-highest-altitude
[Python3] clean solution
hwsbjts
0
45
find the highest altitude
1,732
0.787
Easy
25,012
https://leetcode.com/problems/find-the-highest-altitude/discuss/1031094/Python3-One-liner
class Solution: def largestAltitude(self, gain: List[int]) -> int: return max(0,max(itertools.accumulate(gain)))
find-the-highest-altitude
[Python3] One-liner
vilchinsky
0
60
find the highest altitude
1,732
0.787
Easy
25,013
https://leetcode.com/problems/minimum-number-of-people-to-teach/discuss/1059885/Python3-count-properly
class Solution: def minimumTeachings(self, n: int, languages: List[List[int]], friendships: List[List[int]]) -> int: m = len(languages) languages = [set(x) for x in languages] mp = {} for u, v in friendships: if not languages[u-1] &amp; languages[v-1]: for i in range(n): if i+1 not in languages[u-1]: mp.setdefault(u-1, set()).add(i) if i+1 not in languages[v-1]: mp.setdefault(v-1, set()).add(i) ans = inf for i in range(n): val = 0 for k in range(m): if i in mp.get(k, set()): val += 1 ans = min(ans, val) return ans
minimum-number-of-people-to-teach
[Python3] count properly
ye15
1
107
minimum number of people to teach
1,733
0.418
Medium
25,014
https://leetcode.com/problems/minimum-number-of-people-to-teach/discuss/1059885/Python3-count-properly
class Solution: def minimumTeachings(self, n: int, languages: List[List[int]], friendships: List[List[int]]) -> int: languages = [set(x) for x in languages] users = set() for u, v in friendships: if not languages[u-1] &amp; languages[v-1]: users.add(u-1) users.add(v-1) freq = {} for i in users: for k in languages[i]: freq[k] = 1 + freq.get(k, 0) return len(users) - max(freq.values(), default=0)
minimum-number-of-people-to-teach
[Python3] count properly
ye15
1
107
minimum number of people to teach
1,733
0.418
Medium
25,015
https://leetcode.com/problems/minimum-number-of-people-to-teach/discuss/1032620/Pythonic
class Solution: def minimumTeachings(self, n: int, languages: List[List[int]], friendships: List[List[int]]) -> int: languages = [None] + list(map(set, languages)) friendships = [[u, v] for u, v in friendships if not languages[u] &amp; languages[v]] # teach whoever needs it return min([len({u for pair in friendships for u in pair if lan not in languages[u]}) for lan in range(1, n+1)])
minimum-number-of-people-to-teach
Pythonic
beautyofdeduction
-1
48
minimum number of people to teach
1,733
0.418
Medium
25,016
https://leetcode.com/problems/decode-xored-permutation/discuss/1031227/Python-or-Detailed-Exeplanation-by-finding-the-first-one
class Solution: def decode(self, encoded: List[int]) -> List[int]: n = len(encoded)+1 XOR = 0 for i in range(1,n+1): XOR = XOR^i s = 0 for i in range(1,n,2): s = s^encoded[i] res = [0]*n res[0] = XOR^s for j in range(1,n): res[j] = res[j-1]^encoded[j-1] return res
decode-xored-permutation
Python | Detailed Exeplanation by finding the first one
jmin3
1
111
decode xored permutation
1,734
0.624
Medium
25,017
https://leetcode.com/problems/decode-xored-permutation/discuss/2673976/python-easy-solution
class Solution: def decode(self, encoded: List[int]) -> List[int]: l=[] x=0 n=len(encoded)+1 for i in range (1,n+1): # xor of 1 to n+1 x^=i #print(x) for i in range (len(encoded)): #xor of normal array whoes index is odd if i%2==1: x^=encoded[i] print(x) #finding first element of an output l.append(x) #print(l) for i in range (len(encoded)): #finding first element then calculating xor with encoded elements x=l[i]^encoded[i] l.append(x) return l
decode-xored-permutation
python easy solution
tush18
0
5
decode xored permutation
1,734
0.624
Medium
25,018
https://leetcode.com/problems/decode-xored-permutation/discuss/1059890/Python3-xor-manipulation
class Solution: def decode(self, encoded: List[int]) -> List[int]: x = reduce(xor, list(range(1, len(encoded) + 2))) for i in range(1, len(encoded), 2): x ^= encoded[i] ans = [x] for x in encoded: ans.append(ans[-1] ^ x) return ans
decode-xored-permutation
[Python3] xor manipulation
ye15
0
78
decode xored permutation
1,734
0.624
Medium
25,019
https://leetcode.com/problems/count-ways-to-make-array-with-product/discuss/1355240/No-Maths-Just-Recursion-DP-we-can-come-up-with-in-interviews-greater-WA
class Solution: def waysToFillArray(self, queries: List[List[int]]) -> List[int]: # brute DP O(NK) where N is max(q[0]) and K is max(q[1]) @cache def dp(n,k): if k == 1 or n == 1: return 1 ways = 0 for factor in range(1, k+1): if k % factor == 0: ways += dp(n-1, k//factor) # or take the '3' part ways %= (10**9+7) return ways % (10**9+7) res = [0] * len(queries) for i,(n, k) in enumerate(queries): res[i] = dp(n,k) return res # better solution -> find out how many prime factors a number has. # how many ways to group P numbers into N groups (since array has N values only) # but you can group in lesser groups and keep 1 1 1 1 as padding in array :(
count-ways-to-make-array-with-product
No Maths Just Recursion DP we can come up with in interviews -> WA
yozaam
1
326
count ways to make array with product
1,735
0.506
Hard
25,020
https://leetcode.com/problems/count-ways-to-make-array-with-product/discuss/1355240/No-Maths-Just-Recursion-DP-we-can-come-up-with-in-interviews-greater-WA
class Solution: def waysToFillArray(self, queries, mod = 10**9+7) -> List[int]: def getPrimeFactorFreq(n): i = 2 while i*i <= n: fre = 0 while n % i == 0: fre += 1 n //= i if fre > 0: yield fre i += 1 if n > 1: yield 1 @functools.cache def combinations(n, r): if n < r: return 0 elif r == 0 or n == r: return 1 return (combinations(n-1,r-1) + combinations(n-1,r)) % mod def getWays(n, k): ways = 1 for fre in getPrimeFactorFreq(k): print('--', fre) # how many ways to place this factor # among N boxes, he has `fre` occurance # https://cp-algorithms.com/combinatorics/stars_and_bars.html ways_cur_factor = combinations(n+fre-1, fre) ways = (ways * ways_cur_factor) % mod return ways return [getWays(n,k) for n,k in queries]
count-ways-to-make-array-with-product
No Maths Just Recursion DP we can come up with in interviews -> WA
yozaam
1
326
count ways to make array with product
1,735
0.506
Hard
25,021
https://leetcode.com/problems/count-ways-to-make-array-with-product/discuss/1059848/Python3-via-sieve-and-comb
class Solution: def waysToFillArray(self, queries: List[List[int]]) -> List[int]: spf = list(range(10001)) # spf = smallest prime factor for i in range(4, 10001, 2): spf[i] = 2 for i in range(3, int(sqrt(10001))+1): if spf[i] == i: for ii in range(i*i, 10001, i): spf[ii] = min(spf[ii], i) ans = [] for n, k in queries: freq = {} # prime factorization via sieve while k != 1: freq[spf[k]] = 1 + freq.get(spf[k], 0) k //= spf[k] val = 1 for x in freq.values(): val *= comb(n+x-1, x) ans.append(val % 1_000_000_007) return ans
count-ways-to-make-array-with-product
[Python3] via sieve & comb
ye15
0
174
count ways to make array with product
1,735
0.506
Hard
25,022
https://leetcode.com/problems/count-ways-to-make-array-with-product/discuss/1059848/Python3-via-sieve-and-comb
class Solution: def waysToFillArray(self, queries: List[List[int]]) -> List[int]: spf = list(range(10001)) # spf = smallest prime factor prime = [] for i in range(2, 10001): if spf[i] == i: prime.append(i) for x in prime: if x <= spf[i] and i*x < 10001: spf[i * x] = x else: break ans = [] for n, k in queries: freq = {} # prime factorization via sieve while k != 1: freq[spf[k]] = 1 + freq.get(spf[k], 0) k //= spf[k] val = 1 for x in freq.values(): val *= comb(n+x-1, x) ans.append(val % 1_000_000_007) return ans
count-ways-to-make-array-with-product
[Python3] via sieve & comb
ye15
0
174
count ways to make array with product
1,735
0.506
Hard
25,023
https://leetcode.com/problems/count-ways-to-make-array-with-product/discuss/1033612/Look-for-helpPython3-trying-to-come-up-with-a-DP-solution
class Solution: def __init__(self): self.dp = {} def waysToFillArray(self, queries: List[List[int]]) -> List[int]: mod = 10 ** 9 + 7 def dfs(n, val): if (n, val) not in self.dp: if n == 1: return 1 temp = 1 for k in range(val//2, 0, -1): if val % k == 0: temp += dfs(n-1, val // k) self.dp[n, val] = temp % mod return self.dp[n, val] res = [] for n, val in queries: res.append(dfs(n, val)) return res
count-ways-to-make-array-with-product
[Look for help][Python3] trying to come up with a DP solution
hwsbjts
0
71
count ways to make array with product
1,735
0.506
Hard
25,024
https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/discuss/1032030/Python3-if-elif
class Solution: def maximumTime(self, time: str) -> str: time = list(time) for i in range(len(time)): if time[i] == "?": if i == 0: time[i] = "2" if time[i+1] in "?0123" else "1" elif i == 1: time[i] = "3" if time[0] == "2" else "9" elif i == 3: time[i] = "5" else: time[i] = "9" return "".join(time)
latest-time-by-replacing-hidden-digits
[Python3] if-elif
ye15
27
1,500
latest time by replacing hidden digits
1,736
0.422
Easy
25,025
https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/discuss/1032173/Python-short
class Solution: def maximumTime(self, time: str) -> str: maxTime = "23:59" if time[0] in "?2" and time[1] in "?0123" else "19:59" return "".join(t if t != "?" else m for t, m in zip(time, maxTime))
latest-time-by-replacing-hidden-digits
Python, short
blue_sky5
4
306
latest time by replacing hidden digits
1,736
0.422
Easy
25,026
https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/discuss/1915764/Easiest-and-Simplest-Python3-Solution-with-if-conditions-or-100-Faster-or-Easy-to-Understand
class Solution: def maximumTime(self, time: str) -> str: s=list(time) for i in range(len(s)): if s[i]=='?': if i==0: if s[i+1] in ['0','1','2','3','?']: s[i]='2' else: s[i]='1' elif i==1: if s[i-1]=='1' or s[i-1]=='0': s[i]='9' else: s[i]='3' elif i==3: s[i]='5' elif i==4: s[i]='9' return ''.join(s)
latest-time-by-replacing-hidden-digits
Easiest & Simplest Python3 Solution with if conditions | 100% Faster | Easy to Understand
RatnaPriya
3
116
latest time by replacing hidden digits
1,736
0.422
Easy
25,027
https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/discuss/1118360/WEEB-DOES-PYTHON-WITH-97.70-RUNTIME
class Solution: def maximumTime(self, time: str) -> str: memo = {"0":"9", "1":"9", "?":"3", "2":"3"} answer = "" for idx, val in enumerate(time): if val == "?": if idx == 0: if time[idx+1] == "?": answer += "2" else: if int(time[idx+1]) >= 4: answer += "1" else: answer += "2" if idx == 1: answer += memo[time[idx-1]] if idx == 3: answer += "5" if idx == 4: answer += "9" else: answer += val return answer
latest-time-by-replacing-hidden-digits
WEEB DOES PYTHON WITH 97.70% RUNTIME
Skywalker5423
3
308
latest time by replacing hidden digits
1,736
0.422
Easy
25,028
https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/discuss/1701829/Python-3-Solution-%3A-Easy-and-Understandable
class Solution: def maximumTime(self, time: str) -> str: hr,mn = time.split(':') hr = list(hr) mn = list(mn) if hr[0]=='?' and hr[1]!='?': if 4<= int(hr[1]) <=9: hr[0] = "1" else: hr[0] = "2" if hr[1]=='?' and hr[0]!='?': if hr[0] == "2": hr[1] = "3" else: hr[1] = "9" if hr[0]=='?' and hr[1]=='?': hr[0] = "2" hr[1] = "3" if mn[0] == '?' and mn[1]!='?': mn[0] = "5" if mn[1] == '?' and mn[0]!='?': mn[1] = "9" if mn[0] == '?' and mn[1]=='?': mn[0] = "5" mn[1] = "9" hr.append(':') return "".join(hr+mn)
latest-time-by-replacing-hidden-digits
Python 3 Solution : Easy and Understandable
deleted_user
1
73
latest time by replacing hidden digits
1,736
0.422
Easy
25,029
https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/discuss/2789220/Python-simple-greedy-solution
class Solution: def maximumTime(self, time: str) -> str: hr, mn = time.split(':') if hr[0] == '?': if hr[1] == '?': hr = '23' else: if int(hr[1]) <= 3: hr = '2'+hr[1] else: hr = '1'+hr[1] elif hr[1] == '?': if hr[0] == '2': hr = hr[0]+'3' else: hr = hr[0]+'9' if mn[0] == '?': if mn[1] == '?': mn = '59' else: mn = '5'+mn[1] elif mn[1] == '?': mn = mn[0]+'9' return hr+':'+mn
latest-time-by-replacing-hidden-digits
Python simple greedy solution
ankurkumarpankaj
0
6
latest time by replacing hidden digits
1,736
0.422
Easy
25,030
https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/discuss/2560255/Python-easy-to-understand-(runtime%3A-30-40ms)
class Solution: def maximumTime(self, time: str) -> str: a=['2','3',':','5','9'] b=['1','9',':','5','9'] c=['4','5','6','7','8','9'] if time[0]=='2' or (time[0]=='?' and time[1] not in c): for i in range(5): if time[i]!='?': a[i]=time[i] return(a[0]+a[1]+':'+a[3]+a[4]) else: for i in range(5): if time[i]!='?': b[i]=time[i] return(b[0]+b[1]+':'+b[3]+b[4])
latest-time-by-replacing-hidden-digits
Python easy to understand (runtime: 30-40ms)
jakeyhe
0
34
latest time by replacing hidden digits
1,736
0.422
Easy
25,031
https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/discuss/2352715/Python3-Brute-force-each-%22%22-one-by-one-except-%22%22
class Solution: def maximumTime(self, time: str) -> str: def brute_force(substring, limit): for i in range(10)[::-1]: value = substring.replace('?', f'{i}') if int(value) < limit: return value hh = '23' if time[:2] == '??' else brute_force(time[:2], 24) mm = '59' if time[3:] == '??' else brute_force(time[3:], 60) return(f'{hh}:{mm}')
latest-time-by-replacing-hidden-digits
[Python3] Brute force each "?" one by one except "??"
TomS_Ekb
0
35
latest time by replacing hidden digits
1,736
0.422
Easy
25,032
https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/discuss/1847943/Python-dollarolution
class Solution: def maximumTime(self, time: str) -> str: v = ['2','3','9','5','9'] s = '' for i in range(5): if time[i] == '?': if i == 0 and time[i+1] not in '0,1,2,3,?': s += '1' elif i == 1 and s[i-1] != '2': s += v[i+1] else: s += v[i] else: s += time[i] return s
latest-time-by-replacing-hidden-digits
Python $olution
AakRay
0
49
latest time by replacing hidden digits
1,736
0.422
Easy
25,033
https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/discuss/1495933/Choose-max-digits-based-on-neighbor-82-speed
class Solution: def maximumTime(self, time: str) -> str: lst = list(time) if lst[0] == lst[1] == "?": lst[0], lst[1] = "2", "3" elif lst[0] == "?": lst[0] = "2" if lst[1] < "4" else "1" elif lst[1] == "?": lst[1] = "9" if lst[0] < "2" else "3" if lst[3] == "?": lst[3] = "5" if lst[4] == "?": lst[4] = "9" return "".join(lst)
latest-time-by-replacing-hidden-digits
Choose max digits based on neighbor, 82% speed
EvgenySH
0
106
latest time by replacing hidden digits
1,736
0.422
Easy
25,034
https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/discuss/1446044/Python3-Faster-Than-95.42
class Solution: def maximumTime(self, time: str) -> str: z = [time[0], time[1], time[3], time[4]] if time[0] == '?': if time[1] == '?': z[0] = '2' elif int(time[1]) >= 4: z[0] = '1' else: z[0] = '2' if time[1] == '?': if z[0] == '2': z[1] = '3' else: z[1] = '9' if time[3] == '?': z[2] = '5' if time[4] == '?': z[3] = '9' return z[0] + z[1] + ':' + z[2] + z[3]
latest-time-by-replacing-hidden-digits
Python3 Faster Than 95.42%
Hejita
0
71
latest time by replacing hidden digits
1,736
0.422
Easy
25,035
https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/discuss/1309740/Python-fast-and-simple-solution
class Solution: def maximumTime(self, time: str) -> str: _time = list(time) if _time[0] == "?": if _time[1] == "?" or int(_time[1]) < 4: _time[0] = "2" else: _time[0] = "1" if _time[1] == "?": if _time[0] == "2": _time[1] = "3" else: _time[1] = "9" if _time[3] == "?": _time[3] = "5" if _time[4] == "?": _time[4] = "9" return "".join(_time)
latest-time-by-replacing-hidden-digits
Python fast and simple solution
MihailP
0
120
latest time by replacing hidden digits
1,736
0.422
Easy
25,036
https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/discuss/1265779/Python3-List-out-every-possibility
class Solution: def maximumTime(self, time: str) -> str: res = '' for i in range(len(time)): if time[i] == '?': if i == 0: if time[1] == '?': res += '2' else: if int(time[1]) > 3: res += '1' else: res += '2' elif i == 1: if res[0] == '2': res += '3' else: res += '9' elif i == 3: res += '5' else: res += '9' else: res += time[i] return res
latest-time-by-replacing-hidden-digits
Python3 List out every possibility
georgeqz
0
91
latest time by replacing hidden digits
1,736
0.422
Easy
25,037
https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/discuss/1250513/Python3-simple-solution
class Solution: def maximumTime(self, time: str) -> str: if time[0] == '?': if time[1] != '?'and not int(time[1]) <= 3: time = '1' + time[1:] else: time = '2' + time[1:] if time[1] == '?': if time[0] in ['0','1']: time = time[0] + '9' + time[2:] else: time = time[0] + '3' + time[2:] if time[3] == '?': time = time[:3] + '5' + time[4] if time[4] == '?': time = time[:4] + '9' return time
latest-time-by-replacing-hidden-digits
Python3 simple solution
EklavyaJoshi
0
74
latest time by replacing hidden digits
1,736
0.422
Easy
25,038
https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/discuss/1033653/Python3-Solution-with-in-line-explanation
class Solution: def maximumTime(self, time: str) -> str: # first digit: if second_digit >= 4: [0, 1], else: [0, 2] # second digit: if first_digit == 2: [0, 3], else: [0, 9] # third digit: always [0, 5] # fourth digit: always [0, 9] time = list(time) if time[0] == '?' and (time[1] == '?' or time[1] < '4'): time[0] = '2' elif time[0] == '?': time[0] = '1' if time[1] == '?' and time[0] == '2': time[1] = '3' elif time[1] == '?': time[1] = '9' if time[3] == '?': time[3] = '5' if time[4] == '?': time[4] = '9' return ''.join(time)
latest-time-by-replacing-hidden-digits
[Python3] Solution with in-line explanation
hwsbjts
0
92
latest time by replacing hidden digits
1,736
0.422
Easy
25,039
https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/discuss/1032916/Python-2-liner
class Solution: def maximumTime(self, time: str) -> str: maxChar = lambda i: "23:59"[i] if time[0] in "2?" and time[1] in "0123?" else "19:59"[i] return "".join(c if c != "?" else maxChar(i) for i, c in enumerate(time))
latest-time-by-replacing-hidden-digits
Python 2-liner
cenkay
0
188
latest time by replacing hidden digits
1,736
0.422
Easy
25,040
https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/discuss/1032762/PYTHON-oror-EASY-oror-20MS-oror-HASHMAP
class Solution: def maximumTime(self, time: str) -> str: maxValues = { '0': '2', '1': {'0': '9', '1': '9', '2': '3'}, '3': '5', '4': '9' } result = [] for i, char in enumerate(time): if char == '?': if i == 0 and time[i + 1] != '?' and time[i + 1] >= '4': result.append('1') elif i == 1: result.append(maxValues['1'][result[i - 1]]) else: result.append(maxValues[str(i)]) else: result.append(char) return ''.join(result)
latest-time-by-replacing-hidden-digits
PYTHON || EASY || 20MS || HASHMAP
akashgkrishnan
0
79
latest time by replacing hidden digits
1,736
0.422
Easy
25,041
https://leetcode.com/problems/change-minimum-characters-to-satisfy-one-of-three-conditions/discuss/1032055/Python3-scan-through-a-z-w-prefix
class Solution: def minCharacters(self, a: str, b: str) -> int: pa, pb = [0]*26, [0]*26 for x in a: pa[ord(x)-97] += 1 for x in b: pb[ord(x)-97] += 1 ans = len(a) - max(pa) + len(b) - max(pb) # condition 3 for i in range(25): pa[i+1] += pa[i] pb[i+1] += pb[i] ans = min(ans, pa[i] + len(b) - pb[i]) # condition 2 ans = min(ans, len(a) - pa[i] + pb[i]) # condition 1 return ans
change-minimum-characters-to-satisfy-one-of-three-conditions
[Python3] scan through a-z w/ prefix
ye15
1
58
change minimum characters to satisfy one of three conditions
1,737
0.352
Medium
25,042
https://leetcode.com/problems/find-kth-largest-xor-coordinate-value/discuss/1032117/Python3-compute-xor-O(MNlog(MN))-or-O(MNlogK)-or-O(MN)
class Solution: def kthLargestValue(self, matrix: List[List[int]], k: int) -> int: m, n = len(matrix), len(matrix[0]) # dimensions ans = [] for i in range(m): for j in range(n): if i: matrix[i][j] ^= matrix[i-1][j] if j: matrix[i][j] ^= matrix[i][j-1] if i and j: matrix[i][j] ^= matrix[i-1][j-1] ans.append(matrix[i][j]) return sorted(ans)[-k]
find-kth-largest-xor-coordinate-value
[Python3] compute xor O(MNlog(MN)) | O(MNlogK) | O(MN)
ye15
15
936
find kth largest xor coordinate value
1,738
0.613
Medium
25,043
https://leetcode.com/problems/find-kth-largest-xor-coordinate-value/discuss/1032117/Python3-compute-xor-O(MNlog(MN))-or-O(MNlogK)-or-O(MN)
class Solution: def kthLargestValue(self, matrix: List[List[int]], k: int) -> int: m, n = len(matrix), len(matrix[0]) # dimensions pq = [] for i in range(m): for j in range(n): if i: matrix[i][j] ^= matrix[i-1][j] if j: matrix[i][j] ^= matrix[i][j-1] if i and j: matrix[i][j] ^= matrix[i-1][j-1] heappush(pq, matrix[i][j]) if len(pq) > k: heappop(pq) return pq[0]
find-kth-largest-xor-coordinate-value
[Python3] compute xor O(MNlog(MN)) | O(MNlogK) | O(MN)
ye15
15
936
find kth largest xor coordinate value
1,738
0.613
Medium
25,044
https://leetcode.com/problems/find-kth-largest-xor-coordinate-value/discuss/1032117/Python3-compute-xor-O(MNlog(MN))-or-O(MNlogK)-or-O(MN)
class Solution: def kthLargestValue(self, matrix: List[List[int]], k: int) -> int: m, n = len(matrix), len(matrix[0]) # dimensions vals = [] for i in range(m): for j in range(n): if i: matrix[i][j] ^= matrix[i-1][j] if j: matrix[i][j] ^= matrix[i][j-1] if i and j: matrix[i][j] ^= matrix[i-1][j-1] vals.append(matrix[i][j]) def part(lo, hi): """Partition vals from lo (inclusive) to hi (exclusive).""" i, j = lo+1, hi-1 while i <= j: if vals[i] < vals[lo]: i += 1 elif vals[lo] < vals[j]: j -= 1 else: vals[i], vals[j] = vals[j], vals[i] i += 1 j -= 1 vals[lo], vals[j] = vals[j], vals[lo] return j lo, hi = 0, len(vals) while lo < hi: mid = part(lo, hi) if mid + k < len(vals): lo = mid + 1 else: hi = mid return vals[lo]
find-kth-largest-xor-coordinate-value
[Python3] compute xor O(MNlog(MN)) | O(MNlogK) | O(MN)
ye15
15
936
find kth largest xor coordinate value
1,738
0.613
Medium
25,045
https://leetcode.com/problems/find-kth-largest-xor-coordinate-value/discuss/1563463/Python-3-Prefix-%22XOR%22-and-Quickselect-(but-why-built-in-sort()-is-faster)
class Solution: def quickselect(self, arr, k, low, high): """ select k largest element """ def swap(arr, i, j): arr[i], arr[j] = arr[j], arr[i] def partition(arr, low, high): """ select last elem as pivot, return the pivot index after rearranged array """ # randomly choose index randidx = random.randint(low,high) pivot = arr[randidx] swap(arr, randidx, high) i = low for j in range(low, high): if arr[j] > pivot: swap(arr, i, j) i += 1 swap(arr, i, high) return i if low == high: return arr[low] pivot_idx = partition(arr, low, high) if k-1 == pivot_idx: return arr[pivot_idx] elif k-1 > pivot_idx: return self.quickselect(arr, k, pivot_idx+1, high) else: return self.quickselect(arr, k, low, pivot_idx-1) return quickselect(nums, k, 0, len(nums)-1) def kthLargestValue(self, matrix: List[List[int]], k: int) -> int: """ prefix-XOR flatten matrix into 1d quickselect(k) [ ][-][+][ ] [ ][+][x][ ] [ ][ ][ ][ ] [ ][ ][ ][ ] """ nrow, ncol = len(matrix), len(matrix[0]) prefix_XOR = [[0 for _ in range(ncol)] for _ in range(nrow)] # init first row and first col prefix_XOR[0][0] = matrix[0][0] for i in range(1,ncol): prefix_XOR[0][i] = prefix_XOR[0][i-1] ^ matrix[0][i] for i in range(1,nrow): prefix_XOR[i][0] = prefix_XOR[i-1][0] ^ matrix[i][0] # prefix XOR for i in range(1,nrow): for j in range(1,ncol): prefix_XOR[i][j] = matrix[i][j] ^ prefix_XOR[i-1][j] ^ prefix_XOR[i][j-1] ^ prefix_XOR[i-1][j-1] # flatten 2d matrix into 1d flatten = [] for i in prefix_XOR: flatten += i # quick select k # res = self.quickselect(flatten, k, 0, len(flatten)-1) # why quickselect not working? (TLE) res = sorted(flatten)[-k] # why built-in sorted() works? return res
find-kth-largest-xor-coordinate-value
[Python 3] Prefix-"XOR" and Quickselect (but why built-in sort() is faster?)
nick19981122
1
126
find kth largest xor coordinate value
1,738
0.613
Medium
25,046
https://leetcode.com/problems/find-kth-largest-xor-coordinate-value/discuss/1197268/Python3-Solution-with-Comments-Faster-than-96
class Solution: def kthLargestValue(self, matrix: List[List[int]], k: int) -> int: res = [] prefix_sum = [[0]*(len(matrix[0])+1) for _ in range(0,len(matrix)+1)] #initialize prefix sum matrix # for each index (i,j) in matrix, calculate XOR of prefix_sum[i-1][j] and matrix[i][j] # then XOR the result with XOR of all values from matrix[i][0] to matrix[i][j-1] for i in range(1,len(matrix)+1): XOR_value = 0 #initialize XOR value for row i of matrix for j in range(1,len(matrix[0])+1): XOR_value ^= matrix[i-1][j-1] #XOR with value at index i,j of matrix (as loops start from 1, we use indices i-1 and j-1) prefix_sum[i][j] = XOR_value^prefix_sum[i-1][j] #update current index of prefix sum by XORing the current XOR value with the prefix sum at the upper cell res.append(prefix_sum[i][j]) #store this resultant XOR at res return sorted(res)[-k] #need k'th largest element, so sort it and get the value at the (k-1)'th index from the right
find-kth-largest-xor-coordinate-value
Python3 Solution with Comments, Faster than 96%
bPapan
1
73
find kth largest xor coordinate value
1,738
0.613
Medium
25,047
https://leetcode.com/problems/find-kth-largest-xor-coordinate-value/discuss/1358597/Python3-solution-beats-95-users
class Solution: def kthLargestValue(self, matrix: List[List[int]], k: int) -> int: dp = [] for i in range(len(matrix)): x = [] for j in range(len(matrix[0])): x.append(0) dp.append(x) for i in range(len(matrix)): c = 0 for j in range(len(matrix[0])): c ^= matrix[i][j] if j == 0: if i == 0: dp[i][j] = matrix[i][j] else: dp[i][j] = dp[i-1][j] ^ matrix[i][j] else: if i == 0: dp[i][j] = c else: dp[i][j] = c ^ dp[i-1][j] l = [] for i in dp: l += i return sorted(l,reverse=True)[k-1]
find-kth-largest-xor-coordinate-value
Python3 solution beats 95% users
EklavyaJoshi
0
78
find kth largest xor coordinate value
1,738
0.613
Medium
25,048
https://leetcode.com/problems/find-kth-largest-xor-coordinate-value/discuss/1032166/Python-Solution
class Solution: def kthLargestValue(self, matrix, k: int) -> int: large = [matrix[0][0]] n = len(matrix) m = len(matrix[0]) for i in range(1, n): matrix[i][0] ^= matrix[i - 1][0] large.append(matrix[i][0]) for j in range(1, m): matrix[0][j] ^= matrix[0][j - 1] large.append(matrix[0][j]) for i in range(1, n): for j in range(1, m): matrix[i][j] ^= matrix[i][j - 1] ^ matrix[i - 1][j] ^ matrix[i - 1][j - 1] large.append(matrix[i][j]) large.sort() return large[-k]
find-kth-largest-xor-coordinate-value
Python Solution
mariandanaila01
0
69
find kth largest xor coordinate value
1,738
0.613
Medium
25,049
https://leetcode.com/problems/building-boxes/discuss/1032104/Python3-math
class Solution: def minimumBoxes(self, n: int) -> int: x = int((6*n)**(1/3)) if x*(x+1)*(x+2) > 6*n: x -= 1 ans = x*(x+1)//2 n -= x*(x+1)*(x+2)//6 k = 1 while n > 0: ans += 1 n -= k k += 1 return ans
building-boxes
[Python3] math
ye15
12
371
building boxes
1,739
0.519
Hard
25,050
https://leetcode.com/problems/building-boxes/discuss/1032104/Python3-math
class Solution: def minimumBoxes(self, n: int) -> int: x = int((6*n)**(1/3)) if x*(x+1)*(x+2) > 6*n: x -= 1 n -= x*(x+1)*(x+2)//6 return x*(x+1)//2 + ceil((sqrt(1+8*n)-1)/2)
building-boxes
[Python3] math
ye15
12
371
building boxes
1,739
0.519
Hard
25,051
https://leetcode.com/problems/building-boxes/discuss/1777473/python3-Fastest-and-Most-Elegant-Script
class Solution: def minimumBoxes(self, n: int) -> int: a = 0 b = 0 s = 0 while n > s: a += 1 b += a s += b while n <= s: s -= a a -= 1 b -= 1 return b + 1
building-boxes
[python3] Fastest & Most Elegant Script
wubj97
1
69
building boxes
1,739
0.519
Hard
25,052
https://leetcode.com/problems/building-boxes/discuss/2792603/Python-or-Tetrahedral-and-Triangular-Numbers-or-O(m13)
class Solution: def minimumBoxes(self, m: int) -> int: def cbrt(x): return x**(1. / 3) # Find the first tetrahedral number greater than # or equal to m. x = cbrt(sqrt(3)*sqrt(243*(m**2) - 1) + 27*m) n = ceil(x/cbrt(9) + 1/(cbrt(3)*x) - 1) # If m is the nth tetrahedral number, return the # nth triangular number (the base). t_n =n*(n+1)*(n+2) // 6 if m == t_n: return n*(n+1)//2 # Otherwise, we must adjust the answer. ans = n*(n+1)//2 j = t_n + 1 while m < j: j -= n ans -= 1 n -= 1 return ans + 1
building-boxes
Python | Tetrahedral and Triangular Numbers | O(m^1/3)
on_danse_encore_on_rit_encore
0
1
building boxes
1,739
0.519
Hard
25,053
https://leetcode.com/problems/building-boxes/discuss/2111487/Python-or-Detailed-Explanation
class Solution: def minimumBoxes(self, n: int) -> int: r = 0 while (n_upper := r*(r+1)*(r+2)//6) < n: r += 1 m = r*(r+1)//2 for i in range(r, 0, -1): if (n_upper - i) < n: break n_upper -= i m -= 1 return m
building-boxes
Python | Detailed Explanation
Lindelt
0
137
building boxes
1,739
0.519
Hard
25,054
https://leetcode.com/problems/building-boxes/discuss/1032028/Python3.-Build-pyramid.-Easy-with-explanation.
class Solution: def minimumBoxes(self, n: int) -> int: boxesPlaced = 0 maxFloor = 1 boxesOnFloor = 0 while boxesPlaced < n: for i in range(1, maxFloor + 1): boxesPlaced += i boxesOnFloor += 1 if boxesPlaced >= n: break maxFloor += 1 return boxesOnFloor
building-boxes
Python3. Build pyramid. Easy with explanation.
yaroslav-repeta
0
74
building boxes
1,739
0.519
Hard
25,055
https://leetcode.com/problems/maximum-number-of-balls-in-a-box/discuss/1042922/Python3-freq-table
class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: freq = defaultdict(int) for x in range(lowLimit, highLimit+1): freq[sum(int(xx) for xx in str(x))] += 1 return max(freq.values())
maximum-number-of-balls-in-a-box
[Python3] freq table
ye15
11
1,300
maximum number of balls in a box
1,742
0.739
Easy
25,056
https://leetcode.com/problems/maximum-number-of-balls-in-a-box/discuss/1043417/Python-3-Easy-to-understand-COMMENTED-solution.
class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: boxes = [0] * 100 for i in range(lowLimit, highLimit + 1): # For the current number "i", convert it into a list of its digits. # Compute its sum and increment the count in the frequency table. boxes[sum([int(j) for j in str(i)])] += 1 return max(boxes)
maximum-number-of-balls-in-a-box
[Python 3] - Easy to understand COMMENTED solution.
mb557x
7
675
maximum number of balls in a box
1,742
0.739
Easy
25,057
https://leetcode.com/problems/maximum-number-of-balls-in-a-box/discuss/1692190/Python-Solution-(Dictionary-based)
class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: box = {} for balls in range(lowLimit,highLimit+1): boxNo = self.sumOfDigits(balls) if boxNo in box: box[boxNo] += 1 else: box[boxNo] = 1 max = 0 for key in box: if box[key] > max: max = box[key] return max def sumOfDigits(self,n): ans = 0 while n > 0: ans += n % 10 n = n // 10 return ans
maximum-number-of-balls-in-a-box
Python Solution (Dictionary based)
s_m_d_29
1
123
maximum number of balls in a box
1,742
0.739
Easy
25,058
https://leetcode.com/problems/maximum-number-of-balls-in-a-box/discuss/1043081/Python-Dictionary-or-easy-to-understand
class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: res = 0 boxes = collections.defaultdict(int) for num in range(lowLimit, highLimit+1): box = 0 while num: digit = num%10 num = num//10 box += digit boxes[box] +=1 res = max(res, boxes[box]) return res
maximum-number-of-balls-in-a-box
[Python] Dictionary | easy to understand
SonicM
1
229
maximum number of balls in a box
1,742
0.739
Easy
25,059
https://leetcode.com/problems/maximum-number-of-balls-in-a-box/discuss/2781705/ONLY-ARRAY-oror-NO-HASHING-oror-2ms-SOULTION
class Solution: def countBalls(self, lowlimit: int, highlimit: int) -> int: a=[] a=[0 for i in range(highlimit+1)] for i in range(lowlimit,highlimit+1): sum=0 while(i>0): b=i%10 i=i//10 sum+=b a[sum]=a[sum]+1 c=max(a) return(c)
maximum-number-of-balls-in-a-box
ONLY ARRAY || NO HASHING || 2ms SOULTION
Ujjwal_2458
0
2
maximum number of balls in a box
1,742
0.739
Easy
25,060
https://leetcode.com/problems/maximum-number-of-balls-in-a-box/discuss/2654509/Python3_Easy_Understand_Method
class Solution: def countBalls(self, lowLimit, highLimit): dic_A = defaultdict(int) for i in range(lowLimit, highLimit+1): count = 0 for j in str(i): count += int(j) dic_A[count] = dic_A[count]+1 return max(dic_A.values())
maximum-number-of-balls-in-a-box
Python3_Easy_Understand_Method
Hsien_Chiu
0
1
maximum number of balls in a box
1,742
0.739
Easy
25,061
https://leetcode.com/problems/maximum-number-of-balls-in-a-box/discuss/2507451/Python3-Beats-99.7-with-Dictionary-O(n)-Time-O(n)-Space
class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: h = defaultdict(int) # find the first box number s = 0 temp = lowLimit while temp > 0: s += temp % 10 temp = temp // 10 h[s] += 1 x = lowLimit + 1 while x <= highLimit: # check rightmost digit if 1 <= x % 10 <= 9: s = s+1 else: s = s - 8 temp = x // 10 while temp > 0 and temp % 10 == 0: s -= 9 temp = temp // 10 h[s] += 1 x += 1 return max(h.values())
maximum-number-of-balls-in-a-box
[Python3] Beats 99.7% with Dictionary - O(n) Time, O(n) Space
rt500
0
46
maximum number of balls in a box
1,742
0.739
Easy
25,062
https://leetcode.com/problems/maximum-number-of-balls-in-a-box/discuss/2348005/Python-dictionary-solution
class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: hashmap = {} for i in range(lowLimit, highLimit +1): digit_sum = 0 while i: digit_sum += i%10 i = i//10 if digit_sum not in hashmap: hashmap[digit_sum] = 1 else: hashmap[digit_sum] += 1 return max(hashmap.values())
maximum-number-of-balls-in-a-box
Python dictionary solution
hochunlin
0
49
maximum number of balls in a box
1,742
0.739
Easy
25,063
https://leetcode.com/problems/maximum-number-of-balls-in-a-box/discuss/2290269/Dictionary-self-explaining-code
class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: boxes = {} for ball_number in range(lowLimit, highLimit + 1): ball_sum = sum([int(str_number) for str_number in str(ball_number)]) if ball_sum in boxes: boxes[ball_sum] += 1 else: boxes[ball_sum] = 1 return max([count for box, count in boxes.items()])
maximum-number-of-balls-in-a-box
Dictionary, self-explaining code
Simzalabim
0
24
maximum number of balls in a box
1,742
0.739
Easy
25,064
https://leetcode.com/problems/maximum-number-of-balls-in-a-box/discuss/2270443/Maximum-Number-of-Balls-in-a-Box
class Solution: def countSum(self,x): y=0 while(x!=0 ): y+=x%10 x=x//10 return y def countBalls(self, lowLimit: int, highLimit: int) -> int: x={} count=0 for i in range(lowLimit,highLimit+1): y = self.countSum(i) if y in x: x[y] +=1 else: x[y]=1 return max([i for i in x.values()])
maximum-number-of-balls-in-a-box
Maximum Number of Balls in a Box
dhananjayaduttmishra
0
22
maximum number of balls in a box
1,742
0.739
Easy
25,065
https://leetcode.com/problems/maximum-number-of-balls-in-a-box/discuss/2179957/Python-simple-solution
class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: ans = [0 for x in range(47)] for i in range(lowLimit, highLimit+1): ans[sum(map(int,list(str(i))))] += 1 return max(ans)
maximum-number-of-balls-in-a-box
Python simple solution
StikS32
0
53
maximum number of balls in a box
1,742
0.739
Easy
25,066
https://leetcode.com/problems/maximum-number-of-balls-in-a-box/discuss/2095436/PYTHON-or-Simple-python-solution
class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: boxMap = {} def getSum(n): sum = 0 for digit in str(n): sum += int(digit) return sum for i in range(lowLimit, highLimit + 1): boxMap[getSum(i)] = 1 + boxMap.get(getSum(i), 0) res = 0 for i in boxMap: res = max(res, boxMap[i]) return res
maximum-number-of-balls-in-a-box
PYTHON | Simple python solution
shreeruparel
0
103
maximum number of balls in a box
1,742
0.739
Easy
25,067
https://leetcode.com/problems/maximum-number-of-balls-in-a-box/discuss/1913734/Python-solution-memory-less-than-74
class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: freq = [0] * 45 for i in range(lowLimit, highLimit+1): dig_sum = sum([int(x) for x in str(i)]) freq[dig_sum - 1] += 1 return max(freq)
maximum-number-of-balls-in-a-box
Python solution memory less than 74%
alishak1999
0
93
maximum number of balls in a box
1,742
0.739
Easy
25,068
https://leetcode.com/problems/maximum-number-of-balls-in-a-box/discuss/1848002/Python-dollarolution
class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: d, maximum = {}, 1 for i in range(lowLimit, highLimit+1): count = 0 while i != 0: count += i%10 i //= 10 if count in d: d[count] += 1 maximum = max(maximum,d[count]) else: d[count] = 1 return maximum
maximum-number-of-balls-in-a-box
Python $olution
AakRay
0
63
maximum number of balls in a box
1,742
0.739
Easy
25,069
https://leetcode.com/problems/maximum-number-of-balls-in-a-box/discuss/1845703/3-Lines-Python-Solution-oror-50-Faster-oror-Memory-less-than-85
class Solution: def countBalls(self, l: int, h: int) -> int: ans=[0]*46 for i in range(l,h+1): ans[sum([int(j) for j in str(i)])]+=1 return max(ans)
maximum-number-of-balls-in-a-box
3-Lines Python Solution || 50% Faster || Memory less than 85%
Taha-C
0
73
maximum number of balls in a box
1,742
0.739
Easy
25,070
https://leetcode.com/problems/maximum-number-of-balls-in-a-box/discuss/1845703/3-Lines-Python-Solution-oror-50-Faster-oror-Memory-less-than-85
class Solution: def countBalls(self, l: int, h: int) -> int: ans=defaultdict(int) for i in range(l,h+1): s=sum([int(i) for i in str(i)]) ; ans[s]+=1 return max(ans.values())
maximum-number-of-balls-in-a-box
3-Lines Python Solution || 50% Faster || Memory less than 85%
Taha-C
0
73
maximum number of balls in a box
1,742
0.739
Easy
25,071
https://leetcode.com/problems/maximum-number-of-balls-in-a-box/discuss/1324917/Python3-solution
class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: d = {} res = 0 for i in range(lowLimit, highLimit+1, 1): tmp = 0 while i >0: tmp += i%10 i = i//10 if tmp not in d: d[tmp] =1 else: d[tmp]+=1 if d[tmp] > res: res = d[tmp] return res
maximum-number-of-balls-in-a-box
Python3 solution
Wyhever
0
98
maximum number of balls in a box
1,742
0.739
Easy
25,072
https://leetcode.com/problems/maximum-number-of-balls-in-a-box/discuss/1114976/Simple-solution-in-normal-programming-way
class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: a=[0]*46 for i in range(lowLimit,highLimit+1): a[self.noofballs(i)] += 1 return (max(a)) def noofballs(self,n:int): sum=0 while n>0: sum=sum+n%(10) n=n//10 return sum
maximum-number-of-balls-in-a-box
Simple solution in normal programming way
ashish87
0
103
maximum number of balls in a box
1,742
0.739
Easy
25,073
https://leetcode.com/problems/maximum-number-of-balls-in-a-box/discuss/1112626/simple-python-solution
class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: box=[0]*(max(lowLimit,highLimit)) for i in range(lowLimit,highLimit+1): s=sum(list(map(int,str(i)))) box[s-1]+=1 return max(box) ```
maximum-number-of-balls-in-a-box
simple python solution
kalluri_sumanth
0
184
maximum number of balls in a box
1,742
0.739
Easy
25,074
https://leetcode.com/problems/maximum-number-of-balls-in-a-box/discuss/1043185/Python3-simple-solution-using-dictionary
class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: d = {} for i in range(lowLimit, highLimit+1): d[sum(list(map(int,list(str(i)))))] = d.get(sum(list(map(int,list(str(i))))),0) + 1 return max(d.values())
maximum-number-of-balls-in-a-box
Python3 simple solution using dictionary
EklavyaJoshi
0
60
maximum number of balls in a box
1,742
0.739
Easy
25,075
https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/discuss/1042939/Python3-graph
class Solution: def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]: graph = {} for u, v in adjacentPairs: graph.setdefault(u, []).append(v) graph.setdefault(v, []).append(u) ans = [] seen = set() stack = [next(x for x in graph if len(graph[x]) == 1)] while stack: n = stack.pop() ans.append(n) seen.add(n) for nn in graph[n]: if nn not in seen: stack.append(nn) return ans
restore-the-array-from-adjacent-pairs
[Python3] graph
ye15
14
1,300
restore the array from adjacent pairs
1,743
0.687
Medium
25,076
https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/discuss/1043117/Python3-Graph-%2B-DFS-or-easy-to-understand
class Solution: def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]: # create the map adj = collections.defaultdict(list) for a, b in adjacentPairs: adj[a].append(b) adj[b].append(a) # find the start num start = adjacentPairs[0][0] for k, v in adj.items(): if len(v) ==1: start = k break # dfs to connect the graph nums=[] seen = set() def dfs(num): seen.add(num) for next_num in adj[num]: if next_num in seen: continue dfs(next_num) nums.append(num) dfs(start) return nums
restore-the-array-from-adjacent-pairs
[Python3] Graph + DFS | easy to understand
SonicM
8
1,000
restore the array from adjacent pairs
1,743
0.687
Medium
25,077
https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/discuss/1915756/Python3-Easy-DFS-Solution
class Solution: def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]: adjList = defaultdict(list) visited = set() res = [] for a, b in adjacentPairs: adjList[a].append(b) adjList[b].append(a) def dfs(element): visited.add(element) res.append(element) for nei in adjList[element]: if nei not in visited: dfs(nei) for start in adjList.keys(): if len(adjList[start]) == 1: dfs(start) break return res
restore-the-array-from-adjacent-pairs
[Python3] Easy DFS Solution
ochen24
2
152
restore the array from adjacent pairs
1,743
0.687
Medium
25,078
https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/discuss/2601489/Python-Readable-Iterative-Solution-using-HashSet
class Solution: def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]: # make the connections conns = collections.defaultdict(set) # connect the connections for a, b in adjacentPairs: conns[a].add(b) conns[b].add(a) # find the start value for node, conn in conns.items(): if len(conn) == 1: break # remove the first node from the first connection result = [node] while conns[node]: # get the next element # (there can only be one, as we always remove one) new = conns[node].pop() # append the new element to the list result.append(new) # delete node from the next connections conns[new].remove(node) # set the new element node = new return result
restore-the-array-from-adjacent-pairs
[Python] - Readable Iterative Solution using HashSet
Lucew
1
141
restore the array from adjacent pairs
1,743
0.687
Medium
25,079
https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/discuss/2177279/python3-simple-dfs-solution
class Solution: def restoreArray(self, adj: List[List[int]]) -> List[int]: ## RC ## ## APPROACH : GRAPH / DFS ## graph = collections.defaultdict(list) for u,v in adj: graph[u].append(v) graph[v].append(u) first = None for u in graph: if len(graph[u]) == 1: first = u break res = [] visited = set() def dfs(node): if node in visited: return visited.add(node) res.append(node) for nei in graph[node]: dfs(nei) dfs(first) return res
restore-the-array-from-adjacent-pairs
[python3] simple dfs solution
101leetcode
1
57
restore the array from adjacent pairs
1,743
0.687
Medium
25,080
https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/discuss/1316177/Python3-solution-using-dictionary-and-dfs
class Solution: def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]: d = {} for i,j in adjacentPairs: d[i] = d.get(i,[])+[j] d[j] = d.get(j,[])+[i] for i in d: if len(d[i]) == 1: start = i break def dfs(s,r,v,d): r.append(s) v.add(s) for i in d[s]: if i not in v: v.add(i) dfs(i,r,v,d) visited = set() res = [] dfs(start,res,visited,d) return res
restore-the-array-from-adjacent-pairs
Python3 solution using dictionary and dfs
EklavyaJoshi
1
107
restore the array from adjacent pairs
1,743
0.687
Medium
25,081
https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/discuss/1043896/Python3-simple-solution
class Solution: def restoreArray(self, ap: List[List[int]]) -> List[int]: nei = collections.defaultdict(list) for x, y in ap: nei[x].append(y) nei[y].append(x) res = [] for k, v in nei.items(): if len(v) == 1: res = [k, v[0]] break while len(res) < len(ap)+1: for x in nei[res[-1]]: if x != res[-2]: res.append(x) break return res
restore-the-array-from-adjacent-pairs
[Python3] simple solution
joysword
1
111
restore the array from adjacent pairs
1,743
0.687
Medium
25,082
https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/discuss/1043889/Python-Solution-with-Detailed-Comments
class Solution: def restoreArray(self, A: List[List[int]]) -> List[int]: """ Build an edge-list/graph. Just do print(graph) if you're not sure what's happening here. """ graph = collections.defaultdict(list) for i, j in A: graph[i].append(j) graph[j].append(i) """ If you print(graph), you can see that the start and end nodes always point to ONLY one node, while middle nodes point to two nodes (as a doubly linked list). """ start = None for i in graph.keys(): if len(graph[i]) == 1: start = i """ DFS code. This is a "greedy" DFS as we only call it once. We know the path we choose will be successful since we are guarunteed to start at the end of the array. That's why we can keep the result &amp; seen 'outside' of the dfs function. """ result, seen = [], set() def dfs(i): seen.add(i) for next_node in graph[i]: if next_node not in seen: dfs(next_node) result.append(i) """ Now, we just call dfs &amp; return! """ dfs(start) return result
restore-the-array-from-adjacent-pairs
Python Solution with Detailed Comments
dev-josh
1
156
restore the array from adjacent pairs
1,743
0.687
Medium
25,083
https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/discuss/2203282/python-3-or-space-optimized-dfs
class Solution: def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]: graph = collections.defaultdict(list) for u, v in adjacentPairs: graph[u].append(v) graph[v].append(u) nums = [] for num, adj in graph.items(): if len(adj) == 1: nums.append(num) nums.append(adj[0]) break for _ in range(len(graph) - 2): if graph[nums[-1]][0] != nums[-2]: nums.append(graph[nums[-1]][0]) else: nums.append(graph[nums[-1]][1]) return nums
restore-the-array-from-adjacent-pairs
python 3 | space optimized dfs
dereky4
0
48
restore the array from adjacent pairs
1,743
0.687
Medium
25,084
https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/discuss/1526225/Python3-solution-with-comments
class Solution: def restoreArray(self, arr: List[List[int]]) -> List[int]: s = set() d = {} for i in range(len(arr)): for j in range(len(arr[0])): if arr[i][j] not in d: # getting a dict to store every element and a list with positions where he could go if j == 0: d[arr[i][j]] = [arr[i][1]] else: d[arr[i][j]] = [arr[i][0]] else: if j == 0: d[arr[i][j]].append(arr[i][1]) else: d[arr[i][j]].append(arr[i][0]) if arr[i][j] not in s: # get the 2 edges of the array (they appear only once) s.add(arr[i][j]) else: s.remove(arr[i][j]) s = list(s) seen = set() # creating a set to mark where we've been count = 1 res = [s[0]] element = s[0] seen.add(element) while count != len(arr)+1: # the number of elements in our list will be len(arr) + 1 if len(d[element]) == 1 and count > 1: # get out because we found the other edge (the edge will have 1 element in his list) break if d[element][0] not in seen: res.append(d[element][0]) element = d[element][0] seen.add(element) # mark every element we added to our list elif d[element][1] not in seen: res.append(d[element][1]) element = d[element][1] seen.add(element) # mark every element we added to our list count += 1 return res
restore-the-array-from-adjacent-pairs
Python3 solution with comments
FlorinnC1
0
141
restore the array from adjacent pairs
1,743
0.687
Medium
25,085
https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/discuss/1526138/Python3-Solution-with-using-dfs
class Solution: def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]: graph = {} # build graph for u, v in adjacentPairs: if u not in graph: graph[u] = [] graph[u].append(v) if v not in graph: graph[v] = [] graph[v].append(u) visited = set() ans = [] # find begin of array cur = 0 for v in graph: if len(graph[v]) == 1: cur = v visited.add(cur) ans.append(cur) break # dfs while len(ans) < len(graph): neighbors = graph[cur] for neighbor in neighbors: if neighbor not in visited: cur = neighbor visited.add(cur) ans.append(cur) return ans
restore-the-array-from-adjacent-pairs
[Python3] Solution with using dfs
maosipov11
0
60
restore the array from adjacent pairs
1,743
0.687
Medium
25,086
https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/discuss/1512178/Python-O(n)-time-O(n)-space-solution
class Solution: def restoreArray(self, pairs: List[List[int]]) -> List[int]: h = defaultdict(set) n = 0 for x, y in pairs: h[x].add(y) h[y].add(x) n += 1 n += 1 # n distinct numbers p = -1 for v in h: if len(h[v]) ==1: p = v res = [] cnt = 0 while len(res) < n: res.append(p) if len(h[p]) == 1: val = sum(h[p]) ## takes O(1), cuz h[p] has only 1 element else: break h[p].remove(val) h[val].remove(p) p = val cnt += 1 return res
restore-the-array-from-adjacent-pairs
Python O(n) time, O(n) space solution
byuns9334
0
156
restore the array from adjacent pairs
1,743
0.687
Medium
25,087
https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/discuss/1055499/Python3-or-Just-map-the-Relations
class Solution: def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]: # map the relations between two elements using dictionary # key=element, value=[elements it is paired with] dict1={} for ii in adjacentPairs: if ii[0] in dict1.keys(): dict1[ii[0]].append(ii[1]) if ii[0] not in dict1.keys(): dict1[ii[0]]=[ii[1]] if ii[1] in dict1.keys(): dict1[ii[1]].append(ii[0]) if ii[1] not in dict1.keys(): dict1[ii[1]]=[ii[0]] # 1st and last element of series will have only pairing element in the list # finding those 2 elements #temp array to store those 2 elements gajab=[] for ii in dict1.keys(): if len(dict1[ii])==1: # if len==1 it can be start or ending elemnt of list gajab.append(ii) # Initializing Solution array with all elemnts as Zero # len of solution array = len(pairs)+1 ans=[0]*((len(adjacentPairs))+1) #Placing 1st and last element in array.You can make any of two element as STARTING or ENDING ans[0]=gajab[0] ans[-1]=gajab[1] #using 1st element in ANS array to find its relation element and then so on... for ii in range(len(ans)-1): pp=dict1[ans[ii]][0] dict1[pp].remove(ans[ii]) # removing the element relation that is already in ANS array ans[ii+1]=pp # adding the element in ANS array at correct position return(ans)
restore-the-array-from-adjacent-pairs
Python3 | Just map the Relations
vishal9994
0
110
restore the array from adjacent pairs
1,743
0.687
Medium
25,088
https://leetcode.com/problems/can-you-eat-your-favorite-candy-on-your-favorite-day/discuss/1042952/Python3-greedy
class Solution: def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]: prefix = [0] for x in candiesCount: prefix.append(prefix[-1] + x) # prefix sum return [prefix[t] < (day+1)*cap and day < prefix[t+1] for t, day, cap in queries]
can-you-eat-your-favorite-candy-on-your-favorite-day
[Python3] greedy
ye15
6
279
can you eat your favorite candy on your favorite day
1,744
0.329
Medium
25,089
https://leetcode.com/problems/palindrome-partitioning-iv/discuss/1042964/Python3-dp
class Solution: def checkPartitioning(self, s: str) -> bool: mp = {} for i in range(2*len(s)-1): lo, hi = i//2, (i+1)//2 while 0 <= lo <= hi < len(s) and s[lo] == s[hi]: mp.setdefault(lo, set()).add(hi) lo -= 1 hi += 1 @lru_cache(None) def fn(i, k): """Return True if s[i:] can be split into k palindromic substrings.""" if k < 0: return False if i == len(s): return k == 0 return any(fn(ii+1, k-1) for ii in mp[i]) return fn(0, 3)
palindrome-partitioning-iv
[Python3] dp
ye15
10
725
palindrome partitioning iv
1,745
0.459
Hard
25,090
https://leetcode.com/problems/palindrome-partitioning-iv/discuss/1042964/Python3-dp
class Solution: def checkPartitioning(self, s: str) -> bool: mp = defaultdict(set) for i in range(2*len(s)-1): lo, hi = i//2, (i+1)//2 while 0 <= lo <= hi < len(s) and s[lo] == s[hi]: mp[lo].add(hi) lo, hi = lo-1, hi+1 for i in range(len(s)): for j in range(i+1, len(s)): if i-1 in mp[0] and j-1 in mp[i] and len(s)-1 in mp[j]: return True return False
palindrome-partitioning-iv
[Python3] dp
ye15
10
725
palindrome partitioning iv
1,745
0.459
Hard
25,091
https://leetcode.com/problems/palindrome-partitioning-iv/discuss/1043049/Python-High-Speed-Permutation-Finding
class Solution: def checkPartitioning(self, s: str) -> bool: # Add bogus characters to s, so we only have to worry about odd palindromes. s = "|" + "|".join(s) + "|" # p[i] is the length of the longest palindrome centered at i, minus 2. p = [0] * len(s) # c is the center of the longest palindrome found so far that ends at r. # r is the index of the rightmost element in that palindrome; c + p[c] == r. c = r = 0 for i in range(len(s)): # The mirror of i about c. mirror = c - (i - c) # If there is a palindrome centered on the mirror that is also within the # c-palindrome, then we dont have to check a few characters as we # know they will match already. p[i] = max(min(r - i, p[mirror]), 0) # We expand the palindrome centered at i. a = i + (p[i] + 1) b = i - (p[i] + 1) while a < len(s) and b >= 0 and s[a] == s[b]: p[i] += 1 a += 1 b -= 1 # If the palindrome centered at i extends beyond r, we update c to i. if i + p[i] > r: c = i r = i + p[i] @lru_cache(None) def dfs(i, k): # can s[i:] be decomposed into k palindromes mid = i + ((len(p) - i) // 2) if k == 1: # s[i:] itself must be a palindrome return p[mid] == mid - i for j in range(mid, i - 1, -1): # p[j] == j - i means s[i:j + p[j]] is a palindrome if p[j] == j - i and dfs(j + p[j], k - 1): return True return False return dfs(0, 3)
palindrome-partitioning-iv
Python - High Speed Permutation Finding
mildog8
2
199
palindrome partitioning iv
1,745
0.459
Hard
25,092
https://leetcode.com/problems/palindrome-partitioning-iv/discuss/2812702/Python3-Solution-or-DP-or-Bit-Manipulation-or-O(n2)
class Solution: def checkPartitioning(self, S): N = len(S) dp = [1] + [0] * N for i in range(2 * N - 1): l = i // 2 r = l + (i &amp; 1) while 0 <= l and r < N and S[l] == S[r]: dp[r + 1] |= (dp[l] << 1) l -= 1 r += 1 return bool(dp[-1] &amp; (1 << 3))
palindrome-partitioning-iv
✔ Python3 Solution | DP | Bit Manipulation | O(n^2)
satyam2001
1
14
palindrome partitioning iv
1,745
0.459
Hard
25,093
https://leetcode.com/problems/palindrome-partitioning-iv/discuss/1833531/Simple-python-solution-O(N2)-or-Easy-to-understand
class Solution: def checkPartitioning(self, s: str) -> bool: n=len(s) pal=[[False]*n for i in range(n)] for i in range(n): pal[i][i]=True for i in range(n-1,-1,-1): for j in range(i+1,n): if i+1==j and s[i]==s[j]: pal[i][j]=True if pal[i+1][j-1] and s[i]==s[j]: pal[i][j]=True dp=[[False for i in range(4)] for j in range(n+1)] dp[n][3]=True for ind in range(n-1,-1,-1): for i in range(ind,n): if pal[ind][i]: dp[ind][2] |= dp[i+1][3] dp[ind][1] |= dp[i+1][2] dp[ind][0] |= dp[i+1][1] return dp[0][0]
palindrome-partitioning-iv
Simple python solution O(N^2) | Easy to understand
_YASH_
0
71
palindrome partitioning iv
1,745
0.459
Hard
25,094
https://leetcode.com/problems/sum-of-unique-elements/discuss/1103188/Runtime-97-or-Python-easy-hashmap-solution
class Solution: def sumOfUnique(self, nums: List[int]) -> int: hashmap = {} for i in nums: if i in hashmap.keys(): hashmap[i] += 1 else: hashmap[i] = 1 sum = 0 for k, v in hashmap.items(): if v == 1: sum += k return sum
sum-of-unique-elements
Runtime 97% | Python easy hashmap solution
vanigupta20024
19
1,900
sum of unique elements
1,748
0.757
Easy
25,095
https://leetcode.com/problems/sum-of-unique-elements/discuss/1135187/Python-faster-than-99-(so-they-say)
class Solution: def sumOfUnique(self, nums: List[int]) -> int: uniq = [] [uniq.append(num) for num in nums if nums.count(num) == 1] return sum(uniq)
sum-of-unique-elements
Python faster than 99% (so they say)
111110100
7
853
sum of unique elements
1,748
0.757
Easy
25,096
https://leetcode.com/problems/sum-of-unique-elements/discuss/1504051/Python-Runtime-98-or-Set
class Solution: def sumOfUnique(self, nums: List[int]) -> int: s = set(nums) for i in nums: if nums.count(i) > 1 and i in s: s.remove(i) return sum(s)
sum-of-unique-elements
[Python] Runtime 98% | Set
deleted_user
3
336
sum of unique elements
1,748
0.757
Easy
25,097
https://leetcode.com/problems/sum-of-unique-elements/discuss/1200613/Easy-simple-Python-3-solution-using-counter
class Solution: def sumOfUnique(self, nums: List[int]) -> int: count = Counter(nums) ans = 0 for index,value in enumerate(nums): if count[value]==1: ans+=value return ans
sum-of-unique-elements
Easy simple Python 3 solution using counter
Sanyamx1x
3
261
sum of unique elements
1,748
0.757
Easy
25,098
https://leetcode.com/problems/sum-of-unique-elements/discuss/1056649/Python3-freq-table
class Solution: def sumOfUnique(self, nums: List[int]) -> int: freq = {} for x in nums: freq[x] = 1 + freq.get(x, 0) return sum(x for x in nums if freq[x] == 1)
sum-of-unique-elements
[Python3] freq table
ye15
2
84
sum of unique elements
1,748
0.757
Easy
25,099