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/using-a-robot-to-print-the-lexicographically-smallest-string/discuss/2679020/Python-or-Stack-or-Clean-Explained-and-Easy-to-Understand
class Solution: def robotWithString(self, s: str) -> str: st = [] g = Counter(s) f = sorted(list(set(s))) f.append('z') cur = 0 re = [] for i in s: if i != f[cur]: st.append(i) g[i] -= 1 while(g[f[cur]] == 0) and cur < len(f) - 1: cur+=1 else: re.append(i) g[i] -= 1 while(g[f[cur]] == 0) and cur < len(f) - 1: cur+=1 while(st and st[-1] <= f[cur]): re.append(st.pop()) while st: re.append(st.pop()) # print(cur, f, g, re) return ''.join(re)
using-a-robot-to-print-the-lexicographically-smallest-string
Python | Stack | Clean, Explained, and Easy to Understand
lukewu28
4
260
using a robot to print the lexicographically smallest string
2,434
0.381
Medium
33,300
https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/discuss/2679754/Python3-Suffix-Minimum
class Solution: def robotWithString(self, s: str) -> str: ret, n = "", len(s) suffixMin = [None]*n # construct suffix minimum array for i in range(n-1, -1, -1): if i == n-1: suffixMin[i] = s[i] else: suffixMin[i] = min(s[i], suffixMin[i+1]) t = [] for i in range(n): # append character at current index i to string t t.append(s[i]) # check whether the last character of string t is not larger than the suffix min at index i+1, # if so, it means we cannot find a smaller character from the characters on the right side of current index i, # and we should print out the last character of string t while t and (i == n-1 or t[-1] <= suffixMin[i+1]): ret += t.pop() return ret
using-a-robot-to-print-the-lexicographically-smallest-string
[Python3] Suffix Minimum
teyuanliu
2
26
using a robot to print the lexicographically smallest string
2,434
0.381
Medium
33,301
https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/discuss/2686943/Python-oror-Easy-Solution-oror-HashMap-oror-Stack
class Solution: def robotWithString(self, s: str) -> str: # Count the Occurence of characters in the String. charMap = Counter(s) p = "" # Final Output or Operation 2. t = [] # Auxillary or Operation 1. "---------Next--Minimum--Character---------" def minInCharMap(): for char in string.ascii_lowercase: if charMap[char] > 0: return char return "#" "------------------------------------------" # main body i = 0 while (i < len(s)): next_min_ch_St = minInCharMap() #next minimum Character from charMap. if (len(t) == 0): # Mandatory when t is empty. t.append(s[i]) charMap[s[i]] -= 1 i += 1 elif (next_min_ch_St < t[-1]): # if next minimum element after ith character is smaller than last element in then perform Operation 1. t.append(s[i]) charMap[s[i]] -= 1 i += 1 else: # if next minimum element after ith character is greater than last element in then perform Operation 2. p += t.pop() while(len(t) > 0): p += t.pop() return p
using-a-robot-to-print-the-lexicographically-smallest-string
Python || Easy Solution || HashMap || Stack
dib_675
0
19
using a robot to print the lexicographically smallest string
2,434
0.381
Medium
33,302
https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/discuss/2683811/Python-Intuitive-Explanation-oror-Beats-100-of-the-Python-Submissions.
class Solution: def robotWithString(self, s: str) -> str: n=len(s) m=[0]*n+[s[n-1]] for i in range(n-1,-1,-1): if s[i]<m[i+1]: m[i]=s[i] else: m[i]=m[i+1] t=[] p=[] for i in range(len(s)): t.append(s[i]) while t and t[-1]<=m[i+1]: p.append(t.pop()) while t : p.append(t.pop()) return "".join(p)
using-a-robot-to-print-the-lexicographically-smallest-string
Python Intuitive Explanation || Beats 100% of the Python Submissions.
code_is_in_my_veins
0
14
using a robot to print the lexicographically smallest string
2,434
0.381
Medium
33,303
https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/discuss/2683430/Python3-Recursive-Solution
class Solution: def robotWithString(self, s: str) -> str: def helper(string, target, carryon, res): index = None for t in range(len(carryon)-1, -1, -1): if carryon[t] <= target: index = t else: break if index != None: res.append(carryon[index:][::-1]) carryon = carryon[:index] if target in string: temp_res = string.split(target) carryon += ''.join(temp_res[:-1]) res.append(target*(len(temp_res)-1)) if target == 'z': res.append(carryon[::-1]) else: helper(temp_res[-1], chr(ord(target)+1), carryon, res) else: if target == 'z': res += carryon[::-1] else: helper(string, chr(ord(target)+1), carryon, res) res = [] helper(s, 'a', '', res) return ''.join(res)
using-a-robot-to-print-the-lexicographically-smallest-string
Python3 Recursive Solution
xxHRxx
0
42
using a robot to print the lexicographically smallest string
2,434
0.381
Medium
33,304
https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/discuss/2683319/Using-a-suffix-array-dollardollarO(n)dollardollar
class Solution: def robotWithString(self, s: str) -> str: suff = [] N = len(s) suff.append('{}') for i in range(N - 1, -1, -1): suff.append(min(suff[-1], s[i])) suff = suff[::-1] res = [] st = [] for i, c in enumerate(s): if suff[i + 1] <= c: st.append(c) else: res.append(c) while st and st[-1] <= suff[i + 1]: res.append(st.pop()) return "".join(res + st[::-1])
using-a-robot-to-print-the-lexicographically-smallest-string
Using a suffix array $$O(n)$$
mohitkumar36
0
3
using a robot to print the lexicographically smallest string
2,434
0.381
Medium
33,305
https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/discuss/2683310/Python-O(n)-time-greedy-simulate-the-whole-process.
class Solution: def robotWithString(self, s: str) -> str: suffix_min = [(s[-1], len(s) - 1)] for i in range(len(s) - 2, -1, -1): prev_min = suffix_min[-1] if prev_min[0] < s[i]: suffix_min.append(prev_min) else: suffix_min.append((s[i], i)) suffix_min = suffix_min[-1::-1] p = list() t = list() s = list(s) min_char, index = suffix_min[0] p += min_char t += s[:index] l = index + 1 while l < len(s): min_char, index = suffix_min[l] while t and t[-1] <= min_char: p.append(t.pop()) p.append(min_char) t += s[l:index] l = index + 1 p += t[-1::-1] return "".join(p)
using-a-robot-to-print-the-lexicographically-smallest-string
Python O(n) time, greedy, simulate the whole process.
yiming999
0
11
using a robot to print the lexicographically smallest string
2,434
0.381
Medium
33,306
https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/discuss/2682467/Python3-or-Using-Stack-or-O(n)
class Solution: def robotWithString(self, s: str) -> str: def getMinChar(freq): for f in range(len(freq)): if freq[f]>0: return f+97 return -1 freq=[0]*26 for c in s: freq[ord(c)-97]+=1 stack=[] ans='' for c in s: stack.append(c) freq[ord(c)-97]-=1 while stack and ord(stack[-1])<=getMinChar(freq): ans+=stack.pop() while stack: ans+=stack.pop() return ans
using-a-robot-to-print-the-lexicographically-smallest-string
[Python3] | Using Stack | O(n)
swapnilsingh421
0
71
using a robot to print the lexicographically smallest string
2,434
0.381
Medium
33,307
https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/discuss/2681939/Python-3Stack-(hint-solution)-with-comments
class Solution: def robotWithString(self, s: str) -> str: # last index for each letter last_idx = {} for i, x in enumerate(s): last_idx[x] = i ans = "" t = [] # current smallest letter q = sorted(set(s)) cur = q.pop(0) for i, x in enumerate(s): # if smallest letter then write down to paper if x == cur: ans += x # if this is the last occurance if i == last_idx[x]: # look for next smallest letter in the remaining string while q and last_idx[q[0]] < i: q.pop(0) # if all letter were in t then return the answer if not q: return ans + "".join(t[::-1]) cur = q.pop(0) # look for any smaller letter occurred before and add to the answer while t and t[-1] <= cur: ans += t.pop() # record previous occurance of letter else: t += [x] return ans + "".join(t[::-1])
using-a-robot-to-print-the-lexicographically-smallest-string
[Python 3]Stack (hint solution) with comments
chestnut890123
0
80
using a robot to print the lexicographically smallest string
2,434
0.381
Medium
33,308
https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/discuss/2681285/python3-Iteration-sol-for-reference
class Solution: def robotWithString(self, s: str) -> str: idx = 0 robot = [] paper = [] minchars = [] dp = list(s) for i in range(len(s)-2, -1, -1): dp[i] = min(dp[i], dp[i+1]) for i in range(len(s)): if s[i] == dp[i]: minchars.append((i, s[i])) for c in s: if idx < len(minchars) and minchars[idx][1] == c: while robot and c >= robot[-1]: paper.append(robot.pop()) paper.append(c) idx += 1 else: if idx < len(minchars): nmc = minchars[idx][1] while robot and robot[-1] <= nmc and c >= robot[-1]: paper.append(robot.pop()) robot.append(c) return "".join(paper + robot[::-1])
using-a-robot-to-print-the-lexicographically-smallest-string
[python3] Iteration sol for reference
vadhri_venkat
0
12
using a robot to print the lexicographically smallest string
2,434
0.381
Medium
33,309
https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/discuss/2680695/greedy-approach-or-stack-solution
class Solution: def robotWithString(self, s: str) -> str: #count of each albhabet hashmap=[0]*26 for i in range(len(s)): temp=ord(s[i])-ord('a') hashmap[temp]+=1 #i pointing to array ,j pointing to string res="" j=0 i=0 temp=[] while(i<26): val=chr(ord('a')+i) #add each albhabet to stack,decrease the counter of each albhabet till hashmap[i]==0 while(hashmap[i]!=0): if s[j]==val: res+=val hashmap[i]-=1 else: temp.append(s[j]) hashmap[ord(s[j])-ord('a')]-=1 j+=1 i+=1 #i pointing to next non zero count albhabet while(i<26 and hashmap[i]==0): i+=1 #check whether top of stack is less than albhabet corresponding to i,if yes pop and add to answer while(temp and j<len(s) and i<26 and ord(temp[-1])<=i+ord('a')): res+=temp.pop() while(temp): res+=temp.pop() return(res)
using-a-robot-to-print-the-lexicographically-smallest-string
greedy approach | stack solution
sundram_somnath
0
61
using a robot to print the lexicographically smallest string
2,434
0.381
Medium
33,310
https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/discuss/2679716/Python-Solve-by-tracking-what-the-next-minimum-character-is
class Solution: def robotWithString(self, s: str) -> str: res = "" next_min = [""] * len(s) next_min[-1] = s[-1] for i in range(len(s)-2, -1, -1): next_min[i] = min(next_min[i+1], s[i]) i = 0 t = [] res = "" while i < len(s): t.append(s[i]) j = i + 1 if s[i] == next_min[i]: res += t.pop() if j < len(s): while t and t[-1] <= next_min[j]: res += t.pop() else: while t: res += t.pop() i += 1 return res
using-a-robot-to-print-the-lexicographically-smallest-string
[Python] Solve by tracking what the next minimum character is
sharma_shubham
0
12
using a robot to print the lexicographically smallest string
2,434
0.381
Medium
33,311
https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/discuss/2678999/Python
class Solution: def robotWithString(self, s: str) -> str: prf = [] mi = 'z' for i in range(len(s) - 1, -1, -1): if s[i] < mi: mi = s[i] prf.append(mi) prf = prf[::-1] res = [] left = [s[0]] right = 1 while right < len(s): if not left or prf[right] < left[-1]: left.append(s[right]) right += 1 else: res.append(left.pop()) while left: res.append(left.pop()) return ''.join(res)
using-a-robot-to-print-the-lexicographically-smallest-string
Python
JSTM2022
0
33
using a robot to print the lexicographically smallest string
2,434
0.381
Medium
33,312
https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/discuss/2678978/Python3-Dictionaries-and-Pointers
class Solution: def robotWithString(self, s: str) -> str: n=len(s) d={} dIndex={} for i in range(n): ch=s[i] if ch not in d: d[ch]=[] dIndex[ch]=0 d[ch].append(i) t=['']*n answ=[] sIndex=0 tIndex=-1 lex=sorted(d.keys()) for ch in lex: while 0<=tIndex and t[tIndex]<=ch: answ.append(t[tIndex]) tIndex-=1 while dIndex[ch]<len(d[ch]): chIndex=d[ch][dIndex[ch]] dIndex[ch]+=1 while n>sIndex<chIndex: dIndex[s[sIndex]]+=1 tIndex+=1 t[tIndex]=s[sIndex] sIndex+=1 answ.append(ch) sIndex+=1 return ''.join(answ)
using-a-robot-to-print-the-lexicographically-smallest-string
Python3, Dictionaries and Pointers
Silvia42
0
26
using a robot to print the lexicographically smallest string
2,434
0.381
Medium
33,313
https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/discuss/2678903/Python-based-on-intuition
class Solution: def robotWithString(self, s: str) -> str: t= [] res = [] #counter would tell if there is any smaller character on the right counter = [0]*26 for char in s: counter[ord(char)-97] += 1 for idx, char in enumerate(s): t.append(char) counter[ord(char)-97] -= 1 while len(t) != 0: value = ord(t[-1])-97 ifc = False for i in range(value): if counter[i] > 0: ifc = True break if ifc: break res.append(t[-1]) t.pop() return "".join(res)
using-a-robot-to-print-the-lexicographically-smallest-string
Python based on intuition
Yihang--
0
75
using a robot to print the lexicographically smallest string
2,434
0.381
Medium
33,314
https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/discuss/2702890/Python-or-3d-dynamic-programming-approach-or-O(m*n*k)
class Solution: def numberOfPaths(self, grid: List[List[int]], k: int) -> int: dp = [[[0 for i in range(k)] for _ in range(len(grid[0]))] for _ in range(len(grid))] rem = grid[0][0] % k dp[0][0][rem] = 1 for i in range(1, len(grid[0])): dp[0][i][(rem + grid[0][i]) % k] = 1 rem = (rem + grid[0][i]) % k rem = grid[0][0] % k for j in range(1, len(grid)): dp[j][0][(rem + grid[j][0]) % k] = 1 rem = (rem + grid[j][0]) % k for i in range(1, len(grid)): for j in range(1, len(grid[0])): for rem in range(k): dp[i][j][(rem + grid[i][j]) % k] = dp[i - 1][j][rem] + dp[i][j - 1][rem] return dp[-1][-1][0] % (10**9 + 7)
paths-in-matrix-whose-sum-is-divisible-by-k
Python | 3d dynamic programming approach | O(m*n*k)
LordVader1
1
16
paths in matrix whose sum is divisible by k
2,435
0.41
Hard
33,315
https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/discuss/2825474/Faster-than-98
class Solution: def numberOfPaths(self, grid: List[List[int]], k: int) -> int: p=10**9+7 m=len(grid) n=len(grid[0]) lst=[([0]*k if j else [1]+[0]*(k-1)) for j in range(n)] for i in range(m): gr=grid[i] klst=[0]*k for j in range(n): g=gr[j] l=lst[j] klst=[(klst[(r-g)%k]+l[(r-g)%k])%p for r in range(k)] lst[j]=klst return lst[-1][0]
paths-in-matrix-whose-sum-is-divisible-by-k
Faster than 98%
mbeceanu
0
3
paths in matrix whose sum is divisible by k
2,435
0.41
Hard
33,316
https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/discuss/2699332/Python-3-or-dp-or-O(mnk)O(nk)
class Solution: MOD = 1000000007 def numberOfPaths(self, grid: List[List[int]], k: int) -> int: m, n = len(grid), len(grid[0]) prev = [[0] * k for _ in range(n + 1)] for i in range(m - 1, -1, -1): cur = [[0] * k for _ in range(n + 1)] for j in range(n - 1, -1, -1): for s in range(k): new = (s + grid[i][j]) % k if i == m - 1 and j == n - 1: cur[j][s] = int(new == 0) else: cur[j][s] = (prev[j][new] + cur[j + 1][new]) % Solution.MOD prev = cur return prev[0][0]
paths-in-matrix-whose-sum-is-divisible-by-k
Python 3 | dp | O(mnk)/O(nk)
dereky4
0
9
paths in matrix whose sum is divisible by k
2,435
0.41
Hard
33,317
https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/discuss/2693760/Python-or-Bottom-up-DP
class Solution: def numberOfPaths(self, grid: List[List[int]], k: int) -> int: m = len(grid) n = len(grid[0]) P = 10**9 + 7 if k == 1: return self.binom(n + m - 2, n - 1, P) dp = [[[0 for r in range(k)] for _ in range(n)] for _ in range(m)] dp[0][0][grid[0][0] % k] = 1 for j in range(1,n): for r in range(k): r_p = (r - grid[0][j] % k) % k dp[0][j][r] = dp[0][j-1][r_p] for i in range(1,m): for r in range(k): r_p = (r - grid[i][0] % k) % k dp[i][0][r] = dp[i-1][0][r_p] for i in range(1,m): for j in range(1,n): for r in range(k): r_p = (r - grid[i][j] % k) % k dp[i][j][r] = (dp[i-1][j][r_p] + dp[i][j-1][r_p]) % P return dp[m-1][n-1][0] # Compute the binomial coefficient n C r modulo p, where # p is prime. def binom(self, n, r, p): prod = 1 for i in range(r): prod = (prod * (n - i) * self.inv(i + 1, p)) % p return prod # Use the Euclidean algorithm to find the inverse of x (mod p). def inv(self, x, p): return self.bezout(x, p)[0] % p def bezout(self, a, b): if b == 0: return (1, 0) u, v = self.bezout (b, a % b) return (v, u - (a // b) * v)
paths-in-matrix-whose-sum-is-divisible-by-k
Python | Bottom-up DP
on_danse_encore_on_rit_encore
0
15
paths in matrix whose sum is divisible by k
2,435
0.41
Hard
33,318
https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/discuss/2688549/Python-DP-solution-with-visual-explanation
class Solution: def numberOfPaths(self, grid: List[List[int]], k: int) -> int: R, C = len(grid), len(grid[0]) dp = defaultdict(lambda: defaultdict(lambda: 0)) dp[(0,0)][grid[0][0]%k] = 1 for i in range(R): for j in range(C): if i > 0: for n, val in dp[(i-1, j)].items(): dp[(i, j)][(n+grid[i][j])%k] += val if j > 0: for n, val in dp[(i, j-1)].items(): dp[(i, j)][(n+grid[i][j])%k] += val return dp[(R-1, C-1)][0] % (10**9 + 7)
paths-in-matrix-whose-sum-is-divisible-by-k
Python DP solution with visual explanation
kaichamp101
0
24
paths in matrix whose sum is divisible by k
2,435
0.41
Hard
33,319
https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/discuss/2687550/Simple-O(nmk)-DP-in-Python
class Solution: def numberOfPaths(self, grid: List[List[int]], k: int) -> int: n, m = len(grid), len(grid[0]) dp = [[[0] * k for _ in range(m)] for _ in range(n)] dp[0][0][grid[0][0] % k] = 1 for i in range(n): for j in range(m): for r in range(k): if i > 0: dp[i][j][r] += dp[i-1][j][(r-grid[i][j]) % k] if j > 0: dp[i][j][r] += dp[i][j-1][(r-grid[i][j]) % k] dp[i][j][r] %= 1000000007 return dp[n-1][m-1][0]
paths-in-matrix-whose-sum-is-divisible-by-k
Simple O(nmk) DP in Python
metaphysicalist
0
36
paths in matrix whose sum is divisible by k
2,435
0.41
Hard
33,320
https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/discuss/2683672/Python3-O(MN)-Dynamic-Programming-Solution
class Solution: def numberOfPaths(self, grid: List[List[int]], k: int) -> int: m, n = len(grid), len(grid[0]) remainder = [[defaultdict(int) for _ in range(n)] for _ in range(m)] for i in range(m): num = grid[i][0] % k if i == 0: remainder[i][0][num] = 1 else: for key, value in remainder[i-1][0].items(): new_val = (key + num) % k remainder[i][0][new_val] += value for j in range(1,n): num = grid[0][j] % k for key,value in remainder[0][j-1].items(): new_val = (key + num) % k remainder[0][j][new_val] += value for i in range(1, m): for j in range(1, n): num = grid[i][j] % k for key,value in remainder[i-1][j].items(): new_val = (key + num) % k remainder[i][j][new_val] += value for key,value in remainder[i][j-1].items(): new_val = (key + num) % k remainder[i][j][new_val] += value return remainder[-1][-1][0] % (10**9 + 7)
paths-in-matrix-whose-sum-is-divisible-by-k
Python3 O(MN) Dynamic Programming Solution
xxHRxx
0
59
paths in matrix whose sum is divisible by k
2,435
0.41
Hard
33,321
https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/discuss/2682892/Python3-or-Tabular-DP
class Solution: def numberOfPaths(self, grid: List[List[int]], k: int) -> int: n,m=len(grid),len(grid[0]) dp=[[[0 for i in range(k)] for i in range(m)] for j in range(n)] dp[0][0][grid[0][0]%k]=1 for i in range(1,m): for j in range(k): curr=(j+grid[0][i])%k dp[0][i][curr]+=dp[0][i-1][j] for i in range(1,n): for j in range(k): curr=(j+grid[i][0])%k dp[i][0][curr]+=dp[i-1][0][j] for i in range(1,n): for j in range(1,m): for v in range(k): curr=(v+grid[i][j])%k dp[i][j][curr]+=dp[i-1][j][v] curr=(v+grid[i][j])%k dp[i][j][curr]+=dp[i][j-1][v] return dp[n-1][m-1][0]%1000000007
paths-in-matrix-whose-sum-is-divisible-by-k
[Python3] | Tabular DP
swapnilsingh421
0
34
paths in matrix whose sum is divisible by k
2,435
0.41
Hard
33,322
https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/discuss/2682398/python3-DP-sol-for-reference
class Solution: def numberOfPaths(self, grid: List[List[int]], k: int) -> int: M = len(grid) N = len(grid[0]) MOD = 10**9+7 dp = defaultdict(lambda: defaultdict(lambda: defaultdict(int))) dp[0][0][grid[0][0]%k] = 1 for x in range(M): for y in range(N): for i in dp[x][y]: if x+1 < M: key = (i+grid[x+1][y])%k dp[x+1][y][key] += dp[x][y][i] if y+1 < N: key = (i+grid[x][y+1])%k dp[x][y+1][key] += dp[x][y][i] return dp[M-1][N-1][0]%MOD
paths-in-matrix-whose-sum-is-divisible-by-k
[python3] DP sol for reference
vadhri_venkat
0
14
paths in matrix whose sum is divisible by k
2,435
0.41
Hard
33,323
https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/discuss/2682293/Python-is-getting-TLE-but-C%2B%2B-is-getting-AC-with-same-solution.
class Solution: def numberOfPaths(self, grid: List[List[int]], k: int) -> int: n, m = len(grid), len(grid[0]) dp = [[[0] * (k + 1) for _ in range(m + 1)] for _ in range(n + 1)] dp[0][0][grid[0][0] % k] = 1 mod = 10 ** 9 + 7 for x in range(0, n): for y in range(0, m): for q in range(k): if x + 1 < n: dp[x + 1][y][(q + grid[x + 1][y]) % k] += dp[x][y][q] dp[x + 1][y][(q + grid[x + 1][y]) % k] %= mod if y + 1 < m: dp[x][y + 1][(q + grid[x][y + 1]) % k] += dp[x][y][q] dp[x][y + 1][(q + grid[x][y + 1]) % k] %= mod return dp[n - 1][m - 1][0]
paths-in-matrix-whose-sum-is-divisible-by-k
Python is getting TLE but C++ is getting AC with same solution.
bayarkhuu
0
13
paths in matrix whose sum is divisible by k
2,435
0.41
Hard
33,324
https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/discuss/2682286/Python-is-getting-TLE-but-C%2B%2B-is-getting-AC-with-same-solution.
class Solution: def numberOfPaths(self, grid: List[List[int]], k: int) -> int: n, m = len(grid), len(grid[0]) dp = [[[0] * (k + 1) for _ in range(m + 1)] for _ in range(n + 1)] dp[0][0][grid[0][0] % k] = 1 mod = 10 ** 9 + 7 for x in range(0, n): for y in range(0, m): for q in range(k): if x + 1 < n: dp[x + 1][y][(q + grid[x + 1][y]) % k] += dp[x][y][q] dp[x + 1][y][(q + grid[x + 1][y]) % k] %= mod if y + 1 < m: dp[x][y + 1][(q + grid[x][y + 1]) % k] += dp[x][y][q] dp[x][y + 1][(q + grid[x][y + 1]) % k] %= mod return dp[n - 1][m - 1][0]
paths-in-matrix-whose-sum-is-divisible-by-k
Python is getting TLE but C++ is getting AC with same solution.
bayarkhuu
0
10
paths in matrix whose sum is divisible by k
2,435
0.41
Hard
33,325
https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/discuss/2681474/Python-Bottom-Up-3D-Dp-oror-Time%3A-6876-ms-Space%3A-146.9-MB
class Solution: def numberOfPaths(self, grid: List[List[int]], k: int) -> int: # TLE # @cache # def valid(i,j): # return 1 if(i>=0 and i<n and j>=0 and j<m) else 0 # @cache # def solve(i,j,s): # if(valid(i,j)): # return solve(i+1,j,(s+grid[i][j])%k)+ solve(i,j+1,(s+grid[i][j])%k) # else: # return 1 if(s==0 and ((i==n-1 and j==m) or (i==n and j==m-1))) else 0 # return (solve(0,0,0)//2)%(int(1e9+7)) #Accepted n=len(grid) m=len(grid[0]) dp=[[[0 for i in range(k+1)] for j in range(m+1)] for p in range(n+1)] dp[n-1][m][0]=1 dp[n][m-1][0]=1 for i in range(n-1,-1,-1): for j in range(m-1,-1,-1): for p in range(k,-1,-1): dp[i][j][p]=dp[i+1][j][(p+grid[i][j])%k]+dp[i][j+1][(p+grid[i][j])%k] return (dp[0][0][0]//2)%int(1e9+7)
paths-in-matrix-whose-sum-is-divisible-by-k
Python Bottom-Up 3D-Dp || Time: 6876 ms , Space: 146.9 MB
koder_786
0
18
paths in matrix whose sum is divisible by k
2,435
0.41
Hard
33,326
https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/discuss/2679590/Python3-Dynamic-Programming
class Solution: def numberOfPaths(self, grid: List[List[int]], k: int) -> int: # m: number of rows; n: number of columns m, n = len(grid), len(grid[0]) # cur: result of current row; pre: result of previous row # we initialize the current row as it contains one cell (-1, 0), # and this cell has one pair of path_sum_modulo_k: frequency (0: 1) cur, pre = {(-1,0):{0:1}}, None # loop over the rows from row index 0 to m-1 for i in range(m): # reinitialize current row and set the result from previous row as pre cur, pre = defaultdict(dict), cur # loop over the columns from column index 0 to n-1 for j in range(n): # if result of cell (i-1, j) exists, merge it into the result of current cell (i, j) if (i-1, j) in pre: # loop over the pairs (path_sum_modulo_k: frequency) stored in the result of cell (i-1, j) for (s, f) in pre[(i-1, j)].items(): # add current cell value to the path_sum_modulo_k cs = (s+grid[i][j])%k # update the result of current cell if cs not in cur[(i, j)]: cur[(i, j)][cs] = f else: cur[(i, j)][cs] += f # if result of cell (i, j-1) exists, merge it into the result of current cell (i, j) if (i, j-1) in cur: for (s, f) in cur[(i, j-1)].items(): cs = (s+grid[i][j])%k if cs not in cur[(i, j)]: cur[(i, j)][cs] = f else: cur[(i, j)][cs] += f # return the frequency of path sum divisible by k if it exists, otherwise return 0 return cur[(m-1, n-1)][0] % (10**9+7) if 0 in cur[(m-1, n-1)] else 0
paths-in-matrix-whose-sum-is-divisible-by-k
[Python3] Dynamic Programming
teyuanliu
0
39
paths in matrix whose sum is divisible by k
2,435
0.41
Hard
33,327
https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/discuss/2679545/11-lines-3d-dp
class Solution: def numberOfPaths(self, grid: List[List[int]], k: int) -> int: N = 10 ** 9 + 7 m, n = len(grid), len(grid[0]) dp = [[[0] * k for i in range(n+1)] for j in range(m+1)] dp[1][1][grid[0][0] % k] = 1 for i in range(m): for j in range(n): for t in range(k): dp[i+1][j+1][(t + grid[i][j]) % k] += (dp[i+1][j][t] + dp[i][j+1][t]) % N return dp[m][n][0]
paths-in-matrix-whose-sum-is-divisible-by-k
11 lines 3d dp
A_Pinterest_Employee
0
18
paths in matrix whose sum is divisible by k
2,435
0.41
Hard
33,328
https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/discuss/2679309/Python-Answer-DP-using-Double-Array-of-Dictionary
class Solution: def numberOfPaths(self, grid: List[List[int]], k: int) -> int: m = len(grid) n = len(grid[0]) mod = 10**9 + 7 k = k tmp = [[defaultdict(int) for i in range(len(grid[0]))] for j in range(len(grid))] tmp[0][0][grid[0][0] %k] = 1 for i in range(1,len(grid)): s = tmp[i-1][0].keys() tmp[i][0][(list(s)[0] +grid[i][0]) %k] =1 for j in range(1,len(grid[0])): s = tmp[0][j-1].keys() tmp[0][j][(list(s)[0] + grid[0][j])%k] = 1 for i in range(1,len(grid)): for j in range(1,len(grid[0])): for l in tmp[i-1][j].keys(): s1 = tmp[i-1][j][l] #+ grid[i][j] tmp[i][j][(l+grid[i][j])%k] += s1 % mod for l in tmp[i][j-1].keys(): s1 = tmp[i][j-1][l] #+ grid[i][j] tmp[i][j][(l+grid[i][j])%k] += s1 % mod return tmp[m-1][n-1][0] % mod
paths-in-matrix-whose-sum-is-divisible-by-k
[Python Answer🤫🐍🐍🐍] DP using Double Array of Dictionary
xmky
0
36
paths in matrix whose sum is divisible by k
2,435
0.41
Hard
33,329
https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/discuss/2679007/Python-DFS-%2B-Memoization
class Solution: def numberOfPaths(self, grid: List[List[int]], k: int) -> int: import copy hm = defaultdict(list) m, n = len(grid), len(grid[0]) def dfs(r, c): if r >= len(grid) or c >= len(grid[0]): return [] if r == m - 1 and c == n - 1: hm[(r, c)] = {grid[r][c] : 1} return if (r, c) not in hm: dfs(r + 1, c) dfs(r, c + 1) it = defaultdict(int) if (r + 1, c) in hm: for i in hm[(r + 1, c)]: it[(grid[r][c] + i) % k] += hm[(r + 1, c)][i] if (r, c + 1) in hm: for i in hm[(r, c + 1)]: it[(grid[r][c] + i) % k] += hm[(r, c + 1)][i] hm[(r, c)] = it return dfs(0, 0) res = 0 for i in hm[(0, 0)]: if i % k == 0: res += hm[(0, 0)][i] res %= (10 ** 9 + 7) return res
paths-in-matrix-whose-sum-is-divisible-by-k
Python DFS + Memoization
JSTM2022
0
89
paths in matrix whose sum is divisible by k
2,435
0.41
Hard
33,330
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2706741/Structural-pattern-matching
class Solution: def countTime(self, t: str) -> int: mm = (6 if t[3] == '?' else 1) * (10 if t[4] == '?' else 1) match [t[0], t[1]]: case ('?', '?'): return mm * 24 case ('?', ('0' | '1' | '2' | '3')): return mm * 3 case ('?', _): return mm * 2 case (('0' | '1'), '?'): return mm * 10 case (_, '?'): return mm * 4 return mm
number-of-valid-clock-times
Structural pattern matching
votrubac
24
806
number of valid clock times
2,437
0.42
Easy
33,331
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2706665/Understandable-If-Else-python-solution
class Solution: def countTime(self, time: str) -> int: res = 1 # split hour and minute digits h1, h2, _ , m1, m2 = time if h1 == "?" and h2 == "?": res*=24 elif h1 == "?": if int(h2) >=4: res*=2 else: res*=3 elif h2 == "?": if int(h1) <= 1: res*=10 elif h1 == "2": res*=4 if m1 == "?" and m2 == "?": res*=60 elif m1 == "?": res*=6 elif m2 == "?": res*=10 return res
number-of-valid-clock-times
Understandable If-Else python solution
namanxk
5
179
number of valid clock times
2,437
0.42
Easy
33,332
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2706726/Python-No-math-simple-pattern-check-O(1)-Clean-and-Concise
class Solution: def countTime(self, time: str) -> int: def getString2Chars(value): if value < 10: return "0" + str(value) return str(value) def isMatching(clock, pattern): s = getString2Chars(clock) if pattern[0] != "?" and s[0] != pattern[0] or pattern[1] != "?" and s[1] != pattern[1]: return False return True hPattern, mPattern = time.split(":") ans = 0 hhCnt, mmCnt = 0, 0 for hh in range(24): if isMatching(hh, hPattern): hhCnt += 1 for mm in range(60): if isMatching(mm, mPattern): mmCnt += 1 return hhCnt * mmCnt
number-of-valid-clock-times
[Python] No math, simple pattern check - O(1) - Clean & Concise
hiepit
2
177
number of valid clock times
2,437
0.42
Easy
33,333
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2799275/JAVAC%2B%2BPY-100-or-0-MS-or-faster-or-simple-or-TIME-and-SPACE-O(1)
class Solution { public int countTime(String time) { if(time.equals("??:??")) return 1440; int ans=1; if(time.charAt(0)=='?' &amp;&amp; time.charAt(1)=='?') ans*=24; else if(time.charAt(0)=='?') ans*=(time.charAt(1)-'0'>=4)?2:3; else if(time.charAt(1)=='?') ans *=(time.charAt(0)-'0'>=2)?4:10; if(time.charAt(3)=='?') ans *=6; if(time.charAt(4)=='?') ans *=10; return ans; } } CPP: int countTime(string time) { if(time=="??:??") return 1440; int ans=1; if(time[0]=='?' &amp;&amp; time[1]=='?') ans*=24; else if(time[0]=='?') ans*=(time[1]-'0'>=4)?2:3; else if(time[1]=='?') ans *=(time[0]-'0'>=2)?4:10; if(time[3]=='?') ans *=6; if(time[4]=='?') ans *=10; return ans; } PY : def countTime(self, time: str) -> int: if(time=="??:??"): return 1440; ans=1; if(time[0]=='?' and time[1]=='?'): ans=ans*24; elif (time[0]=='?'): if(ord(time[1])-ord('0')>=4): ans = ans*2; else: ans=ans*3; elif (time[1]=='?'): if(ord(time[0])-ord('0')>=2): ans = ans*4; else:ans= ans*10; if(time[3]=='?'): ans = ans * 6; if(time[4]=='?'): ans = ans * 10; return ans;CPP
number-of-valid-clock-times
✅⬆️ [JAVA/C++/PY] 100 % | 0 MS | faster | simple | TIME & SPACE O(1)
ManojKumarPatnaik
0
2
number of valid clock times
2,437
0.42
Easy
33,334
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2772366/Python-with-easy-to-understand-hours-minutes-matching
class Solution: def countTime(self, time: str) -> int: # hours if time[:2] == "??": combinations = 24 elif time[1] == "?": if time [0] in "01": combinations = 10 else: combinations = 4 elif time[0] == "?" and time[1] in "0123": combinations = 3 elif time[0] == "?" and time[1] in "456789": combinations = 2 else: combinations = 1 # minutes if time[3] == "?": combinations *= 6 if time[4] == "?": combinations *= 10 return combinations
number-of-valid-clock-times
Python with easy to understand hours / minutes matching
mjavka
0
4
number of valid clock times
2,437
0.42
Easy
33,335
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2749145/Two-if-..-elif-94-speed
class Solution: def countTime(self, time: str) -> int: ans = 1 if time[0] == time[1] == "?": ans *= 24 elif time[0] == "?": if time[1] < "4": ans *= 3 else: ans *= 2 elif time[1] == "?": if time[0] < "2": ans *= 10 else: ans *= 4 if time[3] == time[4] == "?": ans *= 60 elif time[3] == "?": ans *= 6 elif time[4] == "?": ans *= 10 return ans
number-of-valid-clock-times
Two if .. elif, 94% speed
EvgenySH
0
5
number of valid clock times
2,437
0.42
Easy
33,336
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2732777/Faster-than-98-of-python-submissions
class Solution: def countTime(self, time: str) -> int: l = time[:2] r = time[-2:] if time == "??:??": return 1440 if l == "??": poss = 24 else: # l_l (left_left = Ones) l_r(left_right = Tens ) l_l = 0 if l[0].isnumeric() else 3 if int(l[1]) <= 3 else 2 l_r = 0 if l[1].isnumeric() else 10 if int(l[0]) < 2 else 4 poss = 1 if l_r + l_l == 0 else l_r + l_l #for the right side xx:{??} if r == "??": poss2 = 60 else: r_l = 0 if r[0].isnumeric() else 6 r_r = 0 if r[1].isnumeric() else 10 poss2 = 1 if r_l + r_r == 0 else r_l + r_r return poss * poss2
number-of-valid-clock-times
Faster than 98% of python submissions
ayoubprog61
0
4
number of valid clock times
2,437
0.42
Easy
33,337
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2730360/Easy-understanding-python-solution-with-explanation
class Solution: def countTime(self, t: str) -> int: # ?0: 00 # 0?:00 # ??:00 # 00: 0? # 00:?0 # 00:?? a, b, c, d = t[0], t[1], t[3], t[4] left, right = 0, 0 if a == "?" and b == "?": left = 24 elif a == "?": if int(b) < 4: left = 3 else: left = 2 elif b == "?": if int(a) < 2: left = 10 else: left = 4 else: left = 1 if c == "?" and d == "?": right = 60 elif c == "?": right = 6 elif d == "?": right = 10 else: right = 1 return left * right
number-of-valid-clock-times
Easy understanding python solution with explanation
jackson-cmd
0
1
number of valid clock times
2,437
0.42
Easy
33,338
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2712868/Python-or-Regex-or-7-lines
class Solution: def countTime(self, time: str) -> int: time, ans = time.replace('?', '.'), 0 for i in range(60 * 24): hours = i // 60 mins = i - 60 * hours candidate = f'{hours:02}:{mins:02}' ans += re.match(time, candidate) is not None return ans
number-of-valid-clock-times
Python | Regex | 7 lines
leeteatsleep
0
10
number of valid clock times
2,437
0.42
Easy
33,339
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2709229/Faster-than-100-or-Easy-to-Understand-or-Python
class Solution(object): def countTime(self, time): h, m = 0, 0 if time[0] == '?' and time[1] == '?': h = 24 elif time[0] == '?': if int(time[1]) > 3: h = 2 else: h = 3 elif time[1] == '?': if int(time[0]) == 2: h = 4 else: h = 10 else: h = 1 if time[3] == '?' and time[4] == '?': m = 60 elif time[3] == '?': m = 6 elif time[4] == '?': m = 10 else: m = 1 return h * m
number-of-valid-clock-times
Faster than 100% | Easy to Understand | Python
its_krish_here
0
6
number of valid clock times
2,437
0.42
Easy
33,340
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2708978/Python3-Brute-Force-(With-Recursion)
class Solution: def countTime(self, time: str) -> int: t = 0 def rec(x, r): nonlocal t if len(r) == 0: ps = x.split(':') if int(ps[0])<24 and int(ps[1])<60: t+=1 elif r[0]=='?': for i in range(10): rec(f"{x}{i}", r[1:]) else: rec(x+r[0], r[1:]) rec("", time) return t
number-of-valid-clock-times
Python3 Brute Force (With Recursion)
godshiva
0
4
number of valid clock times
2,437
0.42
Easy
33,341
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2708459/Python-oror-Simple-Greedy-Solution
class Solution: def countTime(self, time: str) -> int: count_h =1 count_m=1 if time[0] == '?': if time[1] == '?': # If both hours are '?' then we will have 24 combinations for hours count_h =24 elif time[1] >'3': count_h=2 else: count_h=3 elif time[1]=='?': if time[0] == '2': count_h=4 else: count_h=10 if time[3] == '?': if time[4] == '?': # If both minutes are '?' we have 60 combination for minutes count_m=60 else: count_m=6 elif time[4] == '?': count_m=10 return count_m*count_h # Return the product of hours count and minute count
number-of-valid-clock-times
Python || Simple Greedy Solution
Graviel77
0
4
number of valid clock times
2,437
0.42
Easy
33,342
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2707957/Easy-Python-or-Multiplication-or-Lots-of-ifs
class Solution: def countTime(self, time: str) -> int: hour, minute = time.split(':') ans = 1 if minute[0] == '?': ans *= 6 if minute[1] == '?': ans *= 10 if hour[0] == '?': if hour[1] == '?': ans *= 24 elif '4' <= hour[1] <= '9': ans *= 2 else: ans *= 3 elif hour[1] == '?': if hour[0] == '2': ans *= 4 else: ans *= 10 return ans
number-of-valid-clock-times
Easy Python | Multiplication | Lots of ifs
on_danse_encore_on_rit_encore
0
3
number of valid clock times
2,437
0.42
Easy
33,343
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2707298/Python3-if-else
class Solution: def countTime(self, time: str) -> int: ans = 1 if time[0:2] == "??": ans *= 24 elif time[0] == '?': ans *= 3 if time[1] < '4' else 2 elif time[1] == '?': ans *= 4 if time[0] == '2' else 10 if time[3] == '?': ans *= 6 if time[4] == '?': ans *= 10 return ans
number-of-valid-clock-times
[Python3] if-else
ye15
0
5
number of valid clock times
2,437
0.42
Easy
33,344
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2707007/Python-(Beats-100)-or-Mathematical-solution
class Solution: def countTime(self, time: str) -> int: hh, mm = time.split(':') mchoice, hchoice = 1, 1 if mm == '??': mchoice = 60 else: if mm[0] == '?': mchoice = 6 elif mm[1] == '?': mchoice = 10 if hh == '??': hchoice = 24 else: if hh[0] == '?': if int(hh[1]) < 4: hchoice = 3 else: hchoice = 2 elif hh[1] == '?': if hh[0] == '2': hchoice = 4 else: hchoice = 10 return mchoice * hchoice
number-of-valid-clock-times
Python (Beats 100%) | Mathematical solution
KevinJM17
0
4
number of valid clock times
2,437
0.42
Easy
33,345
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2706887/Python-Answer-Queue
class Solution: def countTime(self, time: str) -> int: pot = Deque([time]) while any(['?' in p for p in pot]): for _ in range(len(pot)): p = pot.popleft() if '?' in p: for i in range(0,10): q = p.replace('?', str(i), 1) #print(q) if '?' in q: pot.append(q) continue k = q.split(':') if 0 <= int(k[0]) <= 23 and 0 <= int(k[1]) <= 59: pot.append(q) else: pot.append(p) return len(pot)
number-of-valid-clock-times
[Python Answer🤫🐍🐍🐍] Queue
xmky
0
4
number of valid clock times
2,437
0.42
Easy
33,346
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2706824/Python-easy-simple-check-or-explain-with-comments
class Solution: def countTime(self, time: str) -> int: ans = 1 # for hour first index if time[0] == "?": # if hour second index if time[1] == "?": # we know we will get 24 times (0 to 23) value of counter ans *= 24 elif time[1] < "4": # if hour second index is less than 4 # then we can say we have only 3 options (0th, 10th, 20th) for hour first index # so we multiply by 3 ans *= 3 else: # else we have only 2 options (10th, 20th) # so we multiply by 2 ans *= 2 # for hour second index if time[1] == "?": # check if hour first digit is in 20th place if time[0] == "2": # if so then multiply with 4 (24 - 20 = 4) ans *= 4 elif time[0] < "2": # if this is less than 2 then we have only 1 hour # so for 1 hour we have (0 to 9) = 10 times ans *= 10 # for minute 1st index if time[3] == "?": # if the first index of minute is missing then we have only (0th to 60th) option => 6 times # so we multiply by 6 ans *= 6 # for minute 2nd index if time[4] == "?": # if the second index of minute is missing then we have only (0 to 9) option => 10 times # so we multiply by 10 ans *= 10 return ans
number-of-valid-clock-times
✅ Python easy simple check | explain with comments
sezanhaque
0
4
number of valid clock times
2,437
0.42
Easy
33,347
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2706709/Python-a-bunch-of-if-statements
class Solution: def countTime(self, time: str) -> int: hours = 1 if '?' not in time[:2]: pass else: if time[0] == '?': if time[1] == '?': hours = 24 elif time[1] < '4': hours = 3 else: hours = 2 elif time[0] == '2': hours = 4 else: hours = 10 minutes = 1 if time[-2] == '?': minutes *= 6 if time[-1] == '?': minutes *= 10 return hours * minutes
number-of-valid-clock-times
Python, a bunch of if statements
blue_sky5
0
5
number of valid clock times
2,437
0.42
Easy
33,348
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2706681/Python-solution-with-loop-and-string-comparison-only-53ms-runtime
class Solution: def countTime(self, time: str) -> int: h0, h1, m0, m1 = time[0], time[1], time[3], time[4] res = 0 for h in range(24): hour = "{:02d}".format(h) for m in range(60): minute = "{:02d}".format(m) if h0 != '?' and h0 != hour[0]: continue if h1 != '?' and h1 != hour[1]: continue if m0 != '?' and m0 != minute[0]: continue if m1 != '?' and m1 != minute[1]: continue res += 1 return res
number-of-valid-clock-times
Python solution with loop and string comparison only; 53ms runtime
llJll
0
5
number of valid clock times
2,437
0.42
Easy
33,349
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2706620/Python-or-Corner-cases-Pitfall
class Solution: def countTime(self, time: str) -> int: ans=1 h=time[0:2] m=time[3:] if h=="??": ans*=24 elif h[0]=="?": if int(h[1])>3: ans*=2 else: ans*=3 elif h[1]=="?": if int(h[0])<2: ans*=10 else: ans*=4 else: pass if m=="??": ans*=60 elif m[0]=="?": ans*=6 elif m[1]=="?": ans*=10 else: pass return ans
number-of-valid-clock-times
Python | Corner cases Pitfall
Prithiviraj1927
0
6
number of valid clock times
2,437
0.42
Easy
33,350
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2706605/Python3-Easy-Brute-Force-Solution
class Solution: def countTime(self, time: str) -> int: if time.count('?') == 4: return 1440 else: def helper(string): if string.count('?') == 0: return [string] else: index = string.index('?') temp_res = helper(string[index+1:]) res = [] for element in [str(i) for i in range(10)]: res += [string[:index] + element + x for x in temp_res] return res candidates = helper(time) res = 0 for element in candidates: hour, minute = int(element[:2]), int(element[3:]) if 0 <= hour <= 23 and 0 <= minute <= 59: res += 1 return res
number-of-valid-clock-times
Python3 Easy Brute Force Solution
xxHRxx
0
3
number of valid clock times
2,437
0.42
Easy
33,351
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2706547/Easy-to-understand
class Solution: def countTime(self, time: str) -> int: missing = set() for i in range(len(time)): if time[i] == "?": missing.add(i) hours_val, min_val = 1, 1 if 0 in missing and 1 in missing: hours_val = 24 elif 0 in missing: hours_val = 3 if int(time[1])<=3 else 2 elif 1 in missing: hours_val = 4 if int(time[0])==2 else 10 if 3 in missing and 4 in missing: min_val = 60 elif 3 in missing: min_val = 6 elif 4 in missing: min_val = 10 return hours_val*min_val
number-of-valid-clock-times
Easy to understand
np137
0
7
number of valid clock times
2,437
0.42
Easy
33,352
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2706529/Easy-Python3-Solution
class Solution: def countTime(self, time: str) -> int: a=time[0]+time[1] b=time[3]+time[4] qa=0 for c in a: if c=='?': qa+=1 aa=1 if qa==2: aa=24 elif qa==1: if a[1]=='?': if a[0]=='2': aa=4 else: aa=10 else: if int(a[1])<=3: aa=3 else: aa=2 qb=0 for d in b: if d=='?': qb+=1 ab=1 if qb==2: ab=60 elif qb==1: if b[1]=='?': ab=10 else: ab=6 return aa*ab
number-of-valid-clock-times
Easy [Python3] Solution
shreyasjain0912
0
6
number of valid clock times
2,437
0.42
Easy
33,353
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2706492/Python-O(1)-easy-solution
class Solution: def countTime(self, time: str) -> int: h,m = time.split(":") ans = 0 #00:00~23:59 #Hours tempH = 1 if h =="??": tempH = 24 elif h[0] == "?" and h[1]>"3":# "?4","?5","?6","?7" tempH = 2 #0,1 elif h[0] == "?" and h[1]<="3": tempH = 3 #0,1,2 elif h[1] == "?" and h[0] == "2": #"2?" tempH = 4 #0,1,2,3 elif h[1] == "?" and h[0] <"2": # "1?","0?" tempH = 10 #0,1,2,3,4,5,6,7,8,9 tempM = 1 #Minutes if m == "??": # tempM = 60 #0~60 min elif m[1] == "?": #"0?"~"5?" tempM = 10 #0,1,2,3,4,5,6,7,8,9 elif m[0] == "?": #"?0" tempM = 6 #0,1,2,3,4,5 # print(tempH,tempM) return tempH*tempM
number-of-valid-clock-times
Python O(1) easy solution
tryit163281
0
14
number of valid clock times
2,437
0.42
Easy
33,354
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2706485/Python3-O(1)-Space-and-O(1)-Time-Brute-Force
class Solution: def countTime(self, findings: str) -> int: ans = 1 if findings[-1]=='?' and findings[-2]=='?': ans = 60 elif findings[-1]=='?': ans = 10 elif findings[-2]=='?': ans = 6 if findings[0]=='?' and findings[1]=='?': ans=ans*24 elif findings[0]=='0'and findings[1]=='?': ans = ans*10 elif findings[0]=='1' and findings[1]=='?': ans = ans*10 elif findings[0]=='2' and findings[1]=='?': ans = ans*4 elif findings[0]=='?' and int(findings[1])<=3: ans = ans * 3 elif findings[0]=='?' and int(findings[1])>=4: ans = ans * 2 return ans
number-of-valid-clock-times
[Python3] O(1) Space and O(1) Time, Brute Force
chandu71202
0
5
number of valid clock times
2,437
0.42
Easy
33,355
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2706482/O(1)-O(1)-or-Bunch-of-If-Elif-statements-%3AD
class Solution: def countTime(self, time: str) -> int: answer = 1 n = 5 i = 0 while i != n: if time[i] != '?' and i == 0 and time[i+1] != '?': i = 3 elif time[i] == '?' and i == 0 and time[i+1] == '?': # ?3 - 00-23 choices answer *= 24 i = 3 elif time[i] == '?' and i == 0 and time[i+1] != '?' and int(time[i+1]) > 3: # ?4 - 0,1 choices answer *= 2 i = 3 elif time[i] == '?' and i == 0 and time[i+1] != '?' and int(time[i+1]) <= 3: # ?3 - 0,1,2 choices answer *= 3 i = 3 elif time[i] == '2' and i == 0 and time[i+1] == '?': # 2? - 0,1,2,3 choices answer *= 4 i = 3 elif time[i] != '?' and (time[i] == '0' or time[i] == '1') and i == 0 and time[i+1] == '?': # 1? 0? - 0-9 choices answer *= 10 i = 3 elif time[i] == '?' and i == 3 and time[i+1] != '?': # ?4 - 0-5 choices answer *= 6 i = 5 elif time[i] != '?' and i == 3 and time[i+1] == '?': # 2? - 0-9 choices answer *= 10 i = 5 elif time[i] == '?' and i == 3 and time[i+1] == '?': # ?3 - 00-59 choices answer *= 60 i = 5 elif time[i] != '?' and i== 3 and time[i+1] != '?': i = 5 if answer == 1: return 1 return answer ```
number-of-valid-clock-times
O(1) O(1) | Bunch of If-Elif statements :D
bighornsheep
0
10
number of valid clock times
2,437
0.42
Easy
33,356
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2706456/Python-Solution-with-Proof-and-Explanation-(For-Beginners)
class Solution: def countTime(self, time: str) -> int: a = time[0] b = time[1] c = time[3] d = time[4] result = 1 if a == "?" and b != "?": a1 = 3 if b <= '3' else 2 else: a1 = 1 if b =="?": if a <= "1": b1 = 10 elif a == "2": b1 = 4 elif a == "?": b1 = 24 else: b1 = 1 c1 = 6 if c == "?" else 1 d1 = 10 if d == "?" else 1 return a1 * b1 * c1 * d1
number-of-valid-clock-times
Python Solution with Proof and Explanation (For Beginners)
Jiganesh
0
41
number of valid clock times
2,437
0.42
Easy
33,357
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2706425/Python3-ugly-Brute-Force-is-easy
class Solution: def countTime(self, time: str) -> int: if '?' not in time: return 1 hh,mm=time.split(':') tH,th=hh tM,tm=mm answ=0 d='0123456789' for H in d: for h in d: for M in d: for m in d: Hh=int(H+h) Mm=int(M+m) if Hh<24 and Mm<60: if H!=tH!='?' or h!=th!='?' or M!=tM!='?' or m!=tm!='?': continue answ+=1 return answ
number-of-valid-clock-times
Python3, ugly Brute Force is easy
Silvia42
0
14
number of valid clock times
2,437
0.42
Easy
33,358
https://leetcode.com/problems/range-product-queries-of-powers/discuss/2706690/Python-or-Prefix-Product
class Solution: def productQueries(self, n: int, queries: List[List[int]]) -> List[int]: MOD = (10**9)+7 binary = bin(n)[2:] powers = [] result = [] for index, val in enumerate(binary[::-1]): if val == "1": powers.append(2**index) for index in range(1, len(powers)): powers[index] = powers[index] * powers[index - 1] for l,r in queries: if l == 0: result.append(powers[r]%MOD) else: result.append((powers[r]//powers[l-1])%MOD) return result
range-product-queries-of-powers
Python | Prefix Product
Dhanush_krish
8
320
range product queries of powers
2,438
0.384
Medium
33,359
https://leetcode.com/problems/range-product-queries-of-powers/discuss/2796984/fast-python-solution
class Solution: def productQueries(self, n: int, queries: List[List[int]]) -> List[int]: a=bin(n)[2:] # print(a) a=a[::-1] arr=[1] p=1 for i in range(len(a)): if(a[i]=="1"): p*=2**i arr.append(p) ans=[] print(arr) for q in queries: p=arr[q[1]+1]//arr[q[0]] ans.append(p%(10**9+7)) return ans
range-product-queries-of-powers
fast python solution
droj
4
42
range product queries of powers
2,438
0.384
Medium
33,360
https://leetcode.com/problems/range-product-queries-of-powers/discuss/2724547/Python3-Solution-or-Prefix-Sum-or-2-Line-Solution
class Solution: def productQueries(self, n, Q): A = list(accumulate([i for i in range(31) if n &amp; (1 << i)])) + [0] return [pow(2, A[r] - A[l - 1], 10 ** 9 + 7) for l, r in Q]
range-product-queries-of-powers
✔ Python3 Solution | Prefix Sum | 2 Line Solution
satyam2001
2
15
range product queries of powers
2,438
0.384
Medium
33,361
https://leetcode.com/problems/range-product-queries-of-powers/discuss/2784166/Python-Beats-97-Easy-to-understand-solution
class Solution: def productQueries(self, n: int, queries: List[List[int]]) -> List[int]: MOD = (10**9)+7 powers, res = [], [] binary_list = [int(i) for i in bin(n)[2:]] # convert n to binary for i, n in enumerate(binary_list[::-1]): # create powers list if n: powers.append(pow(2, i)) for i in range(1, len(powers)): # prefix product powers[i] = powers[i] * powers[i-1] for l, r in queries: if l == 0: res.append(powers[r] % MOD) else: res.append((powers[r] // powers[l-1]) % MOD) return res
range-product-queries-of-powers
[Python] Beats 97%, Easy to understand solution
hunarbatra
0
10
range product queries of powers
2,438
0.384
Medium
33,362
https://leetcode.com/problems/range-product-queries-of-powers/discuss/2710457/python3-Binary-search-and-prefix-product-sol-for-reference
class Solution: def productQueries(self, n: int, queries: List[List[int]]) -> List[int]: powersOf2 = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824] p = [] ans = [] MOD = 10**9+7 while n > 0: idx = bisect_left(powersOf2, n) if idx and powersOf2[idx] != n: idx -= 1 p.append(powersOf2[idx]) n -= powersOf2[idx] p = p[::-1] for i in range(1, len(p)): p[i] *= p[i-1] for l, r in queries: if l: ans.append((p[r]//p[l-1])%MOD) else: ans.append(p[r]%MOD) return ans
range-product-queries-of-powers
[python3] Binary search and prefix product sol for reference
vadhri_venkat
0
10
range product queries of powers
2,438
0.384
Medium
33,363
https://leetcode.com/problems/range-product-queries-of-powers/discuss/2709516/Python-solution
class Solution: def productQueries(self, n: int, queries: List[List[int]]) -> List[int]: powers = [] res = [] v = [] mod = (10 ** 9) + 7 while n > 0: v.append(n % 2) n = n // 2 for i in range(len(v)): if v[i] == 1: powers.append(2 ** i) for start, end in queries: prod = 1 for i in range(start, end + 1): prod *= powers[i] res.append(prod % mod) return res
range-product-queries-of-powers
Python solution
KevinJM17
0
5
range product queries of powers
2,438
0.384
Medium
33,364
https://leetcode.com/problems/range-product-queries-of-powers/discuss/2708896/Python-or-Prefix-sum-of-powers-or-Bit-manipulation
class Solution: def productQueries(self, n: int, queries: List[List[int]]) -> List[int]: p = 10**9 + 7 powers_prefix = [] mask, power = 1, 0 while mask <= n: if mask &amp; n: powers_prefix.append(power) mask *= 2 power += 1 # Calculate prefix sum of powers. for i in range(1, len(powers_prefix)): powers_prefix[i] += powers_prefix[i-1] ans = [1] * len(queries) for i, (l, r) in enumerate (queries): power = powers_prefix[r] if l > 0: power -= powers_prefix[l-1] ans[i] = (1 << power) % p return ans
range-product-queries-of-powers
Python | Prefix sum of powers | Bit manipulation
on_danse_encore_on_rit_encore
0
9
range product queries of powers
2,438
0.384
Medium
33,365
https://leetcode.com/problems/range-product-queries-of-powers/discuss/2707300/Python3-simulation
class Solution: def productQueries(self, n: int, queries: List[List[int]]) -> List[int]: powers = [] for i in range(30): if n &amp; 1<<i: powers.append(1<<i) ans = [] for lo, hi in queries: val = 1 for ii in range(lo, hi+1): val = (val * powers[ii]) % 1_000_000_007 ans.append(val) return ans
range-product-queries-of-powers
[Python3] simulation
ye15
0
10
range product queries of powers
2,438
0.384
Medium
33,366
https://leetcode.com/problems/range-product-queries-of-powers/discuss/2707190/Easy-python-solution
class Solution: def productQueries(self, n: int, queries: List[List[int]]) -> List[int]: //this will gives us the binary representation of the number binary_of_n = bin(n).replace("0b", "") result = [] powers = [] //Iterate through the binary number and when ever we //find 1 we add that to the power array. for i in range(len(binary_of_n)-1, -1, -1): if binary_of_n[len(binary_of_n)-1-i] == '1': powers.append(2**i) // now the power are in reverse order so sorting it powers.sort(); for query in queries: first = query[0] second = query[1] temp = 1 for i in range(first, second+1): temp = temp * powers[i] % (10**9 + 7) result.append(temp) return result
range-product-queries-of-powers
Easy python solution
Yuvraj-50
0
8
range product queries of powers
2,438
0.384
Medium
33,367
https://leetcode.com/problems/range-product-queries-of-powers/discuss/2707049/python-solution
class Solution: def productQueries(self, n: int, queries: List[List[int]]) -> List[int]: p,c=[],0 while n>0: if n&amp;1==1: p.append(pow(2,c)) c+=1 n=n>>1 ans=[] for i in queries: s=1 for j in range(i[0],i[1]+1): s*=p[j] ans.append(s%(pow(10,9)+7)) return ans
range-product-queries-of-powers
python solution
cheems_ds_side
0
6
range product queries of powers
2,438
0.384
Medium
33,368
https://leetcode.com/problems/range-product-queries-of-powers/discuss/2706859/Python3-Prefix-Sum-Solution
class Solution: def productQueries(self, n: int, queries: List[List[int]]) -> List[int]: bin_rep = bin(n)[2:] data = [t for t in range(0, len(bin_rep)) if bin_rep[-t-1] == '1'] start = 0 for i in range(len(data)): start += data[i] data[i] = start data.insert(0, 0) res = [] for start, end in queries: res.append((2**(data[end+1] - data[start])) % (10**9 + 7)) return res
range-product-queries-of-powers
Python3 Prefix Sum Solution
xxHRxx
0
5
range product queries of powers
2,438
0.384
Medium
33,369
https://leetcode.com/problems/range-product-queries-of-powers/discuss/2706747/Bit-manipulation-or-Python-3
class Solution: def productQueries(self, n: int, queries: List[List[int]]) -> List[int]: binary=bin(n).replace("0b",'')[::-1] powers=[] ans=[] powe=0 for i in range(len(binary)): if binary[i]=='1': powers.append(2**i) for i in range(1,len(powers)): powers[i]*=powers[i-1] for i,j in queries: if i==0: val=powers[j] else: val=powers[j]//powers[i-1] ans.append(val%1000000007) return ans
range-product-queries-of-powers
Bit manipulation | Python 3
RickSanchez101
0
6
range product queries of powers
2,438
0.384
Medium
33,370
https://leetcode.com/problems/range-product-queries-of-powers/discuss/2706564/Straightforward-PYTHON3-Solution
class Solution: def productQueries(self, n: int, queries: List[List[int]]) -> List[int]: mod=10**9+7 powers=[] a=bin(n)[2:] j=0 for i in range(len(a)-1,-1,-1): if a[i]=='1': powers.append(2**j) j+=1 answers=[] for a,b in queries: c=powers[a] for i in range(a+1,b+1): c*=powers[i] answers.append(c%mod) return answers
range-product-queries-of-powers
Straightforward [PYTHON3] Solution
shreyasjain0912
0
13
range product queries of powers
2,438
0.384
Medium
33,371
https://leetcode.com/problems/range-product-queries-of-powers/discuss/2706500/Python3-Straightforward
class Solution: def productQueries(self, n: int, queries: List[List[int]]) -> List[int]: big=10**9 + 7 nBinary=bin(n)[2:][::-1] powers=[2**x for x in range(len(nBinary)) if nBinary[x]=='1'] answ=[] for left,right in queries: q=1 for i in range(left,right+1): q*=powers[i] answ.append(q%big) return answ
range-product-queries-of-powers
Python3, Straightforward
Silvia42
0
13
range product queries of powers
2,438
0.384
Medium
33,372
https://leetcode.com/problems/range-product-queries-of-powers/discuss/2706429/Python3-Easy-to-understand
class Solution: def productQueries(self, n: int, queries: List[List[int]]) -> List[int]: MOD = 10**9+7 v = [] ans1 = [] while (n > 0): v.append(int(n % 2)) n = int(n / 2) for i in range(0, len(v)): if (v[i] == 1): ans1.append(2**i) ans = [] for i,j in queries: val = 1 for x in range(i,j+1): val*=ans1[x] ans.append(val%MOD) return ans
range-product-queries-of-powers
[Python3] Easy to understand
chandu71202
0
15
range product queries of powers
2,438
0.384
Medium
33,373
https://leetcode.com/problems/range-product-queries-of-powers/discuss/2706423/python-oror-easy-soln
class Solution: def productQueries(self, n: int, queries: List[List[int]]) -> List[int]: def min_arr(x): k = bin(x)[2:] k = k[::-1] ans = [] for i in range(0, len(k)): if (k[i] == '1'): ans.append(2**i) return ans nums = min_arr(n) prod = [1] for i in range(len(nums)): k = (prod[-1]*nums[i]) prod.append(k) res = [] for i in range(len(queries)): b = prod[queries[i][1]+1] a = prod[queries[i][0]] res.append((b//a)) res[i] = res[i]%(10**9 + 7) return res
range-product-queries-of-powers
python || easy soln
deepakchowdary866
0
14
range product queries of powers
2,438
0.384
Medium
33,374
https://leetcode.com/problems/minimize-maximum-of-array/discuss/2706472/Average
class Solution: def minimizeArrayValue(self, nums: List[int]) -> int: return max(ceil(n / (i + 1)) for i, n in enumerate(accumulate(nums)))
minimize-maximum-of-array
Average
votrubac
45
2,800
minimize maximum of array
2,439
0.331
Medium
33,375
https://leetcode.com/problems/minimize-maximum-of-array/discuss/2706976/Python-simple-solution-explained-(rolling-average)-O(n)
class Solution: def minimizeArrayValue(self, nums: List[int]) -> int: max_ = sum_ = 0 for i, num in enumerate(nums, start = 1): sum_ += num ave, modulo = divmod(sum_, i) if modulo: ave += 1 max_ = max(ave, max_) return max_ # end minimizeArrayValue()
minimize-maximum-of-array
Python simple solution explained (rolling average) O(n)
olzh06
10
216
minimize maximum of array
2,439
0.331
Medium
33,376
https://leetcode.com/problems/minimize-maximum-of-array/discuss/2836579/Easy-to-understand-O(n)-time-and-O(1)-space-solution-with-detailed-explanation.
class Solution: def minimizeArrayValue(self, nums: List[int]) -> int: maxim = nums[0] prefix_sum = nums[0] for idx in range(1, len(nums)): curr = nums[idx] prefix_sum += curr if curr > maxim: maxim = max(maxim, math.ceil(prefix_sum / (idx + 1))) return maxim
minimize-maximum-of-array
Easy to understand O(n) time and O(1) space solution with detailed explanation.
Henok2011
1
17
minimize maximum of array
2,439
0.331
Medium
33,377
https://leetcode.com/problems/minimize-maximum-of-array/discuss/2708695/Python3-Minecraft
class Solution: def minimizeArrayValue(self, nums: List[int]) -> int: maxx = nums[0] hole = 0 for i, x in enumerate(nums[1:], 1): if x - maxx > hole: extra_blocks = x - maxx - hole # extra blocks after filling hole cols = i + 1 if extra_blocks % cols == 0: maxx = maxx + extra_blocks // cols hole = 0 else: maxx = maxx + extra_blocks // cols + 1 hole = cols - extra_blocks % cols else: hole = hole + (maxx - x) return maxx
minimize-maximum-of-array
[Python3] Minecraft
rt500
1
24
minimize maximum of array
2,439
0.331
Medium
33,378
https://leetcode.com/problems/minimize-maximum-of-array/discuss/2706483/Short-Python3
class Solution: def minimizeArrayValue(self, nums: List[int]) -> int: mn = nums[0] nums = list(accumulate(nums)) for i, n in enumerate(nums): mn = max(mn, ceil(n/(i+1))) return mn
minimize-maximum-of-array
Short Python3
tglukhikh
1
51
minimize maximum of array
2,439
0.331
Medium
33,379
https://leetcode.com/problems/minimize-maximum-of-array/discuss/2706374/Python3-Binary-Search-on-the-Answer
class Solution: def minimizeArrayValue(self, nums: List[int]) -> int: start, end = 0, max(nums) while start + 1 < end: mid = (start + end) // 2 if self.check(nums, mid): end = mid else: start = mid if self.check(nums, start): return start else: return end def check(self, nums, k): n = len(nums) temp = 0 for i in range(n - 1, 0, -1): if temp + nums[i] > k: temp += nums[i] - k else: temp = 0 return False if temp + nums[0] > k else True
minimize-maximum-of-array
[Python3] Binary Search on the Answer
xil899
1
87
minimize maximum of array
2,439
0.331
Medium
33,380
https://leetcode.com/problems/minimize-maximum-of-array/discuss/2817979/Python-(Simple-DP)
class Solution: def minimizeArrayValue(self, nums): n = len(nums) dp = [0]*n running_sum, dp[0] = nums[0], nums[0] for i in range(1,n): running_sum += nums[i] dp[i] = max(dp[i-1],(running_sum+i)//(i+1)) return max(dp)
minimize-maximum-of-array
Python (Simple DP)
rnotappl
0
3
minimize maximum of array
2,439
0.331
Medium
33,381
https://leetcode.com/problems/minimize-maximum-of-array/discuss/2806905/Python3Monotonic-Stack-O(n)-with-explanation
class Solution: def minimizeArrayValue(self, nums: List[int]) -> int: stk = [] for num in nums: total, cnt = num, 1 while len(stk) > 0 and stk[-1][0] / stk[-1][1] <= total / cnt: top = stk.pop() total += top[0] cnt += top[1] stk.append([total, cnt]) ans = math.ceil(stk[0][0] / stk[0][1]) return ans
minimize-maximum-of-array
[Python3]Monotonic Stack O(n) with explanation
huangweijing
0
3
minimize maximum of array
2,439
0.331
Medium
33,382
https://leetcode.com/problems/minimize-maximum-of-array/discuss/2806878/Easy-to-understand
class Solution: def minimizeArrayValue(self, nums: List[int]) -> int: s,n = 0,len(nums) res = 0 for i in range(n): s+=nums[i] res = max(res,math.ceil(s/(i+1))) return res
minimize-maximum-of-array
Easy to understand
Rtriders
0
3
minimize maximum of array
2,439
0.331
Medium
33,383
https://leetcode.com/problems/minimize-maximum-of-array/discuss/2755712/Binary-search-for-the-max
class Solution: def minimizeArrayValue(self, nums: List[int]) -> int: left, right = nums[0], max(nums) n1 = len(nums) - 1 while left < right: middle = (left + right) // 2 lst = nums.copy() for i in range(n1, 0, -1): diff = lst[i] - middle if diff > 0: lst[i] = middle lst[i - 1] += diff if lst[0] <= middle: right = middle else: left = middle + 1 return right
minimize-maximum-of-array
Binary search for the max
EvgenySH
0
11
minimize maximum of array
2,439
0.331
Medium
33,384
https://leetcode.com/problems/minimize-maximum-of-array/discuss/2711576/Python-Binary-Search-solution-easy-to-understand
class Solution: def minimizeArrayValue(self, nums: List[int]) -> int: n = len(nums) def canForm(k): rest = 0 for i in range(n - 1, 0, -1): cur = nums[i] if rest + cur <= k: rest = 0 else: rest = (cur + rest) - k return rest + nums[0] <= k #binary search: find the first true of canForm lo = 0 hi = max(nums) + 1 while lo < hi: mid = (hi + lo) // 2 if canForm(mid): hi = mid else: lo = mid + 1 return lo
minimize-maximum-of-array
[Python] Binary Search solution, easy to understand
cosmicshuai
0
18
minimize maximum of array
2,439
0.331
Medium
33,385
https://leetcode.com/problems/minimize-maximum-of-array/discuss/2710839/Python3-Binary-Search-Solution
class Solution: def minimizeArrayValue(self, nums: List[int]) -> int: start, end = 0, max(nums) size_t = len(nums) while start < end: mid = floor((start + end) / 2) i = 0 flag = True remain = 0 for i in range(size_t): remain += max(mid - nums[i], 0) remain -= max(nums[i] - mid, 0) if remain < 0: flag = False; break if flag: end = mid else: start = mid + 1 return start
minimize-maximum-of-array
Python3 Binary Search Solution
xxHRxx
0
10
minimize maximum of array
2,439
0.331
Medium
33,386
https://leetcode.com/problems/minimize-maximum-of-array/discuss/2710490/Easy-Python-soln
class Solution: def minimizeArrayValue(self, nums: List[int]) -> int: i=1 while i<len(nums): nums[i]+=nums[i-1] i+=1 i=0 while i<len(nums): nums[i]/=i+1 i+=1 m=max(nums) if int(m)==m: return int(m) else: return int(m)+1
minimize-maximum-of-array
Easy Python soln
DhruvBagrecha
0
9
minimize maximum of array
2,439
0.331
Medium
33,387
https://leetcode.com/problems/minimize-maximum-of-array/discuss/2709857/Python-O(n)-time-O(1)-extra-space-beats-100
class Solution: def minimizeArrayValue(self, nums: List[int]) -> int: curSum = nums[0] curMax = nums[0] for i in range(1, len(nums)): curSum += nums[i] if nums[i] > curMax: bal = curSum//(i+1) curMax = max(curMax, bal + (1 if curSum % (i+1) > 0 else 0)) return curMax
minimize-maximum-of-array
Python O(n) time O(1) extra space beats 100%
AkshayDagar
0
6
minimize maximum of array
2,439
0.331
Medium
33,388
https://leetcode.com/problems/minimize-maximum-of-array/discuss/2708743/python-oror-simple-binary-search
class Solution: def minimizeArrayValue(self, nums: List[int]) -> int: def ispossible(target,arr): for i in range(len(arr)-1): if arr[i] > target: return False arr[i+1] -= target-arr[i] if arr[len(arr)-1]<=target: return True return False ans = 0 l = 0 r = max(nums) while l<=r: mid = (l+r)>>1 arr = nums[:] if ispossible(mid,arr): r = mid-1 ans = mid else: l = mid+1 return ans #please upvote if youlike
minimize-maximum-of-array
python || simple binary search
deepakchowdary866
0
20
minimize maximum of array
2,439
0.331
Medium
33,389
https://leetcode.com/problems/minimize-maximum-of-array/discuss/2707303/Python3-greedy
class Solution: def minimizeArrayValue(self, nums: List[int]) -> int: return max((x+i)//(i+1) for i, x in enumerate(accumulate(nums)))
minimize-maximum-of-array
[Python3] greedy
ye15
0
17
minimize maximum of array
2,439
0.331
Medium
33,390
https://leetcode.com/problems/minimize-maximum-of-array/discuss/2706562/Binary-Search-in-Python
class Solution: def minimizeArrayValue(self, nums: List[int]) -> int: def isPossible(arr,mid): n = len(arr) if arr[0] > mid: return False p = arr[0] for i in range(1,n): d = mid - p p = arr[i] - d if p > mid: return False return True l,h = 1,max(nums) ans = h while l<=h: mid = (l+h)//2 if isPossible(nums,mid): ans = min(mid,ans) h = mid-1 else: l = mid+1 return ans
minimize-maximum-of-array
Binary Search in Python
fahadahasmi
0
24
minimize maximum of array
2,439
0.331
Medium
33,391
https://leetcode.com/problems/minimize-maximum-of-array/discuss/2706524/O(n)-oror-DP-oror-Prefix-sum
class Solution: def minimizeArrayValue(self, nums: List[int]) -> int: n = len(nums) pr = [0] for i in range(n): pr.append(pr[-1] + nums[i]) dp = [0] * n dp[0] = nums[0] for i in range(1, n): if nums[i] < dp[i - 1]: dp[i] = dp[i - 1] else: dp[i] = max(dp[i - 1], math.ceil(pr[i + 1] / (i + 1))) return dp[-1]
minimize-maximum-of-array
O(n) || DP || Prefix sum
ser0p
0
41
minimize maximum of array
2,439
0.331
Medium
33,392
https://leetcode.com/problems/create-components-with-same-value/discuss/2707304/Python3-post-order-dfs
class Solution: def componentValue(self, nums: List[int], edges: List[List[int]]) -> int: tree = [[] for _ in nums] for u, v in edges: tree[u].append(v) tree[v].append(u) def fn(u, p): """Post-order dfs.""" ans = nums[u] for v in tree[u]: if v != p: ans += fn(v, u) return 0 if ans == cand else ans total = sum(nums) for cand in range(1, total//2+1): if total % cand == 0 and fn(0, -1) == 0: return total//cand-1 return 0
create-components-with-same-value
[Python3] post-order dfs
ye15
11
264
create components with same value
2,440
0.543
Hard
33,393
https://leetcode.com/problems/create-components-with-same-value/discuss/2706535/Python-Get-factors-of-sum-all-nodes-then-check
class Solution: def getFactors(self, x): factors = [] for i in range(1, int(sqrt(x)) + 1): if x % i != 0: continue factors.append(i) if x // i != i: factors.append(x // i) return factors def componentValue(self, nums: List[int], edges: List[List[int]]) -> int: n = len(nums) graph = defaultdict(list) for a, b in edges: graph[a].append(b) graph[b].append(a) self.cntRemainZero = 0 def dfs(u, p, sumPerComponent): # return remain of the subtree with root `u` remain = nums[u] for v in graph[u]: if v == p: continue remain += dfs(v, u, sumPerComponent) remain %= sumPerComponent if remain == 0: self.cntRemainZero += 1 return remain def isGood(sumPerComponent, expectedNumOfComponents): self.cntRemainZero = 0 dfs(0, -1, sumPerComponent) return self.cntRemainZero == expectedNumOfComponents sumAllNodes, maxNum = sum(nums), max(nums) for sumPerComponent in sorted(self.getFactors(sumAllNodes)): if sumPerComponent < maxNum: continue # at least maxNum expectedNumOfComponents = sumAllNodes // sumPerComponent if isGood(sumPerComponent, expectedNumOfComponents): return expectedNumOfComponents - 1 # Need to cut `numOfComponent - 1` edges to make `numOfComponent` connected component return 0
create-components-with-same-value
[Python] Get factors of sum all nodes then check
hiepit
4
337
create components with same value
2,440
0.543
Hard
33,394
https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative/discuss/2774238/Easy-Python-Solution
class Solution: def findMaxK(self, nums: List[int]) -> int: nums.sort() for i in nums[::-1]: if -i in nums: return i return -1
largest-positive-integer-that-exists-with-its-negative
Easy Python Solution
Vistrit
3
64
largest positive integer that exists with its negative
2,441
0.678
Easy
33,395
https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative/discuss/2708513/largest-positive-integer-that-exists-with-its-negative
class Solution: def findMaxK(self, nums: List[int]) -> int: nums=sorted(nums,reverse=True) s=set(nums) for i in range(len(nums)): if 0-nums[i] in s: return nums[i] return -1
largest-positive-integer-that-exists-with-its-negative
largest-positive-integer-that-exists-with-its-negative
meenu155
1
35
largest positive integer that exists with its negative
2,441
0.678
Easy
33,396
https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative/discuss/2708334/Python-1-liner-simple
class Solution: def findMaxK(self, nums: List[int]) -> int: return max(list(filter(lambda x: nums.count(x) >= 1 and nums.count(-x) >= 1, nums)) + [-1])
largest-positive-integer-that-exists-with-its-negative
Python 1-liner simple
dhnam2234
1
82
largest positive integer that exists with its negative
2,441
0.678
Easy
33,397
https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative/discuss/2708275/Python-O(n)
class Solution: def findMaxK(self, nums: List[int]) -> int: d = {} for i in nums: d[i] = d.get(i, 0)+1 ans = -1 for i in sorted(d.keys()): if i<0: continue elif i>0 and -i in d: ans = i return ans
largest-positive-integer-that-exists-with-its-negative
Python O(n)
diwakar_4
1
31
largest positive integer that exists with its negative
2,441
0.678
Easy
33,398
https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative/discuss/2846890/Python-Super-Easy-One-Pass-Solution
class Solution: def findMaxK(self, nums: List[int]) -> int: res = -1 s = set() for num in nums: if -num in s: res = max(res, abs(num)) s.add(num) return res
largest-positive-integer-that-exists-with-its-negative
Python Super Easy One Pass Solution
kaien
0
2
largest positive integer that exists with its negative
2,441
0.678
Easy
33,399