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/duplicate-zeros/discuss/1604969/Clean-Python-Solution | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
adjust = 0
for index, number in enumerate(arr[:]):
if not number:
arr.insert(index + adjust, 0)
arr.pop()
adjust += 1 | duplicate-zeros | Clean Python Solution | migash | 0 | 93 | duplicate zeros | 1,089 | 0.515 | Easy | 17,300 |
https://leetcode.com/problems/duplicate-zeros/discuss/1488295/Python-3-Simple | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
i = 0
while (i < len(arr)):
if (arr[i] == 0):
arr.pop() #Delete last element when you counter a 0
arr.insert(i+1, 0) #insert a 0 in the next index
i += 1 # skip the 0 that you just added
i += 1 | duplicate-zeros | Python 3 Simple | huangzi234 | 0 | 219 | duplicate zeros | 1,089 | 0.515 | Easy | 17,301 |
https://leetcode.com/problems/duplicate-zeros/discuss/1476349/Simple-Python-Solution | class Solution:
def duplicateZeros(self, arr: list) -> None:
temp=-1
for idx,num in enumerate(arr):
if num==0 and temp!=idx:
temp=idx+1
arr.pop()
arr.insert(idx,0) | duplicate-zeros | Simple Python Solution | 1_d99 | 0 | 139 | duplicate zeros | 1,089 | 0.515 | Easy | 17,302 |
https://leetcode.com/problems/duplicate-zeros/discuss/1229353/Python-Solution-with-extra-array-and-without-extra-Array | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
extra_arr = []
i = 0
j=0
while j<len(arr):
extra_arr.append(arr[i])
if arr[i]==0:
j+=1
extra_arr.append(0)
i+=1
j+=1
for i in range(len(arr)):
arr[i] = extra_arr[i] | duplicate-zeros | [Python] Solution with extra array and without extra Array | arkumari2000 | 0 | 225 | duplicate zeros | 1,089 | 0.515 | Easy | 17,303 |
https://leetcode.com/problems/duplicate-zeros/discuss/1229353/Python-Solution-with-extra-array-and-without-extra-Array | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
n=len(arr)
i=0
while i<n:
if arr[i]==0:
arr.insert(i+1,0)
i+=1
i+=1
diff = len(arr)-n
while diff!=0:
arr.pop()
diff -=1 | duplicate-zeros | [Python] Solution with extra array and without extra Array | arkumari2000 | 0 | 225 | duplicate zeros | 1,089 | 0.515 | Easy | 17,304 |
https://leetcode.com/problems/duplicate-zeros/discuss/1157080/Python3-why-is-my-arr-is-returned-incorrectly-when-print()-shows-it-correct | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
idx, length = 0, len(arr)
while idx < length:
print(arr)
if arr[idx] == 0:
arr = arr[:idx]+[0]+arr[idx:-1]
idx+=2
else:
idx+=1 | duplicate-zeros | Python3 why is my arr is returned incorrectly when print() shows it correct? | CerBerUs9 | 0 | 46 | duplicate zeros | 1,089 | 0.515 | Easy | 17,305 |
https://leetcode.com/problems/duplicate-zeros/discuss/1124429/Python-OneLiner | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
arr = [int(x) for x in
"".join([str(s) for s in arr]).replace('0', '00')][0:len(arr)]
# Compiler doesn't pick it up correctly but you can run a print(arr) statement to check result. | duplicate-zeros | Python - OneLiner | user0264Wr | 0 | 123 | duplicate zeros | 1,089 | 0.515 | Easy | 17,306 |
https://leetcode.com/problems/duplicate-zeros/discuss/1115980/very-easy-way-to-finish-the-problem | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
items = len(arr)
item = 0
flag = False
while item <= items-1:
if arr[item] == 0:
arr.insert(item + 1, 0)
del arr[-1]
flag = True
item += 1
if flag: | duplicate-zeros | very easy way to finish the problem | shreeyansh | 0 | 180 | duplicate zeros | 1,089 | 0.515 | Easy | 17,307 |
https://leetcode.com/problems/duplicate-zeros/discuss/1087138/Slow-(45)-but-simple-solution | class Solution:
def duplicateZeros(self, arr: list[int]) -> None:
i = 0
starting_len = len(arr) # this is used to remove all elements that exceed the starting len of arr
while i < len(arr):
if arr[i] == 0:
arr.insert(i + 1, 0) # inserts a 0 one place after the first 0
i += 2 # this is to stop infinitely adding 0 because it will keep adding 0 and finding that 0 next loop
else:
i += 1 # goes to next loop
while len(arr) > starting_len: # loops until it's the same len as it started with
arr.pop(-1) # removes the last element of array | duplicate-zeros | Slow (45%) but simple solution | Jamie_2345 | 0 | 93 | duplicate zeros | 1,089 | 0.515 | Easy | 17,308 |
https://leetcode.com/problems/duplicate-zeros/discuss/632734/JavaPython3-two-pointers | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
i, k = len(arr), len(arr) + arr.count(0)
while (i:=i-1) < (k:=k-1):
if k < len(arr): arr[k] = arr[i]
if arr[i] == 0:
if (k:=k-1) < len(arr): arr[k] = arr[i] | duplicate-zeros | [Java/Python3] two pointers | ye15 | 0 | 148 | duplicate zeros | 1,089 | 0.515 | Easy | 17,309 |
https://leetcode.com/problems/duplicate-zeros/discuss/632734/JavaPython3-two-pointers | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
zeros = arr.count(0)
for i in reversed(range(len(arr))):
if i + zeros < len(arr):
arr[i+zeros] = arr[i]
if arr[i] == 0:
zeros -= 1
if i + zeros < len(arr):
arr[i+zeros] = arr[i] | duplicate-zeros | [Java/Python3] two pointers | ye15 | 0 | 148 | duplicate zeros | 1,089 | 0.515 | Easy | 17,310 |
https://leetcode.com/problems/duplicate-zeros/discuss/618603/56-ms-faster-than-99.64-and-14.4-MB-less-than-100.00-of-Python3 | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
i = 0
while i < len(arr):
if arr[i] == 0:
arr.insert(i,0)
arr.pop()
i+=2
else:
i += 1 | duplicate-zeros | 56 ms, faster than 99.64% and 14.4 MB, less than 100.00% of Python3 | zastavropoulos | 0 | 98 | duplicate zeros | 1,089 | 0.515 | Easy | 17,311 |
https://leetcode.com/problems/duplicate-zeros/discuss/507301/Python-Simple-One-Pass-Deque-Solution-O(n)-time-and-space | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
from collections import deque
i, queue = 0, deque()
array_length = len(arr)
while i < array_length:
if queue:
queue.append(arr[i])
arr[i] = queue.popleft()
if arr[i] == 0 and i + 1 < array_length:
queue.append(arr[i + 1])
i += 1
arr[i] = 0
i += 1
return arr | duplicate-zeros | Python Simple One Pass Deque Solution - O(n) time and space | zachtheclimber | 0 | 156 | duplicate zeros | 1,089 | 0.515 | Easy | 17,312 |
https://leetcode.com/problems/duplicate-zeros/discuss/456355/Simple-Python3-solution-with-list-comprehension-(68-ms) | class Solution:
def duplicateZeros(self, arr):
"""
Do not return anything, modify arr in-place instead.
"""
N = len(arr)
indices = [ idx for idx, val in enumerate(arr) if val==0 ]
for idx in reversed(indices):
arr.insert(idx,0)
arr[:] = arr[0:N] | duplicate-zeros | Simple Python3 solution with list comprehension (68 ms) | vietspaceanh | 0 | 64 | duplicate zeros | 1,089 | 0.515 | Easy | 17,313 |
https://leetcode.com/problems/duplicate-zeros/discuss/382626/Solution-in-Python-3-(beats-~100)-(five-lines) | class Solution:
def duplicateZeros(self, a: List[int]) -> None:
L, i = len(a), 0
while i < L:
if not a[i]:
i, _, _= i + 1, a.pop(), a.insert(i,0)
i += 1
- Junaid Mansuri
(LeetCode ID)@hotmail.com | duplicate-zeros | Solution in Python 3 (beats ~100%) (five lines) | junaidmansuri | 0 | 436 | duplicate zeros | 1,089 | 0.515 | Easy | 17,314 |
https://leetcode.com/problems/duplicate-zeros/discuss/377356/100-space-O(n)-based-on-shift | class Solution(object):
def duplicateZeros(self, arr):
"""
:type arr: List[int]
:rtype: None Do not return anything, modify arr in-place instead.
"""
if len(arr) == 1:
return arr
shift = 0
new_elements = [0] * len(arr)
for idx, ele in enumerate(arr):
if ele == 0:
shift += 1
if idx+ shift < len(arr):
new_elements[idx + shift] = ele
i = 0
while i < len(arr):
arr[i] = new_elements[i]
i += 1 | duplicate-zeros | 100% space, O(n), based on shift | xavloc | 0 | 133 | duplicate zeros | 1,089 | 0.515 | Easy | 17,315 |
https://leetcode.com/problems/duplicate-zeros/discuss/366029/Python3-solutions-O(n)-time-and-O(n2)-with-no-extra-space | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
length = len(arr)
input_idx = 0
result_idx = 0
result = [0] * length
while result_idx < length: # result_idx will either reach the end first or at the same time as input_idx
val = arr[input_idx]
result[result_idx] = val
input_idx += 1
result_idx += 1
if val == 0 and result_idx < length:
# duplicate the zero and advance the result index once more
result[result_idx] = 0
result_idx += 1
# copy the result
for i, val in enumerate(result):
arr[i] = val | duplicate-zeros | Python3 solutions O(n) time and O(n^2) with no extra space | llanowarelves | 0 | 73 | duplicate zeros | 1,089 | 0.515 | Easy | 17,316 |
https://leetcode.com/problems/duplicate-zeros/discuss/366029/Python3-solutions-O(n)-time-and-O(n2)-with-no-extra-space | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
length = len(arr)
i = 0
while i < length:
if arr[i] == 0:
self.shift_and_add_zero(arr, i)
i += 1
i += 1
def shift_and_add_zero(self, arr: List[int], idx: int) -> None:
for i, val in enumerate(arr[idx:]):
new_idx = idx + i + 1
if new_idx < len(arr):
arr[new_idx] = val
arr[idx] = 0 | duplicate-zeros | Python3 solutions O(n) time and O(n^2) with no extra space | llanowarelves | 0 | 73 | duplicate zeros | 1,089 | 0.515 | Easy | 17,317 |
https://leetcode.com/problems/duplicate-zeros/discuss/314489/In-Python3-what's-the-difference-between-arr-and-arr%3A | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
left=0
size=len(arr)
while left<=size-1:
if arr[left]!=0:
left+=1
elif arr[left]==0:
arr.insert(left,0)
left+=2
arr[:]=arr[:size] | duplicate-zeros | In Python3 what's the difference between arr and arr[:]? | jasperjoe | 0 | 104 | duplicate zeros | 1,089 | 0.515 | Easy | 17,318 |
https://leetcode.com/problems/duplicate-zeros/discuss/1443178/PYTHON3-oror-%22CHEATING%22-5-LINE | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
res, length = [], len(arr)
for num in arr:
if num: res.append(num)
else: res += [0, 0]
arr[:] = res[: length] | duplicate-zeros | PYTHON3 || "CHEATING" 5 LINE | shadowcatlegion | -1 | 104 | duplicate zeros | 1,089 | 0.515 | Easy | 17,319 |
https://leetcode.com/problems/duplicate-zeros/discuss/1352144/Python-solution-straight-forward | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
temp = []
for i in arr:
if i == 0:
temp.append(0)
temp.append(0)
else:
temp.append(i)
for i in range(len(arr)):
arr[i] = temp[i] | duplicate-zeros | Python solution straight forward | tianshuhuang6 | -2 | 142 | duplicate zeros | 1,089 | 0.515 | Easy | 17,320 |
https://leetcode.com/problems/largest-values-from-labels/discuss/1025001/Python3-greedy-O(NlogN) | class Solution:
def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int:
ans = 0
freq = {}
for value, label in sorted(zip(values, labels), reverse=True):
if freq.get(label, 0) < use_limit:
ans += value
num_wanted -= 1
if not num_wanted: break
freq[label] = 1 + freq.get(label, 0)
return ans | largest-values-from-labels | [Python3] greedy O(NlogN) | ye15 | 2 | 161 | largest values from labels | 1,090 | 0.609 | Medium | 17,321 |
https://leetcode.com/problems/largest-values-from-labels/discuss/1025001/Python3-greedy-O(NlogN) | class Solution:
def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int:
ans = 0
freq = defaultdict(int)
for value, label in sorted(zip(values, labels), reverse=True):
if 0 < num_wanted and freq[label] < use_limit:
ans += value
num_wanted -= 1
freq[label] += 1
return ans | largest-values-from-labels | [Python3] greedy O(NlogN) | ye15 | 2 | 161 | largest values from labels | 1,090 | 0.609 | Medium | 17,322 |
https://leetcode.com/problems/largest-values-from-labels/discuss/2739466/Python3-Using-Heaps-Commented | class Solution:
def largestValsFromLabels(self, values: List[int], labels: List[int], numWanted: int, useLimit: int) -> int:
# collect the highest values for each label
highest = collections.defaultdict(list)
# find the highest values
for label, value in zip(labels, values):
if len(highest[label]) < useLimit:
heapq.heappush(highest[label], value)
else:
heapq.heappushpop(highest[label], value)
# get the resulting values
values = []
for vals in highest.values():
values.extend([-val for val in vals])
# check whether we can use all
if len(values) <= numWanted:
return -sum(values)
# heapify the values
heapq.heapify(values)
# make the sum
result = 0
for _ in range(numWanted):
result += heapq.heappop(values)
return -result | largest-values-from-labels | [Python3] - Using Heaps - Commented | Lucew | 0 | 2 | largest values from labels | 1,090 | 0.609 | Medium | 17,323 |
https://leetcode.com/problems/largest-values-from-labels/discuss/2158255/PYTHON-or-EXPLAINED-or-GREEDY-%2B-SORTING-or-EASY-or-O(n*logn)or | class Solution:
def largestValsFromLabels(self, values: List[int], labels: List[int], numWanted: int, useLimit: int) -> int:
n = len(values)
used = defaultdict(lambda:0)
ans = 0
combined = sorted([(values[i],labels[i]) for i in range(n)],reverse = True)
for value,label in combined:
if numWanted == 0: break
if used[label] < useLimit:
used[label] += 1
ans += value
numWanted -= 1
return ans | largest-values-from-labels | PYTHON | EXPLAINED | GREEDY + SORTING | EASY | O(n*logn)| | reaper_27 | 0 | 55 | largest values from labels | 1,090 | 0.609 | Medium | 17,324 |
https://leetcode.com/problems/largest-values-from-labels/discuss/2111756/python-3-oror-simple-greedy-sorting-solution | class Solution:
def largestValsFromLabels(self, values: List[int], labels: List[int], numWanted: int, useLimit: int) -> int:
items = sorted(((value, label) for value, label in zip(values, labels)), reverse=True)
score = 0
uses = collections.Counter()
for value, label in items:
if uses[label] == useLimit:
continue
score += value
if numWanted == 1:
break
uses[label] += 1
numWanted -= 1
return score | largest-values-from-labels | python 3 || simple greedy sorting solution | dereky4 | 0 | 19 | largest values from labels | 1,090 | 0.609 | Medium | 17,325 |
https://leetcode.com/problems/largest-values-from-labels/discuss/1422486/Python3-solution-using-dictionary | class Solution:
def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int:
n = []
d = {}
for i,j in enumerate(values):
n.append([j,labels[i]])
d[labels[i]] = use_limit
n.sort(key = lambda x:x[0],reverse = True)
count = 0
for i,j in enumerate(n):
if num_wanted <= 0:
break
if d[j[1]] > 0:
count += j[0]
d[j[1]] -= 1
num_wanted -= 1
return count | largest-values-from-labels | Python3 solution using dictionary | EklavyaJoshi | 0 | 39 | largest values from labels | 1,090 | 0.609 | Medium | 17,326 |
https://leetcode.com/problems/largest-values-from-labels/discuss/868135/python3-items-to-list-sort-count-frequency-in-hashmap | class Solution:
# values: List[int]
# labels: List[int]
# num_wanted: int
# use_limit: int
def largestValsFromLabels(self, values, labels, num_wanted, use_limit) -> int:
# create item list of (value, label) tuples; sort
# iterate through items, count frequency in hashmap
# if freq count of label > use_limit, skip
# continue until items == num_wanted, or list expended
# O(NlogN) time, O(N) space
items = []
for i in range(len(values)):
items.append( (values[i], labels[i]) )
items.sort()
i, d, res = 0, {}, 0
while items and i < num_wanted:
val, lbl = items.pop()
d[lbl] = d.setdefault(lbl, 0) + 1
if d[lbl] <= use_limit:
res += val
i += 1
return res | largest-values-from-labels | python3 - items to list, sort, count frequency in hashmap | dachwadachwa | 0 | 65 | largest values from labels | 1,090 | 0.609 | Medium | 17,327 |
https://leetcode.com/problems/largest-values-from-labels/discuss/312749/Python3-straightforward-solution-with-explanation | class Solution:
def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int:
import collections
d=collections.defaultdict(int)
tem=[]
res=[]
a=zip(values,labels)
for i,j in a:
tem.append([i,j])
tem=sorted(tem, key=lambda x:-x[0])
count=0
for i in range(len(tem)):
d[tem[i][1]]+=1
if d[tem[i][1]]<=use_limit:
res.append(tem[i][0])
count+=1
if count==num_wanted:
break
return sum(res) | largest-values-from-labels | Python3 straightforward solution with explanation | jasperjoe | 0 | 56 | largest values from labels | 1,090 | 0.609 | Medium | 17,328 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/2043228/Python-Simple-BFS-with-Explanation | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
# check if source and target are not clear cells
if grid[0][0] != 0 or grid[-1][-1] != 0:
return -1
N = len(grid)
# offsets required for all 8 directions
offsets = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
q = deque()
q.append((0,0)) # starting point
visited = {(0, 0)}
# finds unvisited clear cells using 8 offsets
def get_neighbours(x,y):
for x_offset, y_offset in offsets:
new_row = x + x_offset
new_col = y + y_offset
if 0 <= new_row < N and 0 <= new_col < N and not grid[new_row][new_col] and (new_row, new_col) not in visited:
yield (new_row, new_col)
current_distance = 1 # start with one clear cell
# standard iterative BFS traversal
while q:
length = len(q)
# loop through all the cells at the same distance
for _ in range(length):
row, col = q.popleft()
if row == N-1 and col==N-1: # reached target
return current_distance
# loop though all valid neignbours
for p in get_neighbours(row, col):
visited.add(p)
q.append(p)
current_distance+=1 # update the level or distance from source
return -1 | shortest-path-in-binary-matrix | โ
Python Simple BFS with Explanation | constantine786 | 15 | 1,800 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,329 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/2046009/This-is-why-Memoization-also-fails-(illustrated-example) | class Solution:
NO_CLEAR_PATH = -1
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
n = len(grid)
dirs = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]
dp = [[None] * n for _ in range(n)]
def countCellsToTarget(i, j):
if i < 0 or j < 0 or i >= n or j >= n or grid[i][j] == 1: return self.NO_CLEAR_PATH
if (i, j) == (n-1, n-1): return 1
#if dp[i][j] is not None: return dp[i][j] # memoization removed
result = math.inf
grid[i][j] = 1
for di, dj in dirs:
ii, jj = i + di, j + dj
cellsToTarget = countCellsToTarget(ii, jj)
if cellsToTarget < 1: continue
result = min(result, 1 + cellsToTarget)
if result == math.inf: result = self.NO_CLEAR_PATH
grid[i][j] = 0
dp[i][j] = result
return result
return countCellsToTarget(0, 0) | shortest-path-in-binary-matrix | This is why Memoization also fails (illustrated example) | rcomesan | 12 | 304 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,330 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/1025014/Python3-BFS-O(N) | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
n = len(grid)
if grid[0][0] == 0:
ans = 0
grid[0][0] = 1
queue = deque([(0, 0)])
while queue:
ans += 1
for _ in range(len(queue)):
i, j = queue.popleft()
if i == j == n-1: return ans
for ii in range(i-1, i+2):
for jj in range(j-1, j+2):
if 0 <= ii < n and 0 <= jj < n and grid[ii][jj] == 0:
grid[ii][jj] = 1
queue.append((ii, jj))
return -1 | shortest-path-in-binary-matrix | [Python3] BFS O(N) | ye15 | 3 | 118 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,331 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/2111074/python-3-oror-simple-bfs | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
if m == 1 and n == 1:
return 1 if not grid[0][0] else -1
if grid[0][0] or grid[m - 1][n - 1]:
return -1
directions = ((1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1))
q = collections.deque([(0, 0, 1)])
while q:
i, j, pathLength = q.popleft()
for di, dj in directions:
newI, newJ = i + di, j + dj
if newI == m - 1 and newJ == n - 1:
return pathLength + 1
if newI == -1 or newI == m or newJ == -1 or newJ == n or grid[newI][newJ]:
continue
grid[newI][newJ] = 1
q.append((newI, newJ, pathLength + 1))
return -1 | shortest-path-in-binary-matrix | python 3 || simple bfs | dereky4 | 2 | 195 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,332 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/2006248/Python-BFS | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
if grid[0][0] or grid[-1][-1]:
return -1
n = len(grid)
q = deque([(0, 0, 1)])
grid[0][0] = 1
while q:
r, c, d = q.popleft()
if r == n - 1 and c == n - 1:
return d
for dr, dc in [(-1, 0), (-1, -1), (-1, 1), (1, 0), (1, -1), (1, 1), (0, -1), (0, 1)]:
nr, nc = r + dr, c + dc
if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] != 1:
grid[nr][nc] = 1
q.append((nr, nc, d + 1))
return -1 | shortest-path-in-binary-matrix | Python, BFS | blue_sky5 | 2 | 119 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,333 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/1906805/Template-for-these-kind-of-questions..oror-Python-oror-BFS-oror-without-Visited-set | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
r=len(grid)
c=len(grid[0])
# base case
if grid[0][0] or grid[r-1][c-1]:
return -1
# it's better to define the directioln first instead to define in the bfs main function
direction=[(1,0),(0,1),(-1,0),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)]
# initialize the queue with starting index and starting shell
q=deque([(0,0,1)])
while q:
x,y,no_cell=q.popleft()
# condition to return the result
if x==r-1 and y==c-1:
return no_cell
for d in direction:
nx=x+d[0]
ny=y+d[1]
# check for boundry condition and block places in the grid
if 0<=nx<r and 0<=ny<c and grid[nx][ny]==0:
# changing the grid value so that we don't traverse again through it
# instead of using the seen/visited set we just change the grid value to mark it as visited
grid[nx][ny]=1
q.append((nx,ny,no_cell+1))
return -1 | shortest-path-in-binary-matrix | Template for these kind of questions..|| Python || BFS || without Visited set | Shivam_007 | 2 | 123 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,334 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/2158310/PYTHON-or-FAST-or-BFS-or-EASY-or-WELL-EXPLAINED-or | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
n = len(grid)
if grid[0][0] == 1 or grid[-1][-1] == 1: return -1
queue = [(0,0,1)]
grid[0][0] = 1
while queue:
row,col,dist = queue.pop(0)
if row == col == n-1 : return dist
for x,y in ((row+1,col),(row-1,col),(row,col-1),(row,col+1),(row+1,col+1),\
(row+1,col-1),(row-1,col-1),(row-1,col+1)):
if 0<=x<n and 0<=y<n and grid[x][y] == 0:
grid[x][y] = 1
queue.append((x,y,dist+1))
return -1 | shortest-path-in-binary-matrix | PYTHON | FAST | BFS | EASY | WELL EXPLAINED | | reaper_27 | 1 | 124 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,335 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/1151264/WEEB-DOES-PYTHON-BFS-EASILY | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
row, col, queue = len(grid), len(grid[0]), deque([(0,0,1)])
if grid[0][0] == 1: return -1 # bruh, if it aint 0 then it aint gonna work
while queue:
x, y, steps = queue.popleft()
if x == row-1 and y == col-1:
return steps
for nx,ny in [[x+1,y+1], [x-1,y-1], [x+1,y-1], [x-1,y+1], [x+1,y], [x-1,y], [x,y+1], [x,y-1]]:
if 0<=nx<row and 0<=ny<col and grid[nx][ny] == 0:
grid[nx][ny] = "X"
queue.append((nx, ny, steps+1))
return -1 | shortest-path-in-binary-matrix | WEEB DOES PYTHON BFS EASILY | Skywalker5423 | 1 | 186 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,336 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/2849492/FASTEST-oror-BEATS-95-SUBMISSIONS-oror-EASIEST-oror-BFS | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
m,n=len(grid),len(grid[0])
q=deque()
dirs=[(0,1),(0,-1),(1,0),(-1,0),(-1,-1),(1,1),(-1,1),(1,-1)]
if grid[0][0]==0:
q.append((1,(0,0)))
grid[0][0]=1
while q:
steps,tmp=q.popleft()
r,c=tmp[0],tmp[1]
if (r,c)==(m-1,n-1):
return steps
for i,j in dirs:
nr,nc=r+i,c+j
if 0 <= nr < m and 0 <= nc < n and grid[nr][nc]==0:
q.append((steps+1,(nr,nc)))
grid[nr][nc]=1
return -1 | shortest-path-in-binary-matrix | FASTEST || BEATS 95% SUBMISSIONS || EASIEST || BFS | Pritz10 | 0 | 1 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,337 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/2804843/BFS.-In-place-modificationyu | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
layer = [(0,0)]
n = len(grid)
if grid[0][0] == 1:
return -1
grid[0][0] = -1
while layer:
n_layer = []
for (i,j) in layer:
for x in [-1,0,1]:
for y in [-1,0,1]:
if x==y==0 or i+x < 0 or i+x > n-1 or j+y < 0 or j+y > n-1:
continue
if grid[i+x][j+y] == 0:
n_layer.append((i+x,j+y))
grid[i+x][j+y] = grid[i][j] - 1
elif grid[i+x][j+y] < 0 and grid[i+x][j+y] < grid[i][j] - 1:
grid[i+x][j+y] = grid[i][j] - 1
n_layer.append((i+x,j+y))
layer = n_layer
if grid[n-1][n-1] == 0:
return -1
else:
return -grid[n-1][n-1] | shortest-path-in-binary-matrix | BFS. In-place modificationั | Pavel_Kos | 0 | 5 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,338 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/2788623/Python-optimised-bfs-solution-with-time-complexity | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
# bfs approach
# O(n), O(n)
# where n = rows * cols or size of grid
rows, cols = len(grid), len(grid[0])
if grid[0][0] or grid[-1][-1]:
return -1
queue = collections.deque([(0, 0, 1)])
directions = [[0, 1], [0, -1], [1, 0], [-1, 0], [1, 1], [1, -1], [-1, 1], [-1, -1]]
grid[0][0] = 1
while queue:
x, y, path_len = queue.popleft()
if x == (rows - 1) and y == (cols - 1):
return path_len
for dr, dc in directions:
new_x = x + dr
new_y = y + dc
if new_x in range(rows) and new_y in range(cols) and not grid[new_x][new_y]:
grid[new_x][new_y] = 1
queue.append((new_x, new_y, path_len + 1))
return -1 | shortest-path-in-binary-matrix | Python optimised bfs solution with time complexity | sahilkumar158 | 0 | 4 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,339 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/2782476/BFS-for-fun-and-profit | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
n = len(grid) - 1
src, dest = (0,0), (n, n)
if grid[src[0]][src[1]] != 0 or grid[dest[0]][dest[1]] != 0:
return -1
frontier = deque([(src, 1)])
visited = set()
directions = [(-1,0), (-1,-1), (-1,1), (1,0), (1,1),(1,-1), (0,1), (0,-1)]
while frontier:
(r, c), dist = frontier.popleft()
if (r,c) == (n,n):
return dist
for dir in directions:
new_r, new_c = (r + dir[0], c + dir[1])
if 0 <= new_r <= n and 0 <= new_c <= n:
if (new_r, new_c) not in visited and grid[new_r][new_c] == 0:
visited.add((new_r,new_c))
frontier.append(((new_r, new_c), dist + 1))
return -1 | shortest-path-in-binary-matrix | BFS for fun and profit | godelbach | 0 | 5 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,340 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/2707065/Simple-BFS-algorithm | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
if grid[0][0] == 1: return -1
n = len(grid)
distance = [[float("inf")]*len(grid) for _ in range(len(grid))]
directions = [(1,0),(0,1),(-1,0),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)]
distance[0][0] = 1
queue = deque()
queue.append((1,0,0))
while queue:
dist,x,y = queue.popleft()
for dx,dy in directions:
newx,newy = x+dx,y+dy
if self.canVisit(grid,newx,newy):
new_distance = dist+1
if new_distance < distance[newx][newy]:
distance[newx][newy] = new_distance
queue.append((new_distance,newx,newy))
if distance[n-1][n-1] == float("inf"): return -1
return distance[n-1][n-1]
def canVisit(self,grid,x,y):
return x<len(grid) and y<len(grid) and x >= 0 and y >= 0 and grid[x][y] == 0 | shortest-path-in-binary-matrix | Simple BFS algorithm | shriyansnaik | 0 | 4 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,341 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/2700240/Python-or-BFS | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
n = len(grid)
if grid[0][0] != 0 or grid[n-1][n-1] != 0:
return -1
stack = [[[0,0], 1]]
final_steps = 10000
visited = [0]*(n*n)
visited[0] = 1
while stack:
cur_loc, steps = stack.pop(0)
if cur_loc == [n-1, n-1]:
#final_steps = min(final_steps, steps)
return steps
for i in [-1,0,1]:
if cur_loc[0]+i<0 or cur_loc[0]+i>=n:
continue
for j in [-1,0,1]:
if cur_loc[1]+j<0 or cur_loc[1]+j>=n:
continue
if i==j==0:
continue
if visited[(cur_loc[0]+i)*n + cur_loc[1]+j] == 1:
continue
else:
if grid[cur_loc[0]+i][cur_loc[1]+j]==0:
stack.append([[cur_loc[0]+i, cur_loc[1]+j], steps+1])
visited[(cur_loc[0]+i)*n + cur_loc[1]+j] = 1
return -1 | shortest-path-in-binary-matrix | Python | BFS | Arana | 0 | 9 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,342 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/2660608/Python3-oror-easy-oror-BFS-oror-Dijkstra-algorithm-using-simple-queue | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
if not grid:
return
if len(grid)==1 and grid[0][0]==0:
return 1
if (grid[0][0]==1 or grid[-1][-1]==1):
return -1
rowSize=len(grid)
colSize=len(grid)
q=collections.deque()
distanceArray=[[float("inf")]*rowSize for i in range(rowSize)]
directions=[[-1,0],[0,1],[1,0],[0,-1],[-1,-1],[-1,1],[1,-1],[1,1]]
distanceArray[0][0]=0
#(edgeValue,(row,col))
q.append((1,(0,0)))
while q:
pathVal,(row,col)=q.popleft()
for r,c in directions:
newRow=row+r
newCol=col+c
if newRow>=0 and newRow<rowSize and newCol>=0 and newCol<colSize and grid[newRow][newCol]==0:
if distanceArray[newRow][newCol]>pathVal+1:
q.append((pathVal+1,(newRow,newCol)))
distanceArray[newRow][newCol]=pathVal+1
if newRow==rowSize-1 and newCol==colSize-1:
return pathVal+1
return -1 | shortest-path-in-binary-matrix | Python3 || easy || BFS || Dijkstra algorithm using simple queue | _soninirav | 0 | 6 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,343 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/2363297/jw-1091.-Shortest-Path-in-Binary-Matrix | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
if grid[0][0] == 1:
return -1
len_grid = len(grid)-1
if len_grid == 0:
if grid[0][0] == 1:
return -1
else:
return 1
d = ((-1, 0), (1, 0),(0, -1), (0, 1), (-1, -1), (1, -1), (1, 1), (-1, 1))
q = deque()
#์ด๊ธฐ ์ํ ์ ์
q.append((0, 0, 1))
grid[0][0] = 1
# print (len(grid))
while q:
h, w, time = q.popleft()
for dh, dw in d:
nh, nw, ntime = h+dh, w+dw, time + 1
print (nh, nw, ntime)
print (h,w)
if not 0 <= nh <= len_grid:
continue
if not 0 <= nw <= len_grid:
continue
if grid[nh][nw] == 1:
continue
if nh == len_grid and nw == len_grid:
return ntime
q. append((nh, nw, ntime))
grid[nh][nw] = 1
return -1 | shortest-path-in-binary-matrix | jw - 1091. Shortest Path in Binary Matrix | gozj32 | 0 | 8 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,344 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/2287341/Python-BFS-beginner-firendly-solution | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
if 1 in [grid[0][0], grid[-1][-1]]:
return -1
visited = set((0, 0))
q = collections.deque([(0, 0, 1)])
n = len(grid)
directions = [(0, 1), (1, 0), (-1, 0), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)]
while q:
x, y, step = q.popleft()
if (x, y) == (n - 1, n - 1):
return step
for dx, dy in directions:
newX = x + dx
newY = y + dy
if 0 <= newX < len(grid) and 0 <= newY < len(grid[0]) and grid[newX][newY] == 0 and (newX, newY) not in visited:
visited.add((newX, newY))
q.append((newX, newY, step + 1))
return -1 | shortest-path-in-binary-matrix | Python BFS, beginner firendly solution | scr112 | 0 | 96 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,345 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/2171104/why-my-solution-is-giving-TLE-passing-the-test-cases | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
if grid[0][0]==1:
return -1
li = []
li.append([0,0])
r = len(grid)
c = len(grid[0])
if r==1 and c==1:
return 1
ans = 1
while len(li)>0:
ans+=1
l = len(li)
for i in range(l):
curX = li[0][0]
curY = li[0][1]
for j in [[1,0],[-1,0],[0,1],[0,-1],[1,1],[1,-1],[-1,1],[-1,-1]]:
tempX = curX + j[0]
tempY = curY + j[1]
if tempX>=0 and tempX<=r-1 and tempY>=0 and tempY<=c-1 and grid[tempX][tempY]==0:
if tempX==r-1 and tempY==c-1:
return ans
li.append([tempX,tempY])
grid[curX][curY]=1
li.pop(0)
return -1 | shortest-path-in-binary-matrix | why my solution is giving TLE, passing the test cases | abhineetsingh192 | 0 | 37 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,346 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/2044266/Literal-BFS-in-Python-3 | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
from itertools import product
from collections import deque
# 8-directional ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1))
dirs = tuple(((x, y) for x, y in product(range(-1, 2), repeat=2) if x or y))
q, n, INF = deque(), len(grid), -1
lengths = [[INF] * n for _ in range(n)]
# make sure that both start and destination are reachable
if (grid[0][0], grid[-1][-1]) == (0, 0):
q += (0, 0),
lengths[0][0] = 1
while q:
cx, cy = q.popleft()
for dx, dy in dirs:
nx, ny = cx + dx, cy + dy
if not (0 <= nx < n and 0 <= ny < n and grid[nx][ny] == 0):
continue
if lengths[nx][ny] == INF or lengths[nx][ny] > lengths[cx][cy] + 1:
q += (nx, ny), # enqueue
lengths[nx][ny] = lengths[cx][cy] + 1
return lengths[-1][-1] | shortest-path-in-binary-matrix | Literal BFS in Python 3 | mousun224 | 0 | 40 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,347 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/2043806/Python-BFS-Dijkstra-Easy-understand | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
if grid[0][0] == 1: return -1
m, n = len(grid), len(grid[0])
heap = [(1, 0, 0)] # length, starting_x, starting_y
seen = set()
seen.add((0, 0))
while heap:
length, x, y = heapq.heappop(heap)
if (x, y) == (m - 1, n - 1): return length
for i, j in [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]:
nx, ny = x + i, y + j
if 0 <= nx < m and 0 <= ny < n and (nx, ny) not in seen and grid[nx][ny] == 0:
seen.add((nx, ny))
heapq.heappush(heap, (length + 1, nx, ny))
return -1 | shortest-path-in-binary-matrix | Python BFS Dijkstra Easy-understand | Kennyyhhu | 0 | 59 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,348 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/2043432/Python-solution-BFS | class Solution:
def shortestPathBinaryMatrix(self, grid):
N = len(grid)
dirs = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]]
queue = deque([(1, 0, 0)]) if grid[0][0] == 0 else deque()
visit = set()
while queue:
dist, x, y = queue.popleft()
if (x, y) == (N-1, N-1): return dist
for ax, ay in dirs:
if 0<=x+ax<N and 0<=y+ay<N and grid[x+ax][y+ay] == 0 and (x+ax, y+ay) not in visit:
visit.add((x+ax,y+ay))
queue.append((dist + 1, x+ax, y+ay))
return -1 | shortest-path-in-binary-matrix | Python solution BFS | saladino | 0 | 20 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,349 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/2043326/Python3-or-Simple-or-Easy-to-Understand-or-BFS | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
n = len(grid)
if grid[0][0] == 1 or grid[n-1][n-1] == 1:
return -1
return self.bfs(grid, n)
def bfs(self, grid, n):
queue = [(0, 0)]
minD = [[10**9 for _ in range(n)] for _ in range(n)]
minD[0][0] = 1
while queue:
x, y = queue.pop(0)
for i, j in self.adj(grid, n, x, y):
if i == n-1 and j == n-1:
return minD[x][y]+1
if not minD[i][j] != 10**9:
queue.append((i, j))
minD[i][j] = min(minD[i][j], minD[x][y]+1)
if minD[n-1][n-1] == 10**9:
return -1
return minD[n-1][n-1]
def adj(self, grid, n, x, y):
lst = [(x-1, y), (x+1, y), (x-1, y-1), (x-1, y+1), (x+1, y-1), (x+1, y+1), (x, y-1), (x, y+1)]
arr = []
for i, j in lst:
if i>=0 and i<n and j>=0 and j<n and grid[i][j] == 0:
arr.append((i, j))
return arr | shortest-path-in-binary-matrix | Python3 | Simple | Easy to Understand | BFS | H-R-S | 0 | 27 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,350 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/1929842/BFS-Python-Time-Limit-Exceeding | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
row_length = len(grid)
column_length = len(grid[0])
if grid[0][0] == 1:
return -1
adj = {}
for row in range(row_length):
for column in range(column_length):
if grid[row][column] == 1:
"""
Don't need to look at the paths we can't go to.
"""
continue
adj.update({f"{row},{column}": self.neighbors(row, column, grid)})
ORIGIN = f"{0},{0}"
DESTINATION = f"{row_length - 1},{column_length - 1}"
return self.bfs_length_shortest_path(adj, ORIGIN, DESTINATION)
def neighbors(self, row: int, column: int, grid: List[List[int]]) -> List:
row_length = len(grid)
column_length = len(grid[0])
result = []
steps = [
(1, 0),
(1, 1),
(0, 1),
(-1, 1),
(-1, 0),
(-1, -1),
(0, -1),
(1, -1)
]
for ix, iy in steps:
new_iy = iy + row
new_ix = ix + column
if not self.out_of_bounds(new_iy, new_ix, row_length, column_length) and grid[new_iy][new_ix] == 0:
result.append(f"{new_iy},{new_ix}")
return result
def out_of_bounds(self, row: int, column: int, row_size: int, column_size: int) -> bool:
if 0 <= row < row_size and 0 <= column < column_size:
return False
return True
def bfs_length_shortest_path(self, adj, origin, destination) -> int:
stack = [[origin]]
visited = set()
while stack:
current = stack.pop()
print(current)
current_position = current[-1]
if current_position == destination:
return len(current)
visited.add(current_position)
neighbors = adj[current_position]
for neigh in neighbors:
if neigh in visited:
continue
copy_current = current[:]
copy_current.append(neigh)
# stack.append(copy_current)
stack.insert(0, copy_current)
return -1 | shortest-path-in-binary-matrix | BFS Python Time Limit Exceeding | authier | 0 | 96 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,351 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/1878617/85-faster-or-45-less-mem-or-BFS-or-easy | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
ROWS, COLS = len(grid), len(grid[0])
if grid[0][0] == 1 or grid[ROWS-1][COLS-1] == 1:
return -1
moves = [[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1],[-1,0],[-1,1]]
visited = set()
dq = collections.deque()
steps, row, col = 0, 0, 0
visited.add((row,col))
dq.append((steps, row,col))
while dq:
steps, cur_x, cur_y = dq.popleft()
if cur_x == ROWS-1 and cur_y == COLS-1:
#print(steps)
return steps+1
for i, j in moves:
r, c = cur_x+i, cur_y+j
if (r >= 0 and r < ROWS and c >= 0 and c < COLS and
grid[r][c] == 0 and (r,c) not in visited):
visited.add((r,c))
dq.append((steps+1,r,c))
#print(dq,'steps', steps)
return -1
``` | shortest-path-in-binary-matrix | 85% faster | 45% less mem | BFS | easy | aamir1412 | 0 | 39 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,352 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/1787241/Python-easy-to-read-and-understand-or-BFS | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
if grid[0][0] == 1 or grid[m-1][n-1] == 1:
return -1
q = [(0, 0)]
grid[0][0] = 1
ans = 1
while q:
for i in range(len(q)):
row, col = q.pop(0)
if row == m-1 and col == n-1:
return ans
if row > 0 and grid[row-1][col] == 0:
grid[row-1][col] = 1
q.append((row-1, col))
if row > 0 and col > 0 and grid[row-1][col-1] == 0:
grid[row-1][col-1] = 1
q.append((row-1, col-1))
if col > 0 and grid[row][col-1] == 0:
grid[row][col-1] = 1
q.append((row, col-1))
if row < m-1 and col > 0 and grid[row+1][col-1] == 0:
grid[row+1][col-1] = 1
q.append((row+1, col-1))
if row < m-1 and grid[row+1][col] == 0:
grid[row+1][col] = 1
q.append((row+1, col))
if row < m-1 and col < n-1 and grid[row+1][col+1] == 0:
grid[row+1][col+1] = 1
q.append((row+1, col+1))
if col < n-1 and grid[row][col+1] == 0:
grid[row][col+1] = 1
q.append((row, col+1))
if row > 0 and col < n-1 and grid[row-1][col+1] == 0:
grid[row-1][col+1] = 1
q.append((row-1, col+1))
ans += 1
return -1 | shortest-path-in-binary-matrix | Python easy to read and understand | BFS | sanial2001 | 0 | 154 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,353 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/1679083/Easy-to-understand-BFS-using-python3 | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
neighbors = {(i, j) for i in range(-1, 2) for j in range(-1, 2)}
n = len(grid)
if grid[0][0] == 1:
return -1
q = [(0, 0, 1)] #position i, position j, number of hops
grid[0][0] = 1 #mark starting cell as visited
while q:
curr_i,curr_j,hops = q.pop(0)
if curr_i == n-1 and curr_j == n-1:
return hops
for i,j in neighbors:
if 0 <= curr_i+i < n and 0 <= curr_j+j < n: #check that neighbor is in bounds
#check that cell is NOT visited
if grid[curr_i+i][curr_j+j] == 0:
grid[curr_i+i][curr_j+j] = 1 #mark cell as visited
q.append((curr_i+i, curr_j+j, hops+1))
return -1 | shortest-path-in-binary-matrix | Easy to understand BFS using python3 | dylwu | 0 | 187 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,354 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/1485163/Python-BFS-using-value-function | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
if grid[-1][-1] == 1 or grid[0][0] == 1:
return -1
current_positions = set([(0, 0)])
value_function = [[-1] * len(grid) for i in range(len(grid))]
value_function[0][0] = 1
posible_positions = set()
for row_idx, row in enumerate(grid):
for col_idx, val in enumerate(row):
if not val:
posible_positions.add((row_idx, col_idx))
directions = [(-1, 0), (-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1)]
while 1:
if (len(grid) - 1, len(grid) - 1) in current_positions:
break
if not len(current_positions):
break
for x, y in list(current_positions):
for x_dir, y_dir in directions:
if (x + x_dir, y + y_dir) in posible_positions:
current_positions.add((x + x_dir, y + y_dir))
value_function[y + y_dir][x + x_dir] = value_function[y][x] + 1
posible_positions.remove((x + x_dir, y + y_dir))
current_positions.remove((x, y))
return value_function[-1][-1] | shortest-path-in-binary-matrix | Python BFS using value function | ac_h_illes | 0 | 149 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,355 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/1480653/Python-BFS-with-getAdjacent()-fully-detached | class Solution:
# outer loop: O(n); inner loop: O(1) as max 8 directions
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
if grid[0][0] == 1:
return -1
queue = [[0, 0]]
grid[0][0] = 1
while len(queue) != 0:
path = queue.pop(0)
value = grid[path[0]][path[1]]
if path[0] == len(grid) - 1 and path[1] == len(grid[0]) - 1:
return value
result = self.getAdjacent(path, grid)
for r in result:
row, col = r
grid[row][col] = value + 1
queue.append([row, col])
return -1
def getAdjacent(self, path, grid):
result = []
r, c = path
if r > 0:
if grid[r - 1][c] == 0:
result.append([r - 1, c])
if c > 0:
if grid[r][c - 1] == 0:
result.append([r, c - 1])
if r + 1 <= len(grid) - 1:
if grid[r + 1][c] == 0:
result.append([r + 1, c])
if c + 1 <= len(grid[0]) - 1:
if grid[r][c + 1] == 0:
result.append([r, c + 1])
if r > 0 and c > 0:
if grid[r - 1][c - 1] == 0:
result.append([r - 1, c - 1])
if r > 0 and c + 1 <= len(grid[0]) - 1:
if grid[r - 1][c + 1] == 0:
result.append([r - 1, c + 1])
if r + 1 <= len(grid) - 1 and c > 0:
if grid[r + 1][c - 1] == 0:
result.append([r + 1, c - 1])
if r + 1 <= len(grid) - 1 and c + 1 <= len(grid[0]) - 1:
if grid[r + 1][c + 1] == 0:
result.append([r + 1, c + 1])
return result | shortest-path-in-binary-matrix | Python BFS with getAdjacent() fully detached | SleeplessChallenger | 0 | 53 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,356 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/1445153/Python3Python-Solution-using-BFS-w-comments | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
# Init
n = len(grid)
min_distance = float("inf")
start = (0,0)
end = (n-1,n-1)
# Function to get all 8 directions of the current cell
def directions(r: int, c: int) -> List:
d = []
d.append((r-1,c)) # Up
d.append((r+1,c)) # Down
d.append((r,c-1)) # Left
d.append((r,c+1)) # Right
d.append((r-1,c-1)) # Up-Left
d.append((r-1,c+1)) # Up-Right
d.append((r+1,c-1)) # Down-Left
d.append((r+1,c+1)) # Down-Right
return d
# Check limits of cell
def inLimits(r: int, c: int) -> bool:
return (0 <= r < n) and (0 <= c < n)
# A modified BFS for end condition
def bfs(queue: List, isVisited: Set):
nonlocal min_distance
if queue: # if queue is not empty
# Pop the oldest entry
row, col, depth = queue.pop(0)
# Check conditions
if (row,col) not in isVisited and inLimits(row,col) and grid[row][col] == 0:
# Check end condition
if (row,col) == end:
# Calc min distance
min_distance = min(min_distance, depth)
else:
# Add to is visited set
isVisited.add((row,col))
# For adjacent nodes
for r,c in directions(row,col):
queue.append((r,c,depth+1))
# Call bfs until queue exhausted
bfs(queue, isVisited)
return # ~bfs()
# Run BFS on the matrix
bfs([(0,0,1)], set())
# Return
return -1 if min_distance == float("inf") else min_distance | shortest-path-in-binary-matrix | [Python3/Python] Solution using BFS w/ comments | ssshukla26 | 0 | 80 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,357 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/1078060/Python-Djkstra-Simple | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
dist = [[sys.maxsize for x in range(len(grid[0]))] for x in range(len(grid))]
minHeap = []
dist[0][0] = 1
directions = [(-1,-1), (1,1), (-1,0), (0,-1), (1,0), (0,1), (-1,1), (1,-1)]
if grid[0][0]==0:
heappush(minHeap, (1,0,0))
while minHeap:
curr_dist,x,y = heappop(minHeap)
for direction in directions:
nx = x+direction[0]
ny = y+direction[1]
if -1<nx<len(grid[0]) and -1<ny<len(grid) and grid[nx][ny]==0:
if dist[nx][ny]>1+curr_dist:
dist[nx][ny] = 1+curr_dist
heappush(minHeap, (dist[nx][ny], nx, ny))
if dist[-1][-1]==sys.maxsize:
return -1
return dist[-1][-1] | shortest-path-in-binary-matrix | Python Djkstra Simple | eastwoodsamuel4 | 0 | 207 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,358 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/1069339/Python-easy-solution-using-BFS | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
N,M = len(grid), len(grid[0])
if grid[0][0] == 1:
return -1
q = deque()
directions = [(-1,1),(0,1),(1,0),(1,1),(0,-1),(-1,0),(-1,-1),(1,-1)]
if grid[0][0] == 0:
q.append((1,(0,0)))
grid[0][0] =1
while q:
steps, tmp = q.popleft()
r,c = tmp[0],tmp[1]
if(r,c) == (N-1,M-1):
return steps
for i,j in directions:
newr, newc = r+i, c+j
if 0<=newr<N and 0<=newc<M and grid[newr][newc]==0:
q.append((steps+1,(newr,newc)))
grid[newr][newc] =1
return -1 | shortest-path-in-binary-matrix | Python easy solution using BFS | Namangarg98 | 0 | 178 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,359 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/796308/Python-3-or-BFS-or-Explanation | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
ans, m, n = 0, len(grid), len(grid[0])
if grid[0][0] == 1 or grid[m-1][n-1] == 1: return -1
q = [(0, 0)]
while q:
tmp_q = []
ans += 1
while q:
x, y = q.pop()
if (x, y) == (m-1, n-1): return ans
for dx, dy in (-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (-1, 1), (1, -1), (1, 1):
xx, yy = x+dx, y+dy
if 0 <= xx < m and 0 <= yy < n and not grid[xx][yy]:
grid[xx][yy] = 1
tmp_q.append((xx, yy))
q = tmp_q
return -1 | shortest-path-in-binary-matrix | Python 3 | BFS | Explanation | idontknoooo | 0 | 265 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,360 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/751691/Python-Easy-to-Read-and-Understand-BFS-beats-85-with-Comments! | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
# rows will == cols here as we're told its n*n
rows = len(grid)
cols = len(grid[0])
# Check validity of grid, make sure we can start and finish.
if not grid or grid[0][0] != 0 or grid[-1][-1] != 0:
return -1
# Use a deque for our BFS.
q = collections.deque([])
q.append((0, 0, 1))
# Store the 8 possible directions that we can search.
directions = [(1, 0), (-1, 0), (0, 1), (0, -1), (-1, -1), (-1, 1), (1, -1), (1, 1)]
while q:
row, col, dist = q.popleft()
# If we've reach the last position in our grid we're done and using
# BFS we can gurantee the first to arrive will be the shortest path.
if row == rows-1 and col==cols-1:
return dist
# Iterate through our directions.
for r, c in directions:
nr = row + r
nc = col + c
# Validate that the move we're going to make is valid:
# The new location is contained within the grid and is empty '0'.
if rows > nr >= 0 and cols > nc >= 0 and grid[nr][nc] == 0:
# Fill the new location so it doesn't get revisted and append the step to the deque.
grid[nr][nc] = '#'
q.append((nr, nc, dist + 1))
return -1 | shortest-path-in-binary-matrix | Python Easy to Read and Understand BFS beats 85% with Comments! | Pythagoras_the_3rd | 0 | 152 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,361 |
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/1811165/Python-simple-multisource-BFS | class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
N, M = len(grid), len(grid[0])
directions = ((1,1),(1,0),(0,1),(1,-1),(-1,1),(0,-1),(-1,0),(-1,-1))
Coordinate = namedtuple('Coordinate', ['x', 'y'])
start = Coordinate(0,0)
goal = Coordinate(N-1, M-1)
if grid[start.x][start.y] != 0:
return -1
def withinBounds(curr):
return 0 <= curr.x < N and 0 <= curr.y < M
queue = deque([(start)])
grid[start.x][start.y] = 1
pathLength = 1
while queue:
for _ in range(len(queue)):
curr = queue.popleft()
if curr == goal:
return pathLength
for r, c in directions:
neigh = Coordinate(curr.x + r, curr.y + c)
if withinBounds(neigh) and grid[neigh.x][neigh.y] == 0:
grid[neigh.x][neigh.y] = 1
queue.append(neigh)
pathLength += 1
return -1 | shortest-path-in-binary-matrix | Python simple multisource BFS | Rush_P | -1 | 61 | shortest path in binary matrix | 1,091 | 0.445 | Medium | 17,362 |
https://leetcode.com/problems/shortest-common-supersequence/discuss/786544/Simple-Python-Accepted-Solution-using-LCS-implementation-faster-than-83-python-users | class Solution:
def shortestCommonSupersequence(self, str1: str, str2: str) -> str:
n,m = len(str1),len(str2)
dp = [[0 for j in range(m+1)]for i in range(n+1)]
for i in range(1,n+1):
for j in range(1,m+1):
if str1[i-1] == str2[j-1]:
dp[i][j] = 1+dp[i-1][j-1]
else:
dp[i][j] = max(dp[i-1][j],dp[i][j-1])
i,j = n,m
ans = ""
while(i>0 and j>0):
if str1[i-1] == str2[j-1]:
ans += str1[i-1]
i -= 1
j -= 1
else:
if(dp[i-1][j] > dp[i][j-1]):
ans += str1[i-1]
i -= 1
else:
ans += str2[j-1]
j -= 1
while(i>0):
ans += str1[i-1]
i -= 1
while(j>0):
ans += str2[j-1]
j -= 1
return ans[::-1] | shortest-common-supersequence | Simple Python Accepted Solution using LCS implementation faster than 83% python users | theflash007 | 7 | 323 | shortest common supersequence | 1,092 | 0.578 | Hard | 17,363 |
https://leetcode.com/problems/shortest-common-supersequence/discuss/1479075/DPIntuitive-Solution-with-slight-variation-of-LCS | class Solution:
def shortestCommonSupersequence(self, str1: str, str2: str) -> str:
m = len(str1)
n = len(str2)
# construct the dp table
t = [[0 for j in range(n + 1)] for i in range(m + 1)]
for i in range(1, m+1):
for j in range(1, n+1):
if str1[i-1] == str2[j-1]:
t[i][j] = 1 + t[i-1][j-1]
else:
t[i][j] = max(t[i-1][j], t[i][j-1])
i = len(str1)
j = len(str2)
string = ''
while i>0 and j>0:
if str1[i-1] == str2[j-1]:
string += str1[i-1]
i -= 1
j -= 1
else:
if t[i][j-1] > t[i-1][j]:
string += str2[j-1]
j -= 1
else:
string += str1[i-1]
i -= 1
# now atleast ome string must have been exhausted
# so for remaining string
# if str1 is remaining
while i>0:
string += str1[i-1]
i -= 1
# if str2 is remaining
while j>0:
string += str2[j-1]
j -= 1
return string[::-1] | shortest-common-supersequence | [DP][Intuitive] Solution with slight variation of LCS | nandanabhishek | 3 | 215 | shortest common supersequence | 1,092 | 0.578 | Hard | 17,364 |
https://leetcode.com/problems/shortest-common-supersequence/discuss/2464477/Hard-made-Easy-Python-solution-LCS-Easy-to-Understand | class Solution:
def LCS(self,s,t):
m=len(s)
n=len(t)
dp=[[0 for i in range(n+1)]for j in range(m+1)]
for i in range(m+1):
dp[i][0]=0
for j in range(n+1):
dp[0][j]=0
for i in range(1,m+1):
for j in range(1,n+1):
if s[i-1]==t[j-1]:
dp[i][j]=1+dp[i-1][j-1]
else:
dp[i][j]=max(dp[i-1][j],dp[i][j-1])
return dp
def shortestCommonSupersequence(self, s: str, t: str) -> str:
dp=self.LCS(s,t)
m=len(dp)-1
n=len(dp[0])-1
ans=""
i=m
j=n
while(i>0 and j>0):
if s[i-1]==t[j-1]:
ans+=s[i-1]
i-=1
j-=1
elif dp[i-1][j]>dp[i][j-1]:
ans+=s[i-1]
i-=1
else:
ans+=t[j-1]
j-=1
while(i>0):
ans+=s[i-1]
i-=1
while(j>0):
ans+=t[j-1]
j-=1
return ans[::-1] | shortest-common-supersequence | Hard made Easy Python solution LCS Easy to Understand | adarshg04 | 2 | 100 | shortest common supersequence | 1,092 | 0.578 | Hard | 17,365 |
https://leetcode.com/problems/shortest-common-supersequence/discuss/2086630/Python-Solution | class Solution:
def shortestCommonSupersequence(self, str1: str, str2: str) -> str:
a=str1
b=str2
m=len(a)
n=len(b)
dp =([[0 for i in range(n + 1)] for i in range(m + 1)])
for i in range(1,m+1):
for j in range(1,n+1):
if a[i-1]==b[j-1]:
dp[i][j]=1+dp[i-1][j-1]
else:
dp[i][j]=max(dp[i][j-1],dp[i-1][j])
i=m
j=n
sr=""
while i>0 and j>0:
if a[i-1]==b[j-1]:
sr+=a[i-1]
i-=1
j-=1
else:
if dp[i][j-1]>dp[i-1][j]:
sr+=b[j-1]
j-=1
else:
sr+=a[i-1]
i-=1
while i>0:
sr+=a[i-1]
i-=1
while j>0:
sr+=b[j-1]
j-=1
return sr[::-1] | shortest-common-supersequence | Python Solution | a_dityamishra | 1 | 53 | shortest common supersequence | 1,092 | 0.578 | Hard | 17,366 |
https://leetcode.com/problems/shortest-common-supersequence/discuss/1893922/Python-Beginner-Easy-Fast-solution-using-LCS | class Solution:
def shortestCommonSupersequence(self, str1: str, str2: str) -> str:
m=len(str1)
n=len(str2)
ans=""
#initialising DP
dp=[[0]*(n+1) for i in range(m+1)]
#filling DP table by finding LCS
for i in range(1,m+1):
for j in range(1,n+1):
if str1[i-1]==str2[j-1]:
dp[i][j]=1+dp[i-1][j-1]
else:
dp[i][j]=max(dp[i-1][j],dp[i][j-1])
#Printing SCS
while i>0 and j>0:
if str1[i-1]==str2[j-1]:
ans=str1[i-1]+ans
i-=1
j-=1
else:
if dp[i-1][j]>dp[i][j-1]:
ans=str1[i-1]+ans
i-=1
else:
ans=str2[j-1]+ans
j-=1
#if length of both string is different
while i>0:
ans=str1[i-1]+ans
i-=1
while j>0:
ans=str2[j-1]+ans
j-=1
return ans | shortest-common-supersequence | [Python] Beginner Easy , Fast solution using LCS | RaghavGupta22 | 1 | 139 | shortest common supersequence | 1,092 | 0.578 | Hard | 17,367 |
https://leetcode.com/problems/shortest-common-supersequence/discuss/1463754/python-3-oror-dp-solution-oror-3-parts | class Solution:
def shortestCommonSupersequence(self, x: str, y: str) -> str:
n=len(x)
m=len(y)
dp=[[-1]*(m+1)for i in range (n+1)]
#1.length of longest common subsequence of x and y
for i in range(n+1):
for j in range(m+1):
#base condition
if i==0 or j==0:
dp[i][j]=0
#choice
elif x[i-1]==y[j-1]:
dp[i][j]=1+dp[i-1][j-1]
else:
dp[i][j]=max(dp[i-1][j],dp[i][j-1])
#2. finding the longest common subsequence string
i=n
j=m
lst=[]
while(i>0 and j>0):
if x[i-1]==y[j-1]:
lst.append(x[i-1])
i-=1
j-=1
else:
if (dp[i][j-1]>dp[i-1][j]):
j-=1
else:
i-=1
lst.reverse()
s="".join(lst)
#3. finding the supersequence-res
res=""
i=0
j=0
for c in s:
while x[i] != c:
res += x[i]
i += 1
while y[j] != c:
res += y[j]
j += 1
res+=c; i+=1; j+=1
return (res + x[i:] + y[j:]) | shortest-common-supersequence | python 3 || dp solution || 3 parts | minato_namikaze | 1 | 110 | shortest common supersequence | 1,092 | 0.578 | Hard | 17,368 |
https://leetcode.com/problems/shortest-common-supersequence/discuss/2767919/Dynamic-Programming-Python-Solution-using-LCS | class Solution:
def LCS(self,str1,str2):
m = len(str1)
n = len(str2)
t = [[-1 for i in range(n + 1)] for j in range(m + 1)]
for i in range(m+1):
t[i][0] = 0
for j in range(n+1):
t[0][j] = 0
for i in range(1,m+1):
for j in range(1,n+1):
if str1[i-1] == str2[j-1]:
t[i][j]=1 + t[i-1][j-1]
else:
t[i][j]=max(t[i-1][j],t[i][j-1])
return t
def shortestCommonSupersequence(self,str1: str, str2: str) -> str:
dp = self.LCS(str1,str2)
print(dp)
m = len(dp)-1
n = len(dp[0])-1
res = ""
i = m
j = n
while (i > 0 and j > 0):
if str1[i - 1] == str2[j - 1]:
res += str1[i - 1]
i -= 1
j -= 1
elif dp[i-1][j] > dp[i][j-1]:
res += str1[i-1]
i -= 1
else:
res += str2[j-1]
j -= 1
while(i > 0):
res += str1[i - 1]
i -= 1
while(j > 0):
res += str2[j - 1]
j -= 1
return res[::-1] | shortest-common-supersequence | [Dynamic Programming] Python Solution using LCS | nikhitamore | 0 | 2 | shortest common supersequence | 1,092 | 0.578 | Hard | 17,369 |
https://leetcode.com/problems/shortest-common-supersequence/discuss/2704903/Python3-or-LCS-Variation | class Solution:
def shortestCommonSupersequence(self, s1: str, s2: str) -> str:
n,m=len(s1),len(s2)
dp=[[0 for i in range(m+1)] for j in range(n+1)]
for i in range(1,n+1):
for j in range(1,m+1):
if s1[i-1]==s2[j-1]:
dp[i][j]=dp[i-1][j-1]+1
else:
dp[i][j]=max(dp[i-1][j],dp[i][j-1])
i,j=n,m
ans=''
while i>0 and j>0:
if s1[i-1]==s2[j-1]:
ans+=s1[i-1]
i-=1
j-=1
elif dp[i-1][j]>dp[i][j-1]:
ans+=s1[i-1]
i-=1
else:
ans+=s2[j-1]
j-=1
while i>0:
ans+=s1[i-1]
i-=1
while j>0:
ans+=s2[j-1]
j-=1
return ans[::-1] | shortest-common-supersequence | [Python3] | LCS Variation | swapnilsingh421 | 0 | 1 | shortest common supersequence | 1,092 | 0.578 | Hard | 17,370 |
https://leetcode.com/problems/shortest-common-supersequence/discuss/2666802/python-easy-LCS-methodp | class Solution:
def shortestCommonSupersequence(self, A: str, B: str) -> str:
dp={}
def solve(A,B,i,j):
if i==0 or j==0:
return ""
if (i,j) in dp:
return dp[(i,j)]
if A[i-1]==B[j-1]:
dp[(i,j)]= A[i-1]+solve(A,B,i-1,j-1)
return dp[(i,j)]
else:
dp[(i,j)]= max(solve(A,B,i-1,j),solve(A,B,i,j-1),key=len)
return dp[(i,j)]
STR = solve(A,B,len(A),len(B))[::-1]
ans = ""
i = 0
j = 0
for c in STR:
while i<len(A) and (A[i] != c) :
ans += A[i]
i+=1
while j<len(B) and (B[j] != c) :
ans += B[j]
j+=1
ans += c
i+=1
j+=1
ans+= A[i:] + B[j:]
return ans | shortest-common-supersequence | python easy LCS methodp | Akash_chavan | 0 | 5 | shortest common supersequence | 1,092 | 0.578 | Hard | 17,371 |
https://leetcode.com/problems/shortest-common-supersequence/discuss/2584944/Top-Down-Approach-oror-DP-oror-Solution-with-Print-Length-of-SCS | class Solution:
def shortestCommonSupersequence(self, str1: str, str2: str) -> str:
def lcs(x,y,n,m):
#creating martix of n+1 and m+1
dp = [[-1 for _ in range(len(y)+1)] for _ in range(len(x)+1)]
for i in range(n+1):
for j in range(m+1):
if i == 0 or j == 0:
dp[i][j] = 0
elif x[i-1] == y[j-1]:
dp[i][j] = 1 + dp[i-1][j-1]
else:
dp[i][j] = max(dp[i-1][j],dp[i][j-1])
# return (m+n-dp[-1][-1])
# to print shortest common subsequence uncomment 17th line and comment out below code
# code to print shortest common subsequence
i = n
j = m
s = ""
# when i and j both have values in it
while i>0 and j>0:
if x[i-1] == y[j-1]:
s+=x[i-1]
i-=1
j-=1
elif dp[i][j-1]>dp[i-1][j]:
s+=y[j-1]
j-=1
else:
s+=x[i-1]
i-=1
# when j has no values but i have
while i>0:
s+=x[i-1]
i-=1
# when i has no values but j have
while j>0:
s+=y[j-1]
j-=1
return s[::-1]
return lcs(str1,str2,len(str1),len(str2)) | shortest-common-supersequence | Top-Down Approach || DP || Solution with Print Length of SCS | ajinkyabhalerao11 | 0 | 23 | shortest common supersequence | 1,092 | 0.578 | Hard | 17,372 |
https://leetcode.com/problems/shortest-common-supersequence/discuss/2249420/Shortest-Common-Supersequence | class Solution:
def shortestCommonSupersequence(self, str1: str, str2: str) -> str:
#found the LCS
subseq = self.LCS(str1,str2,len(str1),len(str2))
#created bool arrays to store the common letters and make markers
bool1 = [False for i in range(len(str1))]
bool2 = [False for j in range(len(str2))]
j = 0
for i in range(len(str1)):
if j < len(subseq) and str1[i] == subseq[j]:
bool1[i] = True
j = j + 1
j = 0
for i in range(len(str2)):
if j < len(subseq) and str2[i] == subseq[j]:
bool2[i] = True
j = j + 1
#printed the supersequence
i,j,x = 0,0,0
ans = []
while i < len(str1) or j < len(str2):
if i < len(str1) and not bool1[i]:
ans.append(str1[i])
i = i + 1
if j < len(str2) and not bool2[j]:
ans.append(str2[j])
j = j + 1
if j < len(str2) and i < len(str1) and bool1[i] and bool2[j]:
ans.append(subseq[x])
i = i + 1
j = j + 1
x = x + 1
return ans
def LCS(self, s1, s2, l1, l2):
dp = [[0 for i in range(l2+1)] for j in range(l1+1)]
for i in range(1,l1+1):
for j in range(1,l2+1):
if s1[i-1] == s2[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = max(dp[i-1][j],dp[i][j-1])
ans = []
i,j = l1,l2
while i > 0 and j > 0:
if s1[i-1] == s2[j-1]:
ans.append(s1[i-1])
i = i - 1
j = j - 1
else:
if dp[i-1][j] < dp[i][j-1]:
j = j - 1
else:
i = i - 1
return ans[::-1] | shortest-common-supersequence | Shortest Common Supersequence | ishitab_15 | 0 | 35 | shortest common supersequence | 1,092 | 0.578 | Hard | 17,373 |
https://leetcode.com/problems/shortest-common-supersequence/discuss/2163034/PYTHON-or-EASIEST-POSSIBLE-SOLUTION-or-USING-LCS-or-WELL-EXPLAINED-or | class Solution:
def shortestCommonSupersequence(self, str1: str, str2: str) -> str:
n1,n2 = len(str1), len(str2)
dp = [[0 for i in range(n2+1)] for j in range(n1+1)]
for i in range(1,n1+1):
for j in range(1,n2+1):
if str1[i-1] == str2[j-1] :dp[i][j] = dp[i-1][j-1] + 1
else: dp[i][j] = dp[i-1][j] if dp[i-1][j] > dp[i][j-1] else dp[i][j-1]
scs = ""
r,c = n1,n2
while r > 0 and c > 0:
if str1[r-1] == str2[c-1]:
scs = str1[r-1] + scs
r -= 1
c -= 1
else:
if dp[r-1][c] == dp[r][c]:
# we are neglecting str2[c-1]
scs = str1[r-1] + scs
r -= 1
else:
scs = str2[c-1] + scs
c -= 1
if r == 0 and c == 0: return scs
if r == 0: scs = str2[0:c] + scs
else: scs = str1[0:r] + scs
return scs | shortest-common-supersequence | PYTHON | EASIEST POSSIBLE SOLUTION | USING LCS | WELL EXPLAINED | | reaper_27 | 0 | 39 | shortest common supersequence | 1,092 | 0.578 | Hard | 17,374 |
https://leetcode.com/problems/shortest-common-supersequence/discuss/1511128/Python3-solution | class Solution:
def shortestCommonSupersequence_0(self, str1: str, str2: str) -> str:
n1 = len(str1)
n2 = len(str2)
# boundary conditions
dp = [ [""]*(n1+1) for _ in range(n2+1) ]
for i in range(n1):
dp[0][i+1] = str1[:i+1]
for j in range(n2):
dp[j+1][0] = str2[:j+1]
# bulk updates
for j in range(n2):
for i in range(n1):
if str1[i] == str2[j]:
dp[j+1][i+1] = dp[j][i] + str1[i]
else:
if len(dp[j+1][i]) < len(dp[j][i+1]):
dp[j+1][i+1] = dp[j+1][i] + str1[i]
else:
dp[j+1][i+1] = dp[j][i+1] + str2[j]
return dp[n2][n1] | shortest-common-supersequence | Python3 solution | dalechoi | 0 | 107 | shortest common supersequence | 1,092 | 0.578 | Hard | 17,375 |
https://leetcode.com/problems/shortest-common-supersequence/discuss/1511128/Python3-solution | class Solution:
# Runtime: 508 ms, faster than 56.63% of Python3
# Memory Usage: 17.4 MB, less than 94.06% of Python3
# two-level scheme
def shortestCommonSupersequence(self, str1: str, str2: str) -> str:
n1 = len(str1)
n2 = len(str2)
# base level set up
dp = [ [""]*(n1+1) for _ in range(2) ]
for i in range(n1):
dp[0][i+1] = str1[:i+1]
# bulk updates
for j in range(n2):
dp[1][0] = str2[:j+1]
for i in range(n1):
if str1[i] == str2[j]:
dp[1][i+1] = dp[0][i] + str1[i]
else:
if len(dp[1][i]) < len(dp[0][i+1]):
dp[1][i+1] = dp[1][i] + str1[i]
else:
dp[1][i+1] = dp[0][i+1] + str2[j]
dp[0] = dp[1].copy() # update level for next iteration
return dp[0][n1] | shortest-common-supersequence | Python3 solution | dalechoi | 0 | 107 | shortest common supersequence | 1,092 | 0.578 | Hard | 17,376 |
https://leetcode.com/problems/shortest-common-supersequence/discuss/1439137/1092.-Shortest-Common-Supersequence-Python-DP-Solution | class Solution:
def shortestCommonSupersequence(self, str1: str, str2: str) -> str:
storage = self.getStorage(str1, str2)
s1 = len(str1)
s2 = len(str2)
shortestCommonSupersequence = ""
while s1 > 0 and s2 > 0:
if str1[s1 - 1] == str2[s2 - 1]:
shortestCommonSupersequence = str1[s1 - 1] + shortestCommonSupersequence
s1 -= 1
s2 -= 1
else:
if storage[s1 - 1][s2] > storage[s1][s2 - 1]:
shortestCommonSupersequence = str1[s1 - 1] + shortestCommonSupersequence
s1 -= 1
else:
shortestCommonSupersequence = str2[s2 - 1] + shortestCommonSupersequence
s2 -= 1
while s1 > 0:
shortestCommonSupersequence = str1[s1 - 1] + shortestCommonSupersequence
s1 -= 1
while s2 > 0:
shortestCommonSupersequence = str2[s2 - 1] + shortestCommonSupersequence
s2 -= 1
return shortestCommonSupersequence
def getStorage(self, str1: str, str2: str):
storage = [[0 for _ in range(len(str2) + 1)] for _ in range(len(str1) + 1)]
for s1 in range(1, len(str1) + 1):
for s2 in range(1, len(str2) + 1):
if str1[s1 - 1] == str2[s2 - 1]:
storage[s1][s2] = 1 + storage[s1 - 1][s2 - 1]
else:
storage[s1][s2] = max(storage[s1 - 1][s2], storage[s1][s2 - 1])
return storage | shortest-common-supersequence | 1092. Shortest Common Supersequence - Python DP Solution | rohanpednekar_ | 0 | 108 | shortest common supersequence | 1,092 | 0.578 | Hard | 17,377 |
https://leetcode.com/problems/shortest-common-supersequence/discuss/1227844/LCS-with-DP-oror-93-faster-oror-Well-explained-oror | class Solution:
def shortestCommonSupersequence(self, str1: str, str2: str) -> str:
def LCS(A,B):
m,n=len(A),len(B)
dp = [["" for _ in range(n+1)] for _ in range(m+1)]
for i in range(m):
for j in range(n):
if A[i]==B[j]:
dp[i+1][j+1]=dp[i][j]+A[i]
else:
dp[i+1][j+1]=max(dp[i+1][j],dp[i][j+1],key=len)
return dp[-1][-1]
res=""
lcs=LCS(str1,str2)
i,j=0,0
for c in lcs:
while str1[i]!=c:
res+=str1[i]
i+=1
while str2[j]!=c:
res+=str2[j]
j+=1
res+=c
i+=1
j+=1
res+=str1[i:]+str2[j:]
return res | shortest-common-supersequence | ๐ {LCS with DP} || 93% faster || Well-explained || | abhi9Rai | 0 | 78 | shortest common supersequence | 1,092 | 0.578 | Hard | 17,378 |
https://leetcode.com/problems/shortest-common-supersequence/discuss/1227378/Python-LCS-based-Simplest-Code | class Solution:
def shortestCommonSupersequence(self, str1: str, str2: str) -> str:
#Length of LCS
m=len(str1)
n=len(str2)
t=[[0 for i in range(n+1)] for j in range(m+1)]
for i in range(1,m+1):
for j in range(1,n+1):
if str1[i-1]==str2[j-1]:
t[i][j]= 1 + t[i-1][j-1]
else:
t[i][j]=max(t[i-1][j],t[i][j-1])
#Print LCS
i=m
j=n
lcs=""
while(i>0 and j>0):
if str1[i-1]==str2[j-1]:
lcs=lcs+str1[i-1]
i-=1
j-=1
else:
if t[i][j-1]>t[i-1][j]:
j-=1
else:
i-=1
lcs=lcs[::-1]
#Print Shortest Common Subsequence
i=0
j=0
ans=""
for k in lcs:
while str1[i]!=k:
ans=ans+str1[i]
i+=1
while str2[j]!=k:
ans=ans+str2[j]
j+=1
ans=ans+k
i+=1
j+=1
return ans+str1[i:]+str2[j:] | shortest-common-supersequence | Python LCS based Simplest Code | coder1311 | 0 | 30 | shortest common supersequence | 1,092 | 0.578 | Hard | 17,379 |
https://leetcode.com/problems/shortest-common-supersequence/discuss/1179633/Python3-dp-and-greedy | class Solution:
def shortestCommonSupersequence(self, str1: str, str2: str) -> str:
@lru_cache(None)
def fn(i, j):
"""Return min length of common supersequence of str1[i:] and str2[j:]."""
if i == len(str1): return len(str2)-j
if j == len(str2): return len(str1)-i
if str1[i] == str2[j]: return 1 + fn(i+1, j+1)
return 1 + min(fn(i+1, j), fn(i, j+1))
ans = []
i = j = 0
while i < len(str1) and j < len(str2):
if str1[i] == str2[j]:
ans.append(str1[i])
i += 1
j += 1
elif fn(i+1, j) < fn(i, j+1):
ans.append(str1[i])
i += 1
else:
ans.append(str2[j])
j += 1
return "".join(ans) + str1[i:] + str2[j:] | shortest-common-supersequence | [Python3] dp & greedy | ye15 | 0 | 62 | shortest common supersequence | 1,092 | 0.578 | Hard | 17,380 |
https://leetcode.com/problems/statistics-from-a-large-sample/discuss/1653119/Python3-one-liner | class Solution:
def sampleStats(self, count: List[int]) -> List[float]:
return [
#Minimum
min(i for i,c in enumerate(count) if c != 0),
#Maximum
max(i for i,c in enumerate(count) if c != 0),
#Mean
sum(i*c for i,c in enumerate(count)) / sum(c for c in count if c != 0),
#Media
(lambda total:
(
next(i for i,s in enumerate(itertools.accumulate(count)) if s >= total//2+1)+
next(i for i,s in enumerate(itertools.accumulate(count)) if s >= total//2+total%2)
)/2
)(sum(c for c in count if c != 0)),
#Mode
max(((i,c) for i,c in enumerate(count) if c != 0),key=(lambda x: x[1]))[0]
] | statistics-from-a-large-sample | Python3 one-liner | pknoe3lh | 0 | 179 | statistics from a large sample | 1,093 | 0.444 | Medium | 17,381 |
https://leetcode.com/problems/statistics-from-a-large-sample/discuss/1485170/Python3-solution | class Solution:
def sampleStats(self, count: List[int]) -> List[float]:
running_sum = 0
min_elem = 300
max_elem = -1
most_frequent_value, max_freq = None, 0
current_idx = 0
all_counter = sum(count)
medium_idx = all_counter // 2
medium_sum = 0
if all_counter % 2 == 0:
medium_idx = medium_idx, medium_idx - 1
else:
medium_idx = medium_idx, medium_idx
for value, counter in enumerate(count):
if medium_idx[0] >= current_idx and medium_idx[0] < current_idx + counter:
medium_sum += value
if medium_idx[1] >= current_idx and medium_idx[1] < current_idx + counter:
medium_sum += value
current_idx += counter
running_sum += value * counter
if min_elem == 300 and counter:
min_elem = value
max_elem = max(value, max_elem) if counter else max_elem
if counter > max_freq:
most_frequent_value = value
max_freq = counter
return min_elem, max_elem, running_sum / all_counter, medium_sum / 2, most_frequent_value | statistics-from-a-large-sample | Python3 solution | ac_h_illes | 0 | 148 | statistics from a large sample | 1,093 | 0.444 | Medium | 17,382 |
https://leetcode.com/problems/statistics-from-a-large-sample/discuss/1025177/Python3-statistics | class Solution:
def sampleStats(self, count: List[int]) -> List[float]:
total = sum(count)
mn = med0 = med1 = -1
psm = cnt = mode = 0
for i, x in enumerate(count):
if x:
if mn < 0: mn = i
mx = i
psm += i * x
cnt += x
if cnt >= (total+1)//2 and med0 < 0: med0 = i
if cnt >= (total+2)//2 and med1 < 0: med1 = i
if x > count[mode]: mode = i
return [mn, mx, psm/total, (med0+med1)/2, mode] | statistics-from-a-large-sample | [Python3] statistics | ye15 | 0 | 119 | statistics from a large sample | 1,093 | 0.444 | Medium | 17,383 |
https://leetcode.com/problems/car-pooling/discuss/1669593/Python3-STRAIGHTFORWARD-()-Explained | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
path = [0]*1000
for num, a, b in trips:
for loc in range (a, b):
path[loc] += num
if path[loc] > capacity: return False
return True | car-pooling | โค [Python3] STRAIGHTFORWARD (โฟโ โฟโ ), Explained | artod | 11 | 826 | car pooling | 1,094 | 0.573 | Medium | 17,384 |
https://leetcode.com/problems/car-pooling/discuss/2158946/PYTHON-or-SIMPLE-INUTITIVE-APPROACH-or-EXPLANATION-WITH-PICTURES-or | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
trips.sort(key = lambda x:x[2])
stations = trips[-1][-1]
people = [0]*(stations+1)
for count , start , end in trips:
people[start] += count
people[end] -= count
if people[0] > capacity: return False
for i in range(1,stations+1):
people[i] += people[i-1]
if people[i] > capacity: return False
return True | car-pooling | PYTHON | SIMPLE INUTITIVE APPROACH | EXPLANATION WITH PICTURES | | reaper_27 | 3 | 79 | car pooling | 1,094 | 0.573 | Medium | 17,385 |
https://leetcode.com/problems/car-pooling/discuss/2640751/Python-O(N)-Very-simple-to-understand | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
passangers = [0]*1001
# lazy propagation
for count, fr, to in trips:
if count > capacity: return False # optimization 1
passangers[fr] += count
passangers[to] -= count
# calculate now the exact passanger counts and see if we exceed capacity
for i in range(1, len(passangers)):
passangers[i] += passangers[i-1]
if passangers[i] > capacity:
return False
return True | car-pooling | Python O(N) Very simple to understand | ya332 | 1 | 94 | car pooling | 1,094 | 0.573 | Medium | 17,386 |
https://leetcode.com/problems/car-pooling/discuss/2164302/Python-sort | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
stops = []
for num, from_, to in trips:
stops.append((from_, num))
stops.append((to, -num))
stops.sort()
passengers = 0
for _, num in stops:
passengers += num
if passengers > capacity:
return False
return True | car-pooling | Python, sort | blue_sky5 | 1 | 40 | car pooling | 1,094 | 0.573 | Medium | 17,387 |
https://leetcode.com/problems/car-pooling/discuss/1866612/10-lines-code-or-O(nlogn)-or-minHeap-or-very-easy-or | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
uber = []
for psg, board, dest in trips: #No. of passengers, start(boarding), end(destination)
uber.append([board, psg])
uber.append([dest, -psg])
heapq.heapify(uber)
while uber:
loc, psg = heapq.heappop(uber)
capacity -= (psg)
if capacity < 0:
return False
return True
``` | car-pooling | 10 lines code | O(nlogn) | minHeap | very easy | | aamir1412 | 1 | 64 | car pooling | 1,094 | 0.573 | Medium | 17,388 |
https://leetcode.com/problems/car-pooling/discuss/1808070/The-simplest-python-solution-(no-sort) | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
counts = [0 for _ in range(1001)] # 0 ~ 1000
for num, f, t in trips:
for i in range(f, t):
counts[i] += num
return max(counts) <= capacity | car-pooling | The simplest python solution (no sort) | byuns9334 | 1 | 43 | car pooling | 1,094 | 0.573 | Medium | 17,389 |
https://leetcode.com/problems/car-pooling/discuss/1670807/Python-Prefix-Sum-Solution | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
last_drop=-1
for i in trips:
last_drop=max(last_drop,i[2])
events=[0]*(last_drop+1)
for pas,st,en in trips:
events[st]+=pas
events[en]-=pas
if events[0]>capacity:
return False
for i in range(1,len(events)):
events[i]=events[i]+events[i-1]
if events[i]>capacity:
return False
return True | car-pooling | Python Prefix Sum Solution | aryanagrawal2310 | 1 | 65 | car pooling | 1,094 | 0.573 | Medium | 17,390 |
https://leetcode.com/problems/car-pooling/discuss/1568472/Python-No-heapNo-sort-No-queuejust-use-list | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
ans = [0] * 1001
for i in trips:
n, l, r = i[0], i[1], i[2]
ans[l] += n
ans[r] -= n
pre = 0
for j in range(len(ans)):
pre += ans[j]
if pre > capacity:
return False
return True | car-pooling | Python/ No heap/No sort/ No queue/just use list | zixin123 | 1 | 62 | car pooling | 1,094 | 0.573 | Medium | 17,391 |
https://leetcode.com/problems/car-pooling/discuss/1546470/Easy-to-understand-oror-99.48-faster-oror-Greedy-. | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
seen = set()
dp = defaultdict(int)
for n,a,b in trips:
dp[a]+=n
dp[b]-=n
seen.add(a)
seen.add(b)
seen = sorted(list(seen))
occ = 0
for p in seen:
occ+=dp[p]
if occ>capacity:
return False
return True | car-pooling | ๐๐ Easy-to-understand || 99.48% faster || Greedy .๐ | abhi9Rai | 1 | 148 | car pooling | 1,094 | 0.573 | Medium | 17,392 |
https://leetcode.com/problems/car-pooling/discuss/843564/Python-3-(Py3.8)-or-Sweep-Line-Heap-or-Explanation-(Meeting-Room-II) | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
heap, cur = [], 0
for n, s, e in trips:
heapq.heappush(heap, (s, n))
heapq.heappush(heap, (e, -n))
while heap:
if (cur := cur + heapq.heappop(heap)[1]) > capacity: return False
return True | car-pooling | Python 3 (Py3.8) | Sweep Line, Heap | Explanation (Meeting Room II) | idontknoooo | 1 | 121 | car pooling | 1,094 | 0.573 | Medium | 17,393 |
https://leetcode.com/problems/car-pooling/discuss/2806004/python-solution-using-hashmap | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
hash_dict = {}
for i in trips:
s = i[1]
e = i[2]
for j in range(s , e):
if j in hash_dict:
hash_dict[j] += i[0]
else:
hash_dict[j] = i[0]
if hash_dict[j] > capacity:
return False
return True | car-pooling | python solution using hashmap | akashp2001 | 0 | 5 | car pooling | 1,094 | 0.573 | Medium | 17,394 |
https://leetcode.com/problems/car-pooling/discuss/2795792/Two-approaches%3A-O(N)-without-sorting-or-binary-search. | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
self.max_len = 1001
self.max_pickup, self.max_drop = 0, 0
self.pickuplist = [0]*self.max_len
self.droplist = [0]*self.max_len
for i in range(len(trips)):
trip = trips[i]
num_pax, pickup, drop = trip[0], trip[1], trip[2]
self.pickuplist[pickup] += num_pax
if pickup > self.max_pickup:
self.max_pickup = pickup
self.droplist[drop] += num_pax
if drop > self.max_drop:
self.max_drop = drop
curr_capacity = 0
for i in range(self.max_drop):
curr_capacity += self.pickuplist[i]
curr_capacity -= self.droplist[i]
if curr_capacity > capacity:
return False
return True | car-pooling | โ
Two approaches: O(N) without sorting or binary search. | sulabhkatiyar | 0 | 2 | car pooling | 1,094 | 0.573 | Medium | 17,395 |
https://leetcode.com/problems/car-pooling/discuss/2795792/Two-approaches%3A-O(N)-without-sorting-or-binary-search. | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
self.max_len = 1001
self.max_drop = 0
self.pax_list = [0]*self.max_len
for i in range(len(trips)):
trip = trips[i]
num_pax, pickup, drop = trip[0], trip[1], trip[2]
self.pax_list[pickup] += num_pax
# Decrement at drop instead of drop+1 (in range addition problem) since pax deboard here
self.pax_list[drop] -= num_pax
if drop > self.max_drop:
self.max_drop = drop
curr_capacity = 0
for i in range(self.max_drop):
curr_capacity += self.pax_list[i]
if curr_capacity > capacity:
return False
return True | car-pooling | โ
Two approaches: O(N) without sorting or binary search. | sulabhkatiyar | 0 | 2 | car pooling | 1,094 | 0.573 | Medium | 17,396 |
https://leetcode.com/problems/car-pooling/discuss/2786536/Prefix-sum-solution-by-UC-Berkeley-Computer-Science-Honor-Society. | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
"""
we want to calculate the maximum number of passengers at each interval.
since fromi and toi are both within 1000, we can use prefix sums!
let pref[i] represent the maximum number of passengers at time index i
we want to check if there's ever a case where pref[i] > capacity, and return false in that case.
"""
pref = [0] * 1001
for num, f, to in trips:
pref[f] += num
pref[to] -= num
for i in range(0, len(pref)):
if i > 0:
pref[i] += pref[i - 1]
if pref[i] > capacity:
return False
return True | car-pooling | Prefix sum solution by UC Berkeley Computer Science Honor Society. | berkeley_upe | 0 | 6 | car pooling | 1,094 | 0.573 | Medium | 17,397 |
https://leetcode.com/problems/car-pooling/discuss/2739759/difference-array | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
res = [0 for _ in range(1001)]
for trip in trips:
res[trip[1]] += trip[0]
res[trip[2]] -= trip[0]
temp = 0
for i in range(1001):
temp += res[i]
if temp > capacity:
return False
return True | car-pooling | difference array | kuroko_6668 | 0 | 2 | car pooling | 1,094 | 0.573 | Medium | 17,398 |
https://leetcode.com/problems/car-pooling/discuss/2736993/Delta-matters | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
delta = [0]*1001
for trip in trips:
delta[trip[1]] += trip[0]
delta[trip[2]] -= trip[0]
# Traverse spots in ascending order, check if cap > capacity
cap = 0
for d in delta:
cap += d
if cap > capacity:
return False
return True | car-pooling | Delta matters | KKCrush | 0 | 7 | car pooling | 1,094 | 0.573 | Medium | 17,399 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.