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/minimum-amount-of-time-to-collect-garbage/discuss/2494579/O(n)-with-total-time-costs-for-every-garbage-and-moving-using-Hash-Map
class Solution: def garbageCollection(self, garbage: List[str], travel: List[int]) -> int: n = len(garbage) s = [0] * n for i in range(1, n): s[i] = s[i-1] + travel[i-1] ans = 0 h_total = {} g_total = {} for i in range(n): g = {} for gi in garbage[i]: g[gi] = g.get(gi, 0) + 1 for k in g: h_total[k] = s[i] g_total[k] = g_total.get(k, 0) + g[k] print(g_total, h_total) ans = sum(h_total.values()) + sum(g_total.values()) print("=" * 20) return ans print = lambda *a,**aa: ()
minimum-amount-of-time-to-collect-garbage
O(n) with total time costs for every garbage and moving using Hash-Map
dntai
0
2
minimum amount of time to collect garbage
2,391
0.851
Medium
32,700
https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2493329/Secret-Python-Answer-Using-a-Stack
class Solution: def garbageCollection(self, garbage: List[str], travel: List[int]) -> int: def traverse(t): vis = [g.count(t) for g in garbage] while(vis and vis[-1] == 0): vis.pop() total = 0 if not vis: return 0 total += vis[0] for i in range(1,len(vis)): total += travel[i-1] total += vis[i] return total res = 0 res += traverse('M') res += traverse('P') res += traverse('G') return res
minimum-amount-of-time-to-collect-garbage
[Secret Python AnswerπŸ€«πŸπŸ‘ŒπŸ˜] Using a Stack
xmky
0
8
minimum amount of time to collect garbage
2,391
0.851
Medium
32,701
https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2493013/Python3-Simulation-Iteration-Easy-Solution
class Solution: def garbageCollection(self, garbage: List[str], travel: List[int]) -> int: def getlast(arr,n, x): for i in range(n-1, -1, -1): if x in arr[i]: return i return 0 ans=0 n = len(garbage) g = getlast(garbage,n, "G") p = getlast(garbage,n, "P") m = getlast(garbage,n, "M") for i in garbage: if "G" in i: ans += (i.count("G")) if "P" in i: ans += (i.count("P")) if "M" in i: ans += (i.count("M")) ans += sum(travel[:g]) ans += sum(travel[:p]) ans += sum(travel[:m]) return ans
minimum-amount-of-time-to-collect-garbage
Python3, Simulation, Iteration, Easy Solution
mrprashantkumar
0
6
minimum amount of time to collect garbage
2,391
0.851
Medium
32,702
https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2492949/Python3-or-Solved-Intuitively-With-Help-of-Three-Hashmaps
class Solution: #If I let n = travel.length and m = garbage.length... #Time-Complexity: O(travel.length + garbage.length*10 + 3*garbage.length) -> O(n + m) #Space-Complexity: O(3m + (n+1)) ->O(m + n) def garbageCollection(self, garbage: List[str], travel: List[int]) -> int: #Approach: First, traverse through garbage array and identify the count as well as the index position of houses #each type of garbage is at! #Utilize 3 hashmaps: one for metal , one for glass , and one for paper! #key: index pos -> count: number of garbage at index pos house of that particular type! metal = {} paper = {} glass = {} #need to allocate another array that describes time cost to reach ith index house! travel_cost = [] travel_cost.append(0) cur_cost = 0 for e in travel: cur_cost += e travel_cost.append(cur_cost) for i in range(len(garbage)): for c in garbage[i]: if(c == 'M'): if(i not in metal): metal[i] = 1 else: metal[i] += 1 elif(c == 'P'): if(i not in paper): paper[i] = 1 else: paper[i] += 1 else: if(i not in glass): glass[i] = 1 else: glass[i] += 1 #once hashmaps are updated, handle 3 types of garbage collection! #1. Metal metal_cost = 0 pre = 0 metal_keys = sorted(metal.keys()) for mk in metal_keys: metal_cost += metal[mk] metal_cost += (travel_cost[mk] - travel_cost[pre]) pre = mk #2. Paper paper_cost = 0 pre2 = 0 paper_keys = sorted(paper.keys()) for pk in paper_keys: paper_cost += paper[pk] paper_cost += (travel_cost[pk] - travel_cost[pre2]) pre2 = pk #3. glass glass_cost = 0 pre3 = 0 glass_keys = sorted(glass.keys()) for gk in glass_keys: glass_cost += glass[gk] glass_cost += (travel_cost[gk] - travel_cost[pre3]) pre3 = gk return metal_cost + paper_cost + glass_cost
minimum-amount-of-time-to-collect-garbage
Python3 | Solved Intuitively With Help of Three Hashmaps
JOON1234
0
9
minimum amount of time to collect garbage
2,391
0.851
Medium
32,703
https://leetcode.com/problems/build-a-matrix-with-conditions/discuss/2492822/Python3-topological-sort
class Solution: def buildMatrix(self, k: int, rowConditions: List[List[int]], colConditions: List[List[int]]) -> List[List[int]]: def fn(cond): """Return topological sort""" graph = [[] for _ in range(k)] indeg = [0]*k for u, v in cond: graph[u-1].append(v-1) indeg[v-1] += 1 queue = deque(u for u, x in enumerate(indeg) if x == 0) ans = [] while queue: u = queue.popleft() ans.append(u+1) for v in graph[u]: indeg[v] -= 1 if indeg[v] == 0: queue.append(v) return ans row = fn(rowConditions) col = fn(colConditions) if len(row) < k or len(col) < k: return [] ans = [[0]*k for _ in range(k)] row = {x : i for i, x in enumerate(row)} col = {x : j for j, x in enumerate(col)} for x in range(1, k+1): ans[row[x]][col[x]] = x return ans
build-a-matrix-with-conditions
[Python3] topological sort
ye15
12
339
build a matrix with conditions
2,392
0.592
Hard
32,704
https://leetcode.com/problems/build-a-matrix-with-conditions/discuss/2494198/Python-3-Topological-Sort-Ez-To-Understand
class Solution: def buildMatrix(self, n: int, rowC: List[List[int]], colC: List[List[int]]) -> List[List[int]]: # create two graphs, one for row and one for columns row_adj = {i: [] for i in range(1, n + 1)} col_adj = {i: [] for i in range(1, n + 1)} for u, v in rowC: row_adj[u].append(v) for u, v in colC: col_adj[u].append(v) # inorder to do topological sort, we need to maintain two visit lists: one marks which node # we have already processed (because not all nodes are connected to each other and we do not # want to end up in a infinite loop), the other one marks nodes we are currently visiting(or in # our recursion stack). If we visit a node that we are currently visiting, that means there is # a loop, so we return False; if it is not in our current visit but has already been visited, we # can safely travel to the next node and return True. row_stack = [] row_visit = set() row_visiting = set() col_stack = [] col_visit = set() col_visiting = set() def dfs(node, stack, visit, visiting, adj): if node in visiting: return False if node in visit: return True visit.add(node) visiting.add(node) for child in adj[node]: if not dfs(child, stack, visit, visiting, adj): return False visiting.remove(node) stack.append(node) return True # do dfs on each row/col graph for i in range(1, n + 1): if i not in row_visit: if not dfs(i, row_stack, row_visit, row_visiting, row_adj): return [] if i not in col_visit: if not dfs(i, col_stack, col_visit, col_visiting, col_adj): return [] # After the dfs, we also need a stack to store which node has been entirely explored. That's why we # append the current node to our stack after exploring all its neighbors. Remember we have to reverse # the stack after all DFS's, because the first-explored node gets appended first. row_stack, col_stack = row_stack[::-1], col_stack[::-1] # mark position for each element row_memo, col_memo = {}, {} for idx, num in enumerate(row_stack): row_memo[num] = idx for idx, num in enumerate(col_stack): col_memo[num] = idx # create an empty matrix as our ans ans = [[0]*n for _ in range(n)] # plug in values from what we have discovered for i in range(1, n + 1): ans[row_memo[i]][col_memo[i]] = i return ans
build-a-matrix-with-conditions
[Python 3] Topological Sort Ez To Understand
Che4pSc1ent1st
1
12
build a matrix with conditions
2,392
0.592
Hard
32,705
https://leetcode.com/problems/build-a-matrix-with-conditions/discuss/2675288/Python3-or-Toposort-or-Kahn's-Algorithm
class Solution: def buildMatrix(self, k: int, rc: List[List[int]], cc: List[List[int]]) -> List[List[int]]: def toposortBFS(cond): adj=[[] for i in range(k+1)] for u,v in cond: adj[u].append(v) inDegree=[0 for i in range(k+1)] topoArray=[] q=[] for i in range(1,k+1): for j in adj[i]: inDegree[j]+=1 for i in range(1,k+1): if inDegree[i]==0: q.append(i) while q: ele=q.pop(0) topoArray.append(ele) for it in adj[ele]: inDegree[it]-=1 if inDegree[it]==0: q.append(it) return topoArray t1=toposortBFS(rc) t2=toposortBFS(cc) if len(t1)<k or len(t2)<k: return [] ans=[[0 for i in range(k)] for i in range(k)] hmap=defaultdict(list) for ind,x in enumerate(t1): hmap[x].append(ind) for ind,x in enumerate(t2): hmap[x].append(ind) for key in hmap.keys(): x,y=hmap[key] ans[x][y]=key return ans
build-a-matrix-with-conditions
[Python3] | Toposort | Kahn's Algorithm
swapnilsingh421
0
9
build a matrix with conditions
2,392
0.592
Hard
32,706
https://leetcode.com/problems/build-a-matrix-with-conditions/discuss/2499448/Topological-Sort
class Solution: def buildMatrix(self, k: int, rs1: List[List[int]], cs: List[List[int]]) -> List[List[int]]: def solve(rs): adj,ind,q,l = defaultdict(list),{},deque(),[] for val in rs: adj[val[1]].append(val[0]) ind[val[0]] = ind.get(val[0],0)+1 for val in range(1,k+1): if ind.get(val,0) == 0: q.append(val) l.append(val) while q: t = q.popleft() for val in adj[t]: ind[val] -= 1 if ind[val] == 0: q.append(val) l.append(val) return l l,l1,dx,dy,ans = solve(rs1),solve(cs),{},{},[[0 for i in range(k)]for j in range(k)] if len(l) != k or len(l1)!=k: return [] for i in range(k): dx[l[i]] = k-1-i for j in range(k): dy[l1[j]] = k-1-j for i in range(1,k+1): ans[dx[i]][dy[i]] = i return ans
build-a-matrix-with-conditions
Topological Sort
Shivamk09
0
9
build a matrix with conditions
2,392
0.592
Hard
32,707
https://leetcode.com/problems/build-a-matrix-with-conditions/discuss/2496111/Python-3Kahn's-algorithm
class Solution: def buildMatrix(self, k: int, rowConditions: List[List[int]], colConditions: List[List[int]]) -> List[List[int]]: gr, gc = defaultdict(set), defaultdict(set) dr, dc = defaultdict(int), defaultdict(int) for a, b in rowConditions: if b in gr[a]: continue #drop duplicates gr[a].add(b) dr[b] += 1 for a, b in colConditions: if b in gc[a]: continue gc[a].add(b) dc[b] += 1 # start from leftmost and upmost nodes row_start = [i for i in range(1, k+1) if not dr[i]] col_start = [i for i in range(1, k+1) if not dc[i]] if not row_start or not col_start: return [] # row and col locations for nodes r, c = defaultdict(lambda: -1), defaultdict(lambda: -1) cnt = 0 while row_start: q = [] for x in row_start: r[x] = cnt cnt += 1 for nei in gr[x]: dr[nei] -= 1 if not dr[nei]: q.append(nei) row_start = q # if still nodes with degree above zero, then cycle detected # e.g. [[1, 4], [4, 2], [2, 3], [3, 4]] if any(dr[x] for x in dr): return [] cnt = 0 while col_start: q = [] for x in col_start: c[x] = cnt cnt += 1 for nei in gc[x]: dc[nei] -= 1 if not dc[nei]: q.append(nei) col_start = q if any(dc[x] for x in dc): return [] non_used_row, non_used_col = len(r), len(c) # for undefined nodes pick any unused row/cols ans = [[0] * k for _ in range(k)] for i in range(1, k+1): x, y = None, None if r[i] != -1: x = r[i] else: x = non_used_row non_used_row += 1 if c[i] != -1: y = c[i] else: y = non_used_col non_used_col += 1 ans[x][y] = i return ans
build-a-matrix-with-conditions
[Python 3]Kahn's algorithm
chestnut890123
0
9
build a matrix with conditions
2,392
0.592
Hard
32,708
https://leetcode.com/problems/build-a-matrix-with-conditions/discuss/2495550/Python3-Topological-Sort-or-Expending-from-other's-work
class Solution: def buildMatrix(self, k: int, rowConditions, colConditions): def releaseSeq(cond): # build dependence map dep = [set() for i in range(k)] acquire = [set() for i in range(k)] for a, b in cond: dep[b - 1].add(a - 1) acquire[a - 1].add(b - 1) # finding item already free released = deque() for i, s in enumerate(dep): if len(s) == 0: released.append(i) if not released: return None ans = [None for i in range(k)] allocatedNum = 0 while released: idx = released.popleft() ans[idx] = allocatedNum allocatedNum += 1 # releasing lock for b in acquire[idx]: dep[b].discard(idx) if len(dep[b]) == 0: # add new free into queue released.append(b) # not all item been released if allocatedNum < k: return None return ans row = releaseSeq(rowConditions) col = None if row is not None: col = releaseSeq(colConditions) if row is None or \ col is None: return [] r = [[0 for i in range(k)] for j in range(k)] for (n, (i, j)) in enumerate(zip(row, col), start = 1): r[i][j] = n return r
build-a-matrix-with-conditions
[Python3] Topological Sort | Expending from other's work
staytime
0
6
build a matrix with conditions
2,392
0.592
Hard
32,709
https://leetcode.com/problems/build-a-matrix-with-conditions/discuss/2494730/python3-topological-sorting-sol-for-reference.
class Solution: def getOrder(self, cond, k): gc = defaultdict(set) order = [] cond = set([tuple(i) for i in cond]) indegree = [0]*(k+1) for a, b in cond: gc[a].add(b) indegree[b] += 1 for i in range(1,k+1): if indegree[i] == 0: order.append(i) orderidx = 0 while orderidx < len(order): node = order[orderidx] orderidx += 1 for nei in gc[node]: indegree[nei] -= 1 if indegree[nei] == 0: order.append(nei) return order def buildMatrix(self, k: int, rowConditions: List[List[int]], colConditions: List[List[int]]) -> List[List[int]]: rorder = self.getOrder(rowConditions, k) corder = self.getOrder(colConditions, k) korder = [[0,0] for _ in range(k+1)] if len(rorder) != k or len(corder) != k: return [] for r in range(1,k+1): korder[rorder[r-1]][0] = r-1 korder[corder[r-1]][1] = r-1 kmatrix = [[0 for _ in range(k)] for _ in range(k)] for i in range(1, k+1): x,y = korder[i] kmatrix [x][y] = i return kmatrix
build-a-matrix-with-conditions
[python3] topological sorting sol for reference.
vadhri_venkat
0
5
build a matrix with conditions
2,392
0.592
Hard
32,710
https://leetcode.com/problems/build-a-matrix-with-conditions/discuss/2493386/Simple-Answer-Alien-Dictionary-Graph-%2B-DFS
class Solution: def buildMatrix(self, k: int, rowConditions: List[List[int]], colConditions: List[List[int]]) -> List[List[int]]: graph_row = defaultdict(set) graph_col = defaultdict(set) for row in rowConditions: graph_row[row[0]].add(row[1]) for col in colConditions: graph_col[col[0]].add(col[1]) order_row = list() order_col = list() visited_row = defaultdict(bool) visited_col = defaultdict(bool) def dfs(i,v,o,g): if i in v: return v[i] v[i] = True for n in g[i]: if dfs(n,v,o,g): return True v[i] = False o.append(i) for i in range(1,k+1): if dfs(i,visited_row, order_row,graph_row): return [] for i in range(1,k+1): if dfs(i,visited_col,order_col ,graph_col): return [] order_row.reverse() order_col.reverse() pos = [[0,0] for i in range(k+1)] for i,v in enumerate(order_row): pos[v][0] = i for i,v in enumerate(order_col): pos[v][1] = i res = [[0 for i in range(k)] for j in range(k)] for i,p in enumerate(pos): if i == 0: continue res[p[0]][p[1]] = i return res
build-a-matrix-with-conditions
[Simple AnswerπŸ€«πŸπŸ‘ŒπŸ˜] Alien Dictionary Graph + DFS
xmky
0
17
build a matrix with conditions
2,392
0.592
Hard
32,711
https://leetcode.com/problems/build-a-matrix-with-conditions/discuss/2492772/Python3-or-Easy-to-understand-solution-based-on-210-or-Topological-Sort
class Solution: def buildMatrix(self, k: int, rowCond: List[List[int]], colCond: List[List[int]]) -> List[List[int]]: # topological sort: # For rows, in other words "above" should be put on the rows with index smaller than "after" # so if we could form an k-length result array with the order restricted by rowCondition # then we know we should put the numbers to the rows accordingly # For example, as for example 1, # if we get [3, 1, 2] as one of the topological sorted result array, # we know that 3 should be put in the first row (idx = 0), 1 in the second row (idx = 1), 2 in the third row(idx = 2) # so we get the row index for each number in [1, k] # We could get the col index similarily def topo(cond): G = defaultdict(list) indegree = [0] * (k + 1) # build graph, above_edge -> below_edge, or left -> right for a, b in cond: G[a].append(b) indegree[b] += 1 queue = deque([i for i in range(1, k + 1) if indegree[i] == 0]) res = [] while queue: cur = queue.popleft() res.append(cur) for nxt in G[cur]: indegree[nxt] -= 1 if indegree[nxt] == 0: queue.append(nxt) return res rows, cols = topo(rowCond), topo(colCond) # can not form a solution with exact k value sorted in topological order if len(rows) != k or len(cols) != k: return [] # build num -> idx mp for easier queries mp1, mp2 = {}, {} for i, r in enumerate(rows): mp1[r] = i for i, c in enumerate(cols): mp2[c] = i res = [[0] * k for _ in range(k)] for num in range(1, k + 1): ri, ci = mp1[num], mp2[num] res[ri][ci] = num return res
build-a-matrix-with-conditions
Python3 | Easy to understand solution based on 210 | Topological Sort
silencea
0
8
build a matrix with conditions
2,392
0.592
Hard
32,712
https://leetcode.com/problems/find-subarrays-with-equal-sum/discuss/2525818/Python-oror-Sliding-window-oror-Bruteforce
class Solution: def findSubarrays(self, nums: List[int]) -> bool: """ Bruteforce approch """ # for i in range(len(nums)-2): # summ1 = nums[i] + nums[i+1] # # for j in range(i+1,len(nums)): # for j in range(i+1,len(nums)-1): # summ = nums[j] + nums[j+1] # if summ == summ1: # return True # return False """ Sliding Window """ one ,two = len(nums)-2,len(nums)-1 // at end of list dic = {} while one >= 0: # print(one,two) summ = nums[one] + nums[two] if summ in dic: return True // if already there then there is 2 pairs else: dic[summ] = 1 // add summ in of window in dictonary one -=1 two -=1 return False
find-subarrays-with-equal-sum
Python || Sliding window || Bruteforce
1md3nd
4
85
find subarrays with equal sum
2,395
0.639
Easy
32,713
https://leetcode.com/problems/find-subarrays-with-equal-sum/discuss/2600901/Python-Simple-Python-Solution-Using-Dictionary-or-95-Faster
class Solution: def findSubarrays(self, nums: List[int]) -> bool: dictionary = {} for i in range(len(nums) - 1): subarray_sum = sum(nums[i:i+2]) if subarray_sum not in dictionary: dictionary[subarray_sum] = nums[i:i+2] else: return True return False
find-subarrays-with-equal-sum
[ Python ] βœ…βœ… Simple Python Solution Using Dictionary | 95% Faster πŸ₯³βœŒπŸ‘
ASHOK_KUMAR_MEGHVANSHI
2
53
find subarrays with equal sum
2,395
0.639
Easy
32,714
https://leetcode.com/problems/find-subarrays-with-equal-sum/discuss/2525530/Python-or-Easy-Understanding
class Solution: def findSubarrays(self, nums: List[int]) -> bool: all_sums = [] for i in range(0, len(nums) - 1): if nums[i] + nums[i + 1] in all_sums: return True else: all_sums.append(nums[i] + nums[i + 1]) return False
find-subarrays-with-equal-sum
Python | Easy Understanding
cyber_kazakh
2
38
find subarrays with equal sum
2,395
0.639
Easy
32,715
https://leetcode.com/problems/find-subarrays-with-equal-sum/discuss/2525028/Python-99-Easy-Simple-Solution-or-Set
class Solution: def findSubarrays(self, nums: list[int]) -> bool: sums = set() for i in range(len(nums) - 1): getSum = nums[i] + nums[i + 1] if getSum in sums: return True sums.add(getSum) return False
find-subarrays-with-equal-sum
βœ… Python 99% Easy Simple Solution | Set
sezanhaque
1
14
find subarrays with equal sum
2,395
0.639
Easy
32,716
https://leetcode.com/problems/find-subarrays-with-equal-sum/discuss/2839515/Simple-Hashmap-solution-Python
class Solution: def findSubarrays(self, nums: List[int]) -> bool: dic = {} for i in range(0,len(nums)-1): s = nums[i] + nums[i+1] if s in dic: return True dic[s] = i return False
find-subarrays-with-equal-sum
Simple Hashmap solution Python
aruj900
0
1
find subarrays with equal sum
2,395
0.639
Easy
32,717
https://leetcode.com/problems/find-subarrays-with-equal-sum/discuss/2638521/Python-easy
class Solution: def findSubarrays(self, nums: List[int]) : res=[] i,j=0,1 while j<=len(nums)-1: res.append(nums[i]+nums[j]) i+=1 j+=1 return len(res)!=len(set(res))
find-subarrays-with-equal-sum
Python easy
HeyAnirudh
0
12
find subarrays with equal sum
2,395
0.639
Easy
32,718
https://leetcode.com/problems/find-subarrays-with-equal-sum/discuss/2567170/Hope-you-like-it
class Solution: def findSubarrays(self, nums: List[int]) -> bool: no=nums d=defaultdict(int) flag=False for i in range(len(no)-1): if sum((no[i],no[i+1])) in d: flag=True else: d[sum((no[i],no[i+1]))]+=1 return flag
find-subarrays-with-equal-sum
Hope you like it
mailer2021rad
0
10
find subarrays with equal sum
2,395
0.639
Easy
32,719
https://leetcode.com/problems/find-subarrays-with-equal-sum/discuss/2565796/Python3-Easy-solution-or-Hashmap
class Solution: def findSubarrays(self, nums: List[int]) -> bool: sums = set() # Note: using range(1, len(nums)) will be 30% slower for i in range(len(nums)-1): sum = nums[i] + nums[i+1] if sum in sums: return True sums.add(sum) return False
find-subarrays-with-equal-sum
Python3 Easy solution | Hashmap
ckayfok
0
28
find subarrays with equal sum
2,395
0.639
Easy
32,720
https://leetcode.com/problems/find-subarrays-with-equal-sum/discuss/2540663/Using-set()-and-zip()-94-speed
class Solution: def findSubarrays(self, nums: List[int]) -> bool: sums = set() for a, b in zip(nums, nums[1:]): if (s := a + b) in sums: return True else: sums.add(s) return False
find-subarrays-with-equal-sum
Using set() and zip(), 94% speed
EvgenySH
0
9
find subarrays with equal sum
2,395
0.639
Easy
32,721
https://leetcode.com/problems/find-subarrays-with-equal-sum/discuss/2526368/Python3-Hash-Set-O(n)-Time-and-Space
class Solution: def findSubarrays(self, nums: List[int]) -> bool: """ Logic: Hash set Time: O(n) Space: O(n) """ visited = set() for i in range(1, len(nums)): if nums[i] + nums[i-1] not in visited: visited.add(nums[i] + nums[i-1]) else: return True return False
find-subarrays-with-equal-sum
[Python3] Hash Set - O(n) Time & Space
hanelios
0
2
find subarrays with equal sum
2,395
0.639
Easy
32,722
https://leetcode.com/problems/find-subarrays-with-equal-sum/discuss/2525313/Python-simple-solution
class Solution: def findSubarrays(self, nums: List[int]) -> bool: seen = set() for i in range(1, len(nums)): if nums[i-1]+nums[i] in seen: return True else: seen.add(nums[i-1]+nums[i]) return False
find-subarrays-with-equal-sum
Python simple solution
StikS32
0
8
find subarrays with equal sum
2,395
0.639
Easy
32,723
https://leetcode.com/problems/find-subarrays-with-equal-sum/discuss/2525295/Easy-Python-Solution-With-Set
class Solution: def findSubarrays(self, nums: List[int]) -> bool: s=set() for i in range(len(nums)-1): x=sum(nums[i:i+2]) if x in s: return True else: s.add(x) return False
find-subarrays-with-equal-sum
Easy Python Solution With Set
a_dityamishra
0
3
find subarrays with equal sum
2,395
0.639
Easy
32,724
https://leetcode.com/problems/find-subarrays-with-equal-sum/discuss/2525251/Python-set
class Solution: def findSubarrays(self, nums: List[int]) -> bool: sums = set() for i in range(1, len(nums)): s = nums[i] + nums[i-1] if s in sums: return True sums.add(s) return False
find-subarrays-with-equal-sum
Python, set
blue_sky5
0
19
find subarrays with equal sum
2,395
0.639
Easy
32,725
https://leetcode.com/problems/find-subarrays-with-equal-sum/discuss/2524923/Set
class Solution: def findSubarrays(self, nums: List[int]) -> bool: possibleSums = set() for i in range(1, len(nums)): possibleSum = nums[i - 1] + nums[i] if possibleSum in possibleSums: return True possibleSums.add(possibleSum) return False
find-subarrays-with-equal-sum
Set
sr_vrd
0
4
find subarrays with equal sum
2,395
0.639
Easy
32,726
https://leetcode.com/problems/find-subarrays-with-equal-sum/discuss/2524740/Python3-hash-set
class Solution: def findSubarrays(self, nums: List[int]) -> bool: seen = set() for i in range(1, len(nums)): sm = nums[i-1] + nums[i] if sm in seen: return True seen.add(sm) return False
find-subarrays-with-equal-sum
[Python3] hash set
ye15
0
13
find subarrays with equal sum
2,395
0.639
Easy
32,727
https://leetcode.com/problems/find-subarrays-with-equal-sum/discuss/2524699/Sliding-Window
class Solution: def findSubarrays(self, nums: List[int]) -> bool: subSum = 0 p1 = 0 count = defaultdict(int) for p2, num in enumerate(nums): subSum += num ln = p2 - p1 + 1 if(ln < 2): continue elif(ln > 2): subSum -= nums[p1] p1 += 1 count[subSum] += 1 if(count[subSum] == 2): return True return False
find-subarrays-with-equal-sum
Sliding Window
thoufic
0
11
find subarrays with equal sum
2,395
0.639
Easy
32,728
https://leetcode.com/problems/strictly-palindromic-number/discuss/2801453/Python-oror-95.34-Faster-oror-Easy-and-Actual-Solution-oror-O(n)-Solution
class Solution: def isStrictlyPalindromic(self, n: int) -> bool: def int2base(n,b): r="" while n>0: r+=str(n%b) n//=b return int(r[-1::-1]) for i in range(2,n-1): if int2base(n,i)!=n: return False return True
strictly-palindromic-number
Python || 95.34% Faster || Easy and Actual Solution || O(n) Solution
DareDevil_007
2
186
strictly palindromic number
2,396
0.877
Medium
32,729
https://leetcode.com/problems/strictly-palindromic-number/discuss/2525677/Python-oror-Bruteforce-oror-Easy
class Solution: def isStrictlyPalindromic(self, n: int) -> bool: def pald(num): if num == num[::-1]: return True return False def pw(num,q): res ="" while num > 0: temp = num % q res = str(temp) + res num //= q return res for i in range(2,n-1): one = pw(n,i) # print(one) if not pald(one): return False return True
strictly-palindromic-number
Python || Bruteforce || Easy
1md3nd
2
48
strictly palindromic number
2,396
0.877
Medium
32,730
https://leetcode.com/problems/strictly-palindromic-number/discuss/2621892/One-Word-Solution-or-Python
class Solution: def isStrictlyPalindromic(self, n: int) -> bool: pass
strictly-palindromic-number
One Word Solution | Python
RajatGanguly
1
122
strictly palindromic number
2,396
0.877
Medium
32,731
https://leetcode.com/problems/strictly-palindromic-number/discuss/2820929/Python-Solution
class Solution: def isStrictlyPalindromic(self, n: int) -> bool: BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" def to_base(n, b): return "0" if not n else to_base(n//b, b).lstrip("0") + BS[n%b] res = False for i in range(2,n-1): i_base = to_base(n, i) if i_base[::-1] == i_base: res = True else: return False return res
strictly-palindromic-number
Python Solution
khaled_achech
0
2
strictly palindromic number
2,396
0.877
Medium
32,732
https://leetcode.com/problems/strictly-palindromic-number/discuss/2783926/Python-Straight-forward-algorithm
class Solution: def isStrictlyPalindromic(self, n: int) -> bool: def convert(n, base): ans = '' while n >= 1: ans = str(n % base) + ans n //= base return ans for i in range(2, n - 1): res = convert(n, i) if res != res[::-1]: return False return True
strictly-palindromic-number
[Python] Straight-forward algorithm
Mark_computer
0
7
strictly palindromic number
2,396
0.877
Medium
32,733
https://leetcode.com/problems/strictly-palindromic-number/discuss/2781741/Simple-Solution-oror-Python3
class Solution: def isStrictlyPalindromic(self, n: int) -> bool: return False
strictly-palindromic-number
Simple Solution || Python3
joshua_mur
0
5
strictly palindromic number
2,396
0.877
Medium
32,734
https://leetcode.com/problems/strictly-palindromic-number/discuss/2781741/Simple-Solution-oror-Python3
class Solution: def isStrictlyPalindromic(self, n: int) -> bool: for i in range(2, n - 1): num = self.baseb(n, i) if not self.isPalindromic(num): return False return True def isPalindromic(self, s: str) -> bool: l = len(s) if l % 2 and s[:l // 2] == s[l // 2 + 2:][::-1]: return True elif not l % 2 and s[:l // 2] == s[l // 2:][::-1]: return True return False def baseb(self, n, b): e = n // b q = n % b if n == 0: return '0' elif e == 0: return str(q) else: return self.baseb(e, b) + str(q)
strictly-palindromic-number
Simple Solution || Python3
joshua_mur
0
5
strictly palindromic number
2,396
0.877
Medium
32,735
https://leetcode.com/problems/strictly-palindromic-number/discuss/2719359/python-solution-or-converting-to-it's-base-or
class Solution: def solve(self, n, i): #to check wheather the given number(n) and it's base (i) sign = '-' if n<0 else '' n = abs(n) if n < i: return str(n) s = '' while n != 0: s = str(n%i) + s n = n//i return sign+s def isStrictlyPalindromic(self, n: int) -> bool: for i in range(2,n-1): check = self.solve(n, i) print(check) if check == n : #if the number (n) less than it's base (i) return False else: if check[::-1] != check: #checking if it's a palindrome return False
strictly-palindromic-number
python solution | converting to it's base |
pandish
0
6
strictly palindromic number
2,396
0.877
Medium
32,736
https://leetcode.com/problems/strictly-palindromic-number/discuss/2710118/Do-not-write-%22return-False%22
class Solution: def to_baseX(self, n: int, base: int) -> str: """ :param n: :param base: :return: convert to base X str """ nums = [] while n: n, mod = divmod(n, base) nums.append(str(mod)) return ''.join(reversed(nums)) def isStrictlyPalindromic(self, n: int) -> bool: for base in range(2, n - 1): result = self.to_baseX(n, base) if result != result[::-1]: return False return True
strictly-palindromic-number
Do not write "return False"
namashin
0
4
strictly palindromic number
2,396
0.877
Medium
32,737
https://leetcode.com/problems/strictly-palindromic-number/discuss/2653490/O(1)-approach
class Solution: def isStrictlyPalindromic(self, n: int) -> bool: return False
strictly-palindromic-number
O(1) approach
maq2628
0
4
strictly palindromic number
2,396
0.877
Medium
32,738
https://leetcode.com/problems/strictly-palindromic-number/discuss/2533263/Python-or-O(1)
class Solution: def isStrictlyPalindromic(self, n: int) -> bool: for i in range(2, n-1): base = "" j = n while j>0: base += str(j%i) j//=i if base != base[::-1]: return False return True
strictly-palindromic-number
Python | O(1)
coolakash10
0
24
strictly palindromic number
2,396
0.877
Medium
32,739
https://leetcode.com/problems/strictly-palindromic-number/discuss/2533263/Python-or-O(1)
class Solution: def isStrictlyPalindromic(self, n: int) -> bool: return False
strictly-palindromic-number
Python | O(1)
coolakash10
0
24
strictly palindromic number
2,396
0.877
Medium
32,740
https://leetcode.com/problems/strictly-palindromic-number/discuss/2525332/Easy-Python-Solution
class Solution: def isStrictlyPalindromic(self, n: int) -> bool: for i in range(2,n-1): s=n sr="" while s>0: d=s%i if s<10: sr+=str(d) else: sr+=chr(ord("A")+d-10) s=s//i if sr!=sr[::-1]: return False return True
strictly-palindromic-number
Easy Python Solution
a_dityamishra
0
29
strictly palindromic number
2,396
0.877
Medium
32,741
https://leetcode.com/problems/strictly-palindromic-number/discuss/2525332/Easy-Python-Solution
class Solution: def isStrictlyPalindromic(self, n: int) -> bool: return False
strictly-palindromic-number
Easy Python Solution
a_dityamishra
0
29
strictly palindromic number
2,396
0.877
Medium
32,742
https://leetcode.com/problems/strictly-palindromic-number/discuss/2524755/Python3-Brain-teaser
class Solution: def isStrictlyPalindromic(self, n: int) -> bool: return False
strictly-palindromic-number
[Python3] Brain teaser
ye15
0
30
strictly palindromic number
2,396
0.877
Medium
32,743
https://leetcode.com/problems/maximum-rows-covered-by-columns/discuss/2524746/Python-Simple-Solution
class Solution: def maximumRows(self, mat: List[List[int]], cols: int) -> int: n,m = len(mat),len(mat[0]) ans = 0 def check(state,row,rowIncludedCount): nonlocal ans if row==n: if sum(state)<=cols: ans = max(ans,rowIncludedCount) return check(state[::],row+1,rowIncludedCount) for j in range(m): if mat[row][j]==1: state[j] = 1 check(state,row+1,rowIncludedCount+1) check([0]*m,0,0) return ans
maximum-rows-covered-by-columns
Python Simple Solution
RedHeadphone
4
431
maximum rows covered by columns
2,397
0.525
Medium
32,744
https://leetcode.com/problems/maximum-rows-covered-by-columns/discuss/2526485/Python-oror-recursion-oror-backtracking
class Solution: def maximumRows(self, mat: List[List[int]], cols: int) -> int: res = [] M = len(mat) N = len(mat[0]) def check(seen): count = 0 for row in mat: flag = True for c in range(N): if row[c] == 1: if c in seen: continue else: flag = False break if flag: count +=1 res.append(count) def solve(c,seen,cols): if cols == 0: check(seen) return if c == N: return else: seen.add(c) solve(c+1,seen,cols-1) seen.remove(c) solve(c+1,seen,cols) seen = set() solve(0,seen,cols) return max(res)
maximum-rows-covered-by-columns
Python || recursion || backtracking
1md3nd
3
113
maximum rows covered by columns
2,397
0.525
Medium
32,745
https://leetcode.com/problems/maximum-rows-covered-by-columns/discuss/2830072/Python-(Simple-Maths)
class Solution: def maximumRows(self, matrix, numSelect): m, n = len(matrix), len(matrix[0]) list_combinations, dict2 = list(combinations({i for i in range(n)},n-numSelect)), defaultdict(int) for i in list_combinations: res = set() for j in i: for k in range(m): if matrix[k][j] == 1: res.add(k) dict2[i] = m - len(res) return max(dict2.values())
maximum-rows-covered-by-columns
Python (Simple Maths)
rnotappl
0
1
maximum rows covered by columns
2,397
0.525
Medium
32,746
https://leetcode.com/problems/maximum-rows-covered-by-columns/discuss/2566226/Combinations-and-issubset()-77-speed
class Solution: def maximumRows(self, matrix: List[List[int]], numSelect: int) -> int: ans = 0 m_ones = [{i for i, v in enumerate(row) if v} for row in matrix] for comb in combinations(range(len(matrix[0])), numSelect): set_comb = set(comb) ans = max(ans, sum(s.issubset(set_comb) for s in m_ones)) return ans
maximum-rows-covered-by-columns
Combinations and issubset(), 77% speed
EvgenySH
0
38
maximum rows covered by columns
2,397
0.525
Medium
32,747
https://leetcode.com/problems/maximum-rows-covered-by-columns/discuss/2534047/Python3-Solution-or-Very-Easy-Approach
class Solution: def maximumRows(self, mat: List[List[int]], cols: int) -> int: allCombinations = [] def combina(nums, k, path): if len(path) == k: allCombinations.append((path)) return for i in range(len(nums)): combina(nums[i+1:], k, path+[nums[i]]) col = len(mat[0]) ans = 0 combina(list(range(0, col)), cols, []) for comb in allCombinations: tot = 0 comb = set(comb) for row in mat: flag = True for i in range(col): if row[i] and i not in comb: flag = False break if flag: tot += 1 ans = max(ans, tot) return ans
maximum-rows-covered-by-columns
Python3 Solution | Very Easy Approach
leet_satyam
0
42
maximum rows covered by columns
2,397
0.525
Medium
32,748
https://leetcode.com/problems/maximum-rows-covered-by-columns/discuss/2527141/Python3-Brute-force-with-combination-helper-function
class Solution: def maximumRows(self, mat: List[List[int]], cols: int) -> int: def helper(start, end, left): if left == 0: return [[]] else: res = [] for element in range(start, end+1): temp_res = helper(element+1, end, left-1) for can in temp_res: res.append([element] + can) return res res = -sys.maxsize m, n = len(mat), len(mat[0]) for element in helper(0, n-1, cols): chosen = set(element) temp_res = 0 for i in range(m): target = mat[i].count(1) row_counter = 0 for j in range(n): if mat[i][j] == 1 and j in chosen: row_counter += 1 if row_counter == target: temp_res += 1 res = max(temp_res, res) return res
maximum-rows-covered-by-columns
Python3 Brute force with combination helper function
xxHRxx
0
10
maximum rows covered by columns
2,397
0.525
Medium
32,749
https://leetcode.com/problems/maximum-rows-covered-by-columns/discuss/2526593/Python3-Backtracing-with-sets
class Solution: def maximumRows(self, mat: List[List[int]], cols: int) -> int: m = len(mat) n = len(mat[0]) # map row to columns with 1s # For example: # mat = [[0,0,0],[1,0,1],[0,1,1],[0,0,1]] # cols_with_ones = { # 0: set([]) # row 0 have no ones # 1: set([0, 2]) # row 1 have ones in column 0 and 2 # 2: set([1, 2]) # 3: set([2]) # } cols_with_ones = defaultdict(set) for i in range(m): for j in range(n): if mat[i][j] == 1: cols_with_ones[i].add(j) def rows_covered(cols_choosen): covered = 0 for i in range(m): if len(cols_with_ones[i] - cols_choosen) == 0: covered += 1 return covered def backtrack(curr_col, cols_choosen): if len(cols_choosen) == cols: return rows_covered(cols_choosen) if curr_col == n: return 0 cols_choosen.add(curr_col) # choose current column v1 = backtrack(curr_col + 1, cols_choosen) cols_choosen.remove(curr_col) # skip current column v2 = backtrack(curr_col + 1, cols_choosen) return max(v1, v2) return backtrack(0, set())
maximum-rows-covered-by-columns
[Python3] Backtracing with sets
helnokaly
0
11
maximum rows covered by columns
2,397
0.525
Medium
32,750
https://leetcode.com/problems/maximum-rows-covered-by-columns/discuss/2525353/Back-tracking-to-find-best-combinations
class Solution: def maximumRows(self, mat: List[List[int]], cols: int) -> int: def fsol(v, k, n, m): vmin = 0 if k==0 else chk[v-1] + 1 vmax = n - k + v # print(v, vmin, vmax, chk) for i in range(vmin, vmax + 1): chk[v] = i if v == k-1: tt = [True] * m for jj in range(n): if jj not in chk: for ii in range(m): if mat[ii][jj]==1: tt[ii] = False ret = m for ii in range(m): if tt[ii] == False: ret = ret - 1 q[0] = max(q[0], ret) # print(chk, tt, ret) else: fsol(v + 1, k, n, m) chk[v] = -1 pass # print(cols) # print("\n".join([" ".join([str(i) for i in v]) for v in mat])) # print() q = [0] m, n = len(mat), len(mat[0]) chk = [-1] * n fsol(0, cols, n, m) ans = q[0] # print("ans:", ans) # print("=" * 20) return ans pass
maximum-rows-covered-by-columns
Back-tracking to find best combinations
dntai
0
9
maximum rows covered by columns
2,397
0.525
Medium
32,751
https://leetcode.com/problems/maximum-rows-covered-by-columns/discuss/2525189/Hard-Core-Brute-force-accepted-python3-solution
class Solution: def maximumRows(self, mat: List[List[int]], cols: int) -> int: if cols>=len(mat[0]): return len(mat) matrix =[] dup_matrix = [i for i in range(len(mat[0]))] print("dup_mat", dup_matrix) def generate(dup_matrix , cols , i , temp): if i == len(dup_matrix): temp.sort() if len(temp) == cols and temp not in matrix: matrix.append(temp) return return generate(dup_matrix , cols , i+1 , temp + [dup_matrix[i]]) generate(dup_matrix , cols , i+1 , temp ) generate(dup_matrix , cols , 0 , []) print("matrix", matrix) self.ans =0 def max_count(matrix ,covered): # covered = 0 for i in range(len(mat)): count = 0 for j in range(len(mat[0])): if mat[i][j] == 1 and j in matrix: count = count +1 if mat[i][j] == 0: count = count+1 print("count" , count ,len(mat)) if count == len(mat[0]): covered = covered+1 print("covered........................." , covered) self.ans = max(self.ans, covered) for i in range(len(matrix)): print("matrix", matrix[i]) max_count(matrix[i], 0) return self.ans
maximum-rows-covered-by-columns
Hard Core Brute force accepted python3 solution
Afzal543
0
12
maximum rows covered by columns
2,397
0.525
Medium
32,752
https://leetcode.com/problems/maximum-rows-covered-by-columns/discuss/2524820/Python-or-Combinations-%2B-Counter
class Solution: def maximumRows(self, mat: List[List[int]], cols: int) -> int: m = len(mat); n = len(mat[0]) if n <= cols: return m numberOfOnes = [Counter(row)[1] for row in mat] def numberOfCoveredRows(columns: List[int]) -> int: coveredRows = 0 for j, row in enumerate(mat): if Counter([row[i] for i in columns])[1] == numberOfOnes[j]: coveredRows += 1 return coveredRows maxCovered = 0 for combination in combinations(range(n), cols): coveredRows = numberOfCoveredRows(combination) if coveredRows == m: return m maxCovered = max(maxCovered, coveredRows) return maxCovered
maximum-rows-covered-by-columns
Python | Combinations + Counter
sr_vrd
0
29
maximum rows covered by columns
2,397
0.525
Medium
32,753
https://leetcode.com/problems/maximum-rows-covered-by-columns/discuss/2524799/Python3-enumeration
class Solution: def maximumRows(self, mat: List[List[int]], cols: int) -> int: m, n = len(mat), len(mat[0]) masks = [] for i in range(m): mask = reduce(xor, (1<<j for j in range(n) if mat[i][j]), 0) masks.append(mask) ans = 0 for x in range(1<<n): if x.bit_count() <= cols: ans = max(ans, sum(mask &amp; x == mask for mask in masks)) return ans
maximum-rows-covered-by-columns
[Python3] enumeration
ye15
0
33
maximum rows covered by columns
2,397
0.525
Medium
32,754
https://leetcode.com/problems/maximum-number-of-robots-within-budget/discuss/2526141/Python3-Intuition-Explained-or-Sliding-Window-or-Similar-Problems-Link
class Solution: def maximumRobots(self, chargeTimes: List[int], runningCosts: List[int], budget: int) -> int: n=len(chargeTimes) start=0 runningsum=0 max_consecutive=0 max_so_far=0 secondmax=0 for end in range(n): runningsum+=runningCosts[end] if max_so_far<=chargeTimes[end]: secondmax=max_so_far max_so_far=chargeTimes[end] k=end-start+1 currentbudget=max_so_far+(k*runningsum) if currentbudget>budget: runningsum-=runningCosts[start] max_so_far=secondmax if chargeTimes[start]==max_so_far else max_so_far start+=1 max_consecutive=max(max_consecutive,end-start+1) return max_consecutive
maximum-number-of-robots-within-budget
[Python3] Intuition Explained πŸ”₯ | Sliding Window | Similar Problems Link πŸš€
glimloop
1
61
maximum number of robots within budget
2,398
0.322
Hard
32,755
https://leetcode.com/problems/maximum-number-of-robots-within-budget/discuss/2536386/Python3-%2B-Sliding-Window-%2B-Max-Heap
class Solution: def maximumRobots(self, charge: List[int], cost: List[int], budget: int) -> int: res, add, start, mxheap = 0, 0, 0, [] heapify(mxheap) for end in range(len(charge)): add += cost[end] heappush(mxheap, (-1*charge[end], end)) while mxheap and -1*mxheap[0][0]+(end-start+1)*add > budget: add -= cost[start] while mxheap and mxheap[0][1] <= start: heappop(mxheap) start += 1 res = max(res, end-start+1) return res
maximum-number-of-robots-within-budget
Python3 + Sliding Window + Max Heap
leet_satyam
0
34
maximum number of robots within budget
2,398
0.322
Hard
32,756
https://leetcode.com/problems/maximum-number-of-robots-within-budget/discuss/2532148/Java-or-Python3-or-Beats-100-or-O(n)-or-Monotonic-Queue
class Solution: def maximumRobots(self, chargeTimes: List[int], runningCosts: List[int], budget: int) -> int: q = [] f, l, currSum, ans, n = 0, 0, 0, 0, len(chargeTimes) while (f < n): while (len(q) != 0 and chargeTimes[q[-1]] < chargeTimes[f]): q.pop() q.append(f) currSum += runningCosts[f] f += 1 while (l != f and chargeTimes[q[0]] + (f-l) * currSum > budget): if q[0] == l: q.pop(0) currSum -= runningCosts[l] l += 1 ans = max(ans, f-l) return ans
maximum-number-of-robots-within-budget
Java | Python3 | Beats 100% | O(n) | Monotonic Queue
DheerajGadwala
0
21
maximum number of robots within budget
2,398
0.322
Hard
32,757
https://leetcode.com/problems/maximum-number-of-robots-within-budget/discuss/2525438/Python-MaxHeap-%2B-prefix-Sum-Easy-understanding-Simple-Solution.
class Solution: def maximumRobots(self, chargeTimes: List[int], runningCosts: List[int], budget: int) -> int: i = 0 j = 0 maxi = 0 total = 0 maxHeap = [] heapq.heapify(maxHeap) prev = 0 maxj = 0 prefix = [0]*len(chargeTimes) while i<=j and j < len(chargeTimes): if total>=budget: maxHeap.remove(-1*chargeTimes[i]) i+=1 heapq.heappush(maxHeap,-1*chargeTimes[j]) prefix[j] = prev + runningCosts[j] prev = prefix[j] max_charge = -1*maxHeap[0] if i == 0 : running = prefix[j] elif i==j: running = runningCosts[j] else: running = prefix[j] -prefix[i-1] total = max_charge + (j-i+1) * running if total<=budget: maxi = max(maxi,j-i+1) j+=1 return maxi
maximum-number-of-robots-within-budget
Python MaxHeap + prefix Sum, Easy understanding, Simple Solution.
shashichintu
0
17
maximum number of robots within budget
2,398
0.322
Hard
32,758
https://leetcode.com/problems/maximum-number-of-robots-within-budget/discuss/2525281/Clean-Python3-or-Sliding-Window-and-Heap-or-O(nlogn)
class Solution: def maximumRobots(self, chargeTimes: List[int], runningCosts: List[int], budget: int) -> int: n, max_robots = len(chargeTimes), 0 max_charge = [] # max heap with tuples: (charge, index) running = runsum = 0 p1 = p2 = cost = 0 while p2 <= n: k = p2 - p1 if cost <= budget: max_robots = max(max_robots, k) if p2 == n: break # pop any charge times that are not in the current window while max_charge and max_charge[0][1] < p1: heapq.heappop(max_charge) if cost <= budget: # add the next robot if we are within budget heapq.heappush(max_charge, (-chargeTimes[p2], p2)) running += runsum + (k + 1) * runningCosts[p2] runsum += runningCosts[p2] cost = running - max_charge[0][0] # max heap stores negs p2 += 1 elif k == 1: p1 = p2 cost = running = runsum = 0 else: # shrink window if budget is exceeded while max_charge and max_charge[0][1] <= p1: heapq.heappop(max_charge) running -= runsum + (k - 1) * runningCosts[p1] runsum -= runningCosts[p1] cost = running - max_charge[0][0] p1 += 1 return max_robots
maximum-number-of-robots-within-budget
Clean Python3 | Sliding Window & Heap | O(nlogn)
ryangrayson
0
12
maximum number of robots within budget
2,398
0.322
Hard
32,759
https://leetcode.com/problems/maximum-number-of-robots-within-budget/discuss/2524778/Sliding-window-%2B-window-maximum-%2B-prefix-sum-O(N)
class Solution: def maximumRobots(self, time: List[int], cost: List[int], budget: int) -> int: prefix_sum = [0] S = 0 for v in cost: S += v prefix_sum.append(S) # print(prefix_sum) maxQ = deque() # slide window n = len(time) l = 0 ret = 0 # the window considered here is [l,r], boundary included for r in range(n): while len(maxQ) and time[r] > maxQ[-1]: maxQ.pop() maxQ.append(time[r]) k = r-l+1 tc = prefix_sum[r+1] - prefix_sum[l] # total cost mt = maxQ[0] # max time while l<=r and (mt + k*tc) > budget: if time[l] == maxQ[0]: maxQ.popleft() l += 1 if l > r: break k = r-l+1 tc = prefix_sum[r+1] - prefix_sum[l] mt = maxQ[0] ret = max(ret, r-l+1) return ret
maximum-number-of-robots-within-budget
Sliding window + window maximum + prefix sum, O(N)
LeonDong1993
0
12
maximum number of robots within budget
2,398
0.322
Hard
32,760
https://leetcode.com/problems/maximum-number-of-robots-within-budget/discuss/2524718/Python3-Binary-search
class Solution: def maximumRobots(self, chargeTimes: List[int], runningCosts: List[int], budget: int) -> int: def fn(k): """Return min cost of running k consecutive robots.""" if k == 0: return 0 ans = inf sm = 0 pq = [] for i, (ct, rc) in enumerate(zip(chargeTimes, runningCosts)): sm += rc heappush(pq, (-ct, i)) if i >= k: sm -= runningCosts[i-k] while pq[0][1] <= i-k: heappop(pq) if i >= k-1: ans = min(ans, -pq[0][0] + k*sm) return ans lo, hi = 0, len(chargeTimes) while lo < hi: mid = lo + hi + 1 >> 1 if fn(mid) <= budget: lo = mid else: hi = mid - 1 return lo
maximum-number-of-robots-within-budget
[Python3] Binary search
ye15
0
31
maximum number of robots within budget
2,398
0.322
Hard
32,761
https://leetcode.com/problems/maximum-number-of-robots-within-budget/discuss/2524718/Python3-Binary-search
class Solution: def maximumRobots(self, chargeTimes: List[int], runningCosts: List[int], budget: int) -> int: ii = rsm = 0 qq = deque() for i, (ct, rc) in enumerate(zip(chargeTimes, runningCosts)): rsm += rc while qq and qq[-1][0] <= ct: qq.pop() qq.append((ct, i)) if chargeTimes[qq[0][1]] + (i - ii + 1) * rsm > budget: if qq[0][1] == ii: qq.popleft() rsm -= runningCosts[ii] ii += 1 return len(chargeTimes)-ii
maximum-number-of-robots-within-budget
[Python3] Binary search
ye15
0
31
maximum number of robots within budget
2,398
0.322
Hard
32,762
https://leetcode.com/problems/check-distances-between-same-letters/discuss/2531135/Python3-oror-3-lines-TM%3A-36ms13.8MB
class Solution: # Pretty much explains itself. def checkDistances(self, s: str, distance: List[int]) -> bool: d = defaultdict(list) for i, ch in enumerate(s): d[ch].append(i) return all(b-a-1 == distance[ord(ch)-97] for ch, (a,b) in d.items())
check-distances-between-same-letters
Python3 || 3 lines, T/M: 36ms/13.8MB
warrenruud
8
596
check distances between same letters
2,399
0.704
Easy
32,763
https://leetcode.com/problems/check-distances-between-same-letters/discuss/2527598/Python-Dictionary-oror-Easy-to-understand
class Solution: def checkDistances(self, s: str, distance: List[int]) -> bool: hashmap = {} for i in range(len(s)): if s[i] in hashmap and i - hashmap[s[i]] - 1 != distance[ord(s[i]) - ord('a')]: return False hashmap[s[i]] = i return True
check-distances-between-same-letters
Python Dictionary || Easy to understand
fight2022
5
285
check distances between same letters
2,399
0.704
Easy
32,764
https://leetcode.com/problems/check-distances-between-same-letters/discuss/2596604/Python-Solution-or-Easy-Understanding
class Solution: def mapper(self, s): # finds difference of indices result = dict() for letter in set(s): indices = [] for idx, value in enumerate(s): if value == letter: indices.append(idx) result[letter] = indices[1] - indices[0] - 1 return result # dict like {'a':1, 'b':0} def checkDistances(self, s, distance) -> bool: alphabet = 'abcdefghijklmnopqrstuvwxyz' for key, value in self.mapper(s).items(): if distance[alphabet.index(key)] != value: return False return True
check-distances-between-same-letters
Python Solution | Easy Understanding
cyber_kazakh
1
42
check distances between same letters
2,399
0.704
Easy
32,765
https://leetcode.com/problems/check-distances-between-same-letters/discuss/2529388/Python-oror-iterative-oror-Easy
class Solution: def checkDistances(self, s: str, distance: List[int]) -> bool: n = len(s) for i in range(n-1): for j in range(i+1,n): if s[i] == s[j]: if distance[ord(s[i]) - 97] != (j - i - 1): return False else: break return True
check-distances-between-same-letters
Python || iterative || Easy
1md3nd
1
51
check distances between same letters
2,399
0.704
Easy
32,766
https://leetcode.com/problems/check-distances-between-same-letters/discuss/2786345/python3-98.8-89-easy
class Solution: def checkDistances(self, s: str, distance: List[int]) -> bool: seen = defaultdict(int) for i , c in enumerate(s): if c not in seen: seen[c] = i elif (i - seen[c])-1 != distance[ord(c)-97]: return False return True
check-distances-between-same-letters
python3 98.8% 89% easy
1ncu804u
0
4
check distances between same letters
2,399
0.704
Easy
32,767
https://leetcode.com/problems/check-distances-between-same-letters/discuss/2746443/Python-O(N)
class Solution: def checkDistances(self, s: str, distance: List[int]) -> bool: arr = list(s) hash = {} hash2 = {} for i in range(0, 26): hash2[chr(97+i)] = i for i in range(len(arr)): if arr[i] not in hash: hash[arr[i]] = i else: hash[arr[i]] = i - hash[arr[i]] - 1 for x in hash: if hash[x] != distance[hash2[x]]: return False return True
check-distances-between-same-letters
Python O(N)
Hurley2017
0
4
check distances between same letters
2,399
0.704
Easy
32,768
https://leetcode.com/problems/check-distances-between-same-letters/discuss/2745383/Easy-Python-Solution-Using-Dictionary-and-Absolute-Value
class Solution: def checkDistances(self, s: str, distance: List[int]) -> bool: dic = {} for i,w in enumerate(s): if w in dic: dic[w].append(i) else: dic[w] = [i] for key, val in dic.items(): if abs(val[0] - val[-1])-1 != distance[ord(key)-97]: return False return True
check-distances-between-same-letters
Easy Python Solution Using Dictionary and Absolute Value
jacobsimonareickal
0
8
check distances between same letters
2,399
0.704
Easy
32,769
https://leetcode.com/problems/check-distances-between-same-letters/discuss/2693642/Python3-No-additional-memory-with-single-pass
class Solution: def checkDistances(self, s: str, distance: List[int]) -> bool: # go through the letters and check whether we find the # second one as noted. We use the distance array to # mark letters we have visited for idx, char in enumerate(s): # check the distance dist = distance[ord(char)-ord('a')] # check that we have not yet visited if dist >= 0: # check whether our character is well spaced if idx+dist+1 < len(s) and s[idx+dist+1] == char: # mark the letter a visited distance[ord(char)-ord('a')] = -1 else: return False return True
check-distances-between-same-letters
[Python3] - No additional memory with single pass
Lucew
0
5
check distances between same letters
2,399
0.704
Easy
32,770
https://leetcode.com/problems/check-distances-between-same-letters/discuss/2547130/Python-runtime-O(n)-memory-O(n)
class Solution: def checkDistances(self, s: str, distance: List[int]) -> bool: d = {} for i in range(len(s)): if s[i] not in d: d[s[i]] = [i] else: d[s[i]].append(i) for e in d.keys(): dis = d[e][1] - d[e][0] - 1 if distance[ord(e)-ord('a')] != dis: return False return True
check-distances-between-same-letters
Python, runtime O(n), memory O(n)
tsai00150
0
42
check distances between same letters
2,399
0.704
Easy
32,771
https://leetcode.com/problems/check-distances-between-same-letters/discuss/2534137/One-pass-and-list-for-seen-chars-71-speed
class Solution: def checkDistances(self, s: str, distance: List[int]) -> bool: seen = [False] * 26 for i, c in enumerate(map(lambda x: ord(x) - 97, s)): if seen[c]: if distance[c] != i - 1: return False else: distance[c] += i seen[c] = True return True
check-distances-between-same-letters
One pass and list for seen chars, 71% speed
EvgenySH
0
13
check distances between same letters
2,399
0.704
Easy
32,772
https://leetcode.com/problems/check-distances-between-same-letters/discuss/2529909/Simpler-Python-Solution
class Solution: def checkDistances(self, s: str, distance: List[int]) -> bool: map = dict(zip(string.ascii_lowercase, range(26))) s_map = defaultdict(list) for key, val in enumerate(s): s_map[val].append(key) for char in s_map.keys(): tmp = s_map[char][-1] - s_map[char][0] if not distance[map[char]] == tmp - 1: return False return True
check-distances-between-same-letters
Simpler Python Solution
blazers08
0
17
check distances between same letters
2,399
0.704
Easy
32,773
https://leetcode.com/problems/check-distances-between-same-letters/discuss/2529658/Easy-Python-Solution-With-Dictionary
class Solution: def checkDistances(self, s: str, distance: List[int]) -> bool: d=defaultdict(list) for i in range(len(s)): d[s[i]].append(i) l=[0]*26 for i,j in d.items(): l[ord(i)-97]=(j[1]-j[0]-1) n=len(set(s)) for j in range(len(distance)): if chr(97+j) not in s: distance[j]=0 return l==distance
check-distances-between-same-letters
Easy Python Solution With Dictionary
a_dityamishra
0
16
check distances between same letters
2,399
0.704
Easy
32,774
https://leetcode.com/problems/check-distances-between-same-letters/discuss/2528363/Easy-to-understand-Python-Soln
class Solution: def checkDistances(self, s: str, distance: List[int]) -> bool: indexes = collections.defaultdict(list) for k,v in enumerate(s): newChar = ord(v) indexes[newChar].append(k) for i in range(len(distance)): newValue = i + 97 if not indexes[newValue]: continue value1, value2 = indexes[newValue] num = value2 - value1 if (num - 1) != distance[i]: return False return True
check-distances-between-same-letters
Easy to understand Python Soln
113377code
0
32
check distances between same letters
2,399
0.704
Easy
32,775
https://leetcode.com/problems/check-distances-between-same-letters/discuss/2527830/Python
class Solution: def checkDistances(self, s: str, distance: List[int]) -> bool: idx = {} for i, c in enumerate(s): if c in idx: if i - idx[c] - 1 != distance[ord(c) - ord('a')]: return False else: idx[c] = i return True
check-distances-between-same-letters
Python
blue_sky5
0
31
check distances between same letters
2,399
0.704
Easy
32,776
https://leetcode.com/problems/check-distances-between-same-letters/discuss/2527530/Readable-python3-or-Find-location-of-first-occurrence-verify-next-appears-after-k-positions
class Solution: def checkDistances(self, s: str, distance: List[int]) -> bool: total = len(s) for index, character_distance in enumerate(distance): character_distance += 1 character = chr(index + ord('a')) location = s.find(character) next_location = location + character_distance if location != -1 and (next_location >= total or s[next_location] != character): return False return True
check-distances-between-same-letters
Readable python3 | Find location of first occurrence, verify next appears after k positions
_snake_case
0
19
check distances between same letters
2,399
0.704
Easy
32,777
https://leetcode.com/problems/check-distances-between-same-letters/discuss/2527471/Either-use-indexing-or-use-dictionary-oror-Python-oror-Simplest-Solution-oror
class Solution: def checkDistances(self, s: str, distance: List[int]) -> bool: length = len(s) for ch in s: left = s.find(ch) right = length - (s[::-1].find(ch)) -1 s.replace(ch, "") if (right - left - 1) != (distance[ord(ch) -97 ]): return False return True
check-distances-between-same-letters
🟒 Either use indexing or use dictionary || Python || Simplest Solution ||
NITIN_DS
0
17
check distances between same letters
2,399
0.704
Easy
32,778
https://leetcode.com/problems/check-distances-between-same-letters/discuss/2527471/Either-use-indexing-or-use-dictionary-oror-Python-oror-Simplest-Solution-oror
class Solution: def checkDistances(self, s: str, distance: List[int]) -> bool: d1 = {} for i in range(len(s)): if s[i] not in d1.keys(): d1[ s[i] ] = i else: if (i - d1[ s[i] ] - 1) != (distance[ord(s[i]) -97 ]) : return False return True
check-distances-between-same-letters
🟒 Either use indexing or use dictionary || Python || Simplest Solution ||
NITIN_DS
0
17
check distances between same letters
2,399
0.704
Easy
32,779
https://leetcode.com/problems/check-distances-between-same-letters/discuss/2527369/Python-Simple-Python-Solution-Using-Dictionary-or-HashMap
class Solution: def checkDistances(self, s: str, distance: List[int]) -> bool: d = {} for i in range(len(s)): if s[i] not in d: d[s[i]] = [i] else: d[s[i]].append(i) d = dict(sorted(d.items(), key = lambda x : x[0])) for i in d: difference = d[i][1] - d[i][0] - 1 index = ord(i) - 97 if distance[index] != difference: return False return True
check-distances-between-same-letters
[ Python ] βœ…βœ… Simple Python Solution Using Dictionary | HashMapπŸ₯³βœŒπŸ‘
ASHOK_KUMAR_MEGHVANSHI
0
37
check distances between same letters
2,399
0.704
Easy
32,780
https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/discuss/2554923/Python3-oror-3-lines-combs-w-explanation-oror-TM%3A-9692
class Solution: # A few points on the problem: # β€’ The start and end is a "red herring." The answer to the problem # depends only on the distance (dist = end-start) and k. # # β€’ A little thought will convince one that theres no paths possible # if k%2 != dist%2 or if abs(dist) > k. # β€’ The problem is equivalent to: # Determine the count of distinct lists of length k with sum = dist # and elements 1 and -1, in which the counts of 1s and -1s in each # list differ by dist. # # β€’ The count of the lists is equal to the number of ways the combination # C((k, (dist+k)//2)). For example, if dist = 1 and k = 5. the count of 1s #. is (5+1)//2 = 3, and C(5,3) = 10. # (Note that if dist= -1 in this example, (5-1)//2 = 2, and C(5,2) = 10) def numberOfWays(self, startPos: int, endPos: int, k: int) -> int: dist = endPos-startPos if k%2 != dist%2 or abs(dist) > k: return 0 return comb(k, (dist+k)//2) %1000000007
number-of-ways-to-reach-a-position-after-exactly-k-steps
Python3 || 3 lines, combs, w/ explanation || T/M: 96%/92%
warrenruud
3
157
number of ways to reach a position after exactly k steps
2,400
0.323
Medium
32,781
https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/discuss/2533891/DP-or-Recursion-oror-Memoization-oror-Python3
class Solution(object): def numberOfWays(self, startPos, endPos, k): """ :type startPos: int :type endPos: int :type k: int :rtype: int """ MOD=1e9+7 dp={} def A(currpos,k): if (currpos,k) in dp: return dp[(currpos,k)] #base case if currpos==endPos and k==0: return 1 #base case if k<=0: return 0 ans1,ans2=0,0 #move left ans1+=A(currpos-1,k-1) #move right ans2+=A(currpos+1,k-1) #sum of left + right possibilities dp[(currpos,k)]=(ans1+ans2)%MOD #return the result return dp[(currpos,k)] return int(A(startPos,k)%MOD) ```
number-of-ways-to-reach-a-position-after-exactly-k-steps
DP }| Recursion || Memoization || Python3
srikarsai550
2
21
number of ways to reach a position after exactly k steps
2,400
0.323
Medium
32,782
https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/discuss/2848349/Python-easy-to-read-and-understand-or-recursion-%2B-memoization
class Solution: def dfs(self, s, e, k): if k == 0: if s == e: return 1 return 0 return self.dfs(s+1, e, k-1) + self.dfs(s-1, e, k-1) def numberOfWays(self, startPos: int, endPos: int, k: int) -> int: return self.dfs(startPos, endPos, k) % (10**9 + 7)
number-of-ways-to-reach-a-position-after-exactly-k-steps
Python easy to read and understand | recursion + memoization
sanial2001
0
1
number of ways to reach a position after exactly k steps
2,400
0.323
Medium
32,783
https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/discuss/2848349/Python-easy-to-read-and-understand-or-recursion-%2B-memoization
class Solution: def dfs(self, s, e, k): if k <= 0: if k == 0 and s == e: return 1 return 0 if (s, k) in self.d: return self.d[(s, k)] self.d[(s, k)] = self.dfs(s+1, e, k-1) + self.dfs(s-1, e, k-1) return self.d[(s, k)] def numberOfWays(self, startPos: int, endPos: int, k: int) -> int: self.d = {} return self.dfs(startPos, endPos, k) % (10**9 + 7)
number-of-ways-to-reach-a-position-after-exactly-k-steps
Python easy to read and understand | recursion + memoization
sanial2001
0
1
number of ways to reach a position after exactly k steps
2,400
0.323
Medium
32,784
https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/discuss/2842609/Simple-Python3-Math-Explained
class Solution: def numberOfWays(self, start: int, end: int, k: int) -> int: d = abs(start - end) if (k + d) % 2: return 0 r = (k + d) // 2 return math.comb(k, r) % (10**9 + 7)
number-of-ways-to-reach-a-position-after-exactly-k-steps
Simple Python3 Math Explained
ryangrayson
0
4
number of ways to reach a position after exactly k steps
2,400
0.323
Medium
32,785
https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/discuss/2821115/Python-simple-recursive-solution
class Solution: def numberOfWays(self, startPos: int, endPos: int, k: int) -> int: cache = {} def findWays(pos, k): if (pos, k) in cache: return cache[(pos, k)] if k == 0: return pos == endPos res = findWays(pos+1, k-1)+findWays(pos-1, k-1) cache[(pos, k)] = res return res return findWays(startPos, k)%(10**9+7)
number-of-ways-to-reach-a-position-after-exactly-k-steps
Python simple recursive solution
ankurkumarpankaj
0
1
number of ways to reach a position after exactly k steps
2,400
0.323
Medium
32,786
https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/discuss/2811166/Python-(Simple-Maths)
class Solution: def numberOfWays(self, startPos, endPos, k): res = [1]*abs(endPos - startPos) rem_k = k - abs(endPos - startPos) if rem_k%2 != 0 or rem_k < 0: return 0 res = res + [1]*(rem_k//2) + [-1]*(rem_k//2) dict1 = Counter(res) final_ans = math.comb(sum(dict1.values()),dict1[1]) return final_ans%(10**9+7)
number-of-ways-to-reach-a-position-after-exactly-k-steps
Python (Simple Maths)
rnotappl
0
3
number of ways to reach a position after exactly k steps
2,400
0.323
Medium
32,787
https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/discuss/2811156/Python-(Simple-Maths)
class Solution: def numberOfWays(self, startPos, endPos, k): res = [1]*abs(endPos - startPos) rem_k = k - abs(endPos - startPos) if rem_k%2 != 0 or rem_k < 0: return 0 res = res + [1]*(rem_k//2) + [-1]*(rem_k//2) dict1 = Counter(res) final_ans = math.factorial(sum(dict1.values()))//(math.factorial(dict1[1])*math.factorial(dict1[-1])) return final_ans%(10**9+7)
number-of-ways-to-reach-a-position-after-exactly-k-steps
Python (Simple Maths)
rnotappl
0
2
number of ways to reach a position after exactly k steps
2,400
0.323
Medium
32,788
https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/discuss/2729637/Python3-Solution-or-2-Line-Solution
class Solution: def numberOfWays(self, S, E, K): D = K - abs(E - S) return 0 if D < 0 or D &amp; 1 else math.comb(K, D // 2) % (10 ** 9 + 7)
number-of-ways-to-reach-a-position-after-exactly-k-steps
βœ” Python3 Solution | 2 Line Solution
satyam2001
0
5
number of ways to reach a position after exactly k steps
2,400
0.323
Medium
32,789
https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/discuss/2557593/Simple-maths-python-easy-readable-code-with-comments
class Solution: def numberOfWays(self, startPos: int, endPos: int, k: int) -> int: # just two equations # 1. left+right=k i.e. sum of left and right steps should be k. # 2. right-left=endpos-startpos i.e. diff b/w right and left steps should be equal to final-startpos. total_steps=k dif_r_l_step=endPos-startPos r_step=(total_steps+dif_r_l_step)//2 r_step2=(total_steps+dif_r_l_step)/2 if r_step!=r_step2: return 0 return comb(total_steps,(r_step))%(10**9+7)
number-of-ways-to-reach-a-position-after-exactly-k-steps
Simple maths , python , easy readable code with comments
Aniket_liar07
0
60
number of ways to reach a position after exactly k steps
2,400
0.323
Medium
32,790
https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/discuss/2553718/python-or-top_down-and-bottom-up-or-explanation-in-comments
class Solution: MOD = 1000000007 def top_down(self, step: int, dist: int) -> int: if dist >= step : return int(step == dist) if self.memo[step][dist] == 0: self.memo[step][dist] = 1 + self.top_down(step - 1, abs(dist - 1)) + self.top_down(step - 1, dist + 1) self.memo[step][dist] = self.memo[step][dist] % Solution.MOD return self.memo[step][dist] - 1 def bottom_up(self, steps: int, dist: int) -> int: prev, curr = None, [] for k in range(steps + 1): for d in range(k + 1): # there is only 1 possible way to cover a distance of 'd' in 'k' steps if d == k: curr.append(1) # if distance was plotted on the x-axis, this is to account for approaching from the -ve part of x-axis elif d == 0: num_ways = 2 * prev[1] if k > 1 else 0 curr.append(num_ways % Solution.MOD) # it is only possible to cover distance 'd' in 'k' steps if 'k' is atleast as big as 'd' elif d <= k: num_ways = prev[d - 1] num_ways += prev[d + 1] if d + 1 < len(prev) else 0 curr.append(num_ways % Solution.MOD) prev = curr curr = [] res = prev[dist] if dist <= k else 0 return res def numberOfWays(self, startPos: int, endPos: int, k: int, is_top_down: bool = False) -> int: if is_top_down: # declare memo self.memo = [[0] * 1001 for _ in range(1001)] # get number of ways to cover distance 'd' (endPos - startPos) res = self.top_down(k, abs(endPos - startPos)) else: res = self.bottom_up(k, abs(endPos - startPos)) return res
number-of-ways-to-reach-a-position-after-exactly-k-steps
python | top_down and bottom-up | explanation in comments
sproq
0
60
number of ways to reach a position after exactly k steps
2,400
0.323
Medium
32,791
https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/discuss/2547198/Python-runtime-O(n)-memory-O(n)-with-simple-math
class Solution: def numberOfWays(self, startPos: int, endPos: int, k: int) -> int: dis = endPos - startPos if k-abs(dis) < 0 or (k-dis)%2 == 1: return 0 if k-abs(dis) == 0: return 1 if dis >= 0: left = self.getWays((k-dis)//2) right = self.getWays((k-dis)//2 + dis) else: left = self.getWays((k+dis)//2 - dis) right = self.getWays((k+dis)//2) return (self.getWays(k) // (left*right)) % (10**9+7) def getWays(self, n): s = 1 for i in range(1, n+1): s *= i print(s) return s
number-of-ways-to-reach-a-position-after-exactly-k-steps
Python, runtime O(n), memory O(n) with simple math
tsai00150
0
57
number of ways to reach a position after exactly k steps
2,400
0.323
Medium
32,792
https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/discuss/2530471/Python3-combinations-Quick-Math
class Solution: def numberOfWays(self, startPos: int, endPos: int, k: int) -> int: distance = endPos - startPos if (k - distance) % 2 == 1 or distance > k: return 0 else: choose = (k - distance) // 2 # k choose (k - distance) // 2 res = 1 for t in range(k - choose + 1, k+1): res *= t for t in range(choose, 0, -1): res //= t return res % (10**9 + 7)
number-of-ways-to-reach-a-position-after-exactly-k-steps
Python3 combinations Quick Math
xxHRxx
0
5
number of ways to reach a position after exactly k steps
2,400
0.323
Medium
32,793
https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/discuss/2528013/Math-explained-or-Python-or-permutation-and-combination
class Solution: def numberOfWays(self, startPos: int, endPos: int, k: int) -> int: D = abs(endPos-startPos) if D>k or (k+D)%2!=0: return 0 mod = 10**9 + 7 def fact(n,lower): if n <= lower: return 1 return (n * fact(n - 1, lower)) f = (D + k)//2 b = k- f ans = comb(k,f) return int(ans%mod)
number-of-ways-to-reach-a-position-after-exactly-k-steps
Math explained | Python | permutation and combination
mync
0
20
number of ways to reach a position after exactly k steps
2,400
0.323
Medium
32,794
https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/discuss/2527594/O(k2)-with-bfs-%2B-two-queues-%2B-hashmap-(Illustration-by-Examples)
class Solution: def numberOfWays(self, startPos: int, endPos: int, k: int) -> int: mod = 10**9 + 7 q1 = {startPos: 1} for i in range(1, k + 1): q2 = {} for di in q1: q2[di-1] = q2.get(di-1, 0) + q1[di] q2[di+1] = q2.get(di+1, 0) + q1[di] q1 = q2 ans = q1.get(endPos, 0) % mod return ans
number-of-ways-to-reach-a-position-after-exactly-k-steps
O(k^2) with bfs + two queues + hashmap (Illustration by Examples)
dntai
0
37
number of ways to reach a position after exactly k steps
2,400
0.323
Medium
32,795
https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/discuss/2527428/8-lines-Python-DP-with-lru_cache-(includes-TLE-BFS-approach-as-well)
class Solution: def numberOfWays(self, startPos: int, endPos: int, k: int) -> int: @lru_cache(maxsize=None) def dfs(position, moves): if moves == k: return int(position == endPos) if abs(position - endPos) > k-moves: return 0 return dfs(position+1, moves+1) + dfs(position-1, moves+1) return (dfs(startPos+1, 1) + dfs(startPos-1, 1)) % (10**9 + 7)
number-of-ways-to-reach-a-position-after-exactly-k-steps
8 lines Python DP with lru_cache (includes TLE BFS approach as well)
_snake_case
0
43
number of ways to reach a position after exactly k steps
2,400
0.323
Medium
32,796
https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/discuss/2527428/8-lines-Python-DP-with-lru_cache-(includes-TLE-BFS-approach-as-well)
class Solution: def numberOfWays(self, startPos: int, endPos: int, k: int) -> int: ways = 0 if k == 0: return 1 if startPos == endPos else 0 queue = collections.deque() queue.append((startPos+1, 1)) queue.append((startPos-1, 1)) while queue: position, moves = queue.popleft() if abs(position - endPos) > k-moves: continue if moves == k: ways += int(position == endPos) continue queue.append((position+1, moves+1)) queue.append((position-1, moves+1)) return ways
number-of-ways-to-reach-a-position-after-exactly-k-steps
8 lines Python DP with lru_cache (includes TLE BFS approach as well)
_snake_case
0
43
number of ways to reach a position after exactly k steps
2,400
0.323
Medium
32,797
https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/discuss/2527390/Python-or-Traditional-top-down-DP
class Solution: def numberOfWays(self, startPos: int, endPos: int, k: int) -> int: if abs(startPos - endPos) > k: return 0 @cache def dp(currentPosition: int = startPos, stepsAvailable: int = k) -> int: if stepsAvailable == 0: return 1 if currentPosition == endPos else 0 numWays = dp(currentPosition + 1, stepsAvailable - 1) + dp(currentPosition - 1, stepsAvailable - 1) return numWays % (10 ** 9 + 7) return dp()
number-of-ways-to-reach-a-position-after-exactly-k-steps
Python | Traditional top -down DP
sr_vrd
0
30
number of ways to reach a position after exactly k steps
2,400
0.323
Medium
32,798
https://leetcode.com/problems/longest-nice-subarray/discuss/2527285/Bit-Magic-with-Explanation-and-Complexities
class Solution: def longestNiceSubarray(self, nums: List[int]) -> int: maximum_length = 1 n = len(nums) current_group = 0 left = 0 for right in range(n): # If the number at the right point is safe to include, include it in the group and update the maximum length. if nums[right] &amp; current_group == 0: current_group |=nums[right] maximum_length = max(maximum_length, right - left + 1) continue # Shrink the window until the number at the right pointer is safe to include. while left < right and nums[right] &amp; current_group != 0: current_group &amp;= (~nums[left]) left += 1 # Include the number at the right pointer in the group. current_group |= nums[right] return maximum_length
longest-nice-subarray
Bit Magic with Explanation and Complexities
wickedmishra
19
488
longest nice subarray
2,401
0.48
Medium
32,799