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-falling-path-sum/discuss/2678642/minFallingPathSum | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
if not matrix[0]:
return 0
dp = matrix[0]
for i in range(1, len(matrix)):
dp_new = matrix[i]
for j in range(len(matrix[i])):
if j == 0:
if j+1 < len(matrix[i]):
dp_new[j] += min(dp[j], dp[j+1])
else:
dp_new[j] += dp[j]
elif j == len(matrix) -1:
if j - 1 > -1:
dp_new[j] += min(dp[j], dp[j-1])
else:
dp_new[j] += dp[j]
else:
dp_new[j] += min(dp[j], dp[j-1], dp[j+1])
dp = dp_new
return min(dp) | minimum-falling-path-sum | minFallingPathSum | langtianyuyu | 0 | 3 | minimum falling path sum | 931 | 0.685 | Medium | 15,100 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/2676742/DPpython | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
n = len(matrix)
res = []
memo = [[-1 for _ in range(n)]for _ in range(n)]
def dp(i,j):
if(i > n-1 or j > n-1 or i < 0 or j < 0):
return float('inf')
if memo[i][j] != -1:
return memo[i][j]
if i == 0:
memo[i][j] = matrix[i][j]
return matrix[i][j]
memo[i][j] = min(dp(i-1,j),dp(i-1,j-1),dp(i-1,j+1))+matrix[i][j]
return memo[i][j]
for x in range(n):
res.append(dp(n-1,x))
return min(res) | minimum-falling-path-sum | [DP]python | kuroko_6668 | 0 | 18 | minimum falling path sum | 931 | 0.685 | Medium | 15,101 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/2665707/Python3-or-DP-or-Modular-approach-or-Memory-efficient | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
rows, cols = len(matrix), len(matrix[0])
if rows == 1:
return min(matrix[0])
prev = [num for num in matrix[0]]
cur = [sys.maxsize for _ in range(cols)]
def getPrevSum(col):
if col < 0 or col >= cols:
return sys.maxsize
return prev[col]
for r in range(1, rows):
for c in range(cols):
left = getPrevSum(c-1)
center = getPrevSum(c)
right = getPrevSum(c+1)
cur[c] = matrix[r][c] + min(left, center, right)
prev = cur.copy()
return min(cur) | minimum-falling-path-sum | Python3 | DP | Modular approach | Memory efficient | Ploypaphat | 0 | 2 | minimum falling path sum | 931 | 0.685 | Medium | 15,102 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/2650131/Python-DP-Space-Optimized | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
n = len(matrix)
prev = [-1] * n
for j in range(n):
prev[j] = matrix[0][j]
for i in range(1, n):
cur = [-1] * n
for j in range(n):
ld, rd = 1e9, 1e9
up = matrix[i][j] + prev[j]
if j-1 >= 0:
ld = matrix[i][j] + prev[j-1]
if j+1 < n:
rd = matrix[i][j] + prev[j+1]
cur[j] = min(up, min(ld, rd))
prev = cur
mini = prev[0]
for j in range(n):
mini = min(mini, prev[j])
return mini | minimum-falling-path-sum | Python - DP - Space Optimized | kritikaparmar | 0 | 4 | minimum falling path sum | 931 | 0.685 | Medium | 15,103 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/2602803/python-dp-button-up-solution | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
n,m=len(matrix),len(matrix[0])
for i in range(1,n):
for j in range(m):
move=[]
if j-1>=0:
move.append(matrix[i-1][j-1])
if j+1<m:
move.append(matrix[i-1][j+1])
move.append(matrix[i-1][j])
matrix[i][j]+=min(move)
return min(matrix[-1]) | minimum-falling-path-sum | python dp button up solution | benon | 0 | 20 | minimum falling path sum | 931 | 0.685 | Medium | 15,104 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/2452008/Python-Simple-Python-Solution-100-Optimal-Solution-3-Different-Ans | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
dp = [[-1 for i in range(len(matrix[0]))] for j in range(len(matrix))]
def sol(i, j):
# Base Case
if dp[i][j] != -1:
return dp[i][j]
if i < 0:
return 0
# Logic of Recursion
lefdia = up = rigdia = 1e9
if j-1 >= 0:
lefdia = matrix[i][j] + sol(i-1, j-1)
up = matrix[i][j] + sol(i-1, j)
if j+1 < len(matrix[0]):
rigdia = matrix[i][j] + sol(i-1, j+1)
dp[i][j] = min(lefdia, up, rigdia)
return dp[i][j]
mini = 1e9
for j in range(len(matrix[0])-1, -1, -1):
mini = min(mini, sol( (len(matrix)-1), j))
# print(mini, j)
return mini | minimum-falling-path-sum | [ Python ] β
Simple Python Solution β
β
β
100% Optimal Solution 3 Different Ans | vaibhav0077 | 0 | 19 | minimum falling path sum | 931 | 0.685 | Medium | 15,105 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/2452008/Python-Simple-Python-Solution-100-Optimal-Solution-3-Different-Ans | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
dp = [[-1 for i in range(len(matrix[0]))] for j in range(len(matrix))]
# Base Case
for i in range(len(matrix[0])):
dp[0][i] = matrix[0][i]
for i in range(1 ,len(matrix)):
for j in range(len(matrix[0])):
lefdia = up = rigdia = 1e9
if j-1 >= 0:
lefdia = matrix[i][j] + dp[i-1][j-1]
up = matrix[i][j] + dp[i-1][j]
if j+1 < len(matrix[0]):
rigdia = matrix[i][j] + dp[i-1][j+1]
dp[i][j] = min(lefdia, up, rigdia)
mini = dp[len(matrix[0])-1][0]
for z in range(len(matrix[0])):
mini = min(mini, dp[len(matrix[0])-1][z])
return mini | minimum-falling-path-sum | [ Python ] β
Simple Python Solution β
β
β
100% Optimal Solution 3 Different Ans | vaibhav0077 | 0 | 19 | minimum falling path sum | 931 | 0.685 | Medium | 15,106 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/2452008/Python-Simple-Python-Solution-100-Optimal-Solution-3-Different-Ans | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
# Base Case
prev = [0 for i in range(len(matrix[0]))]
cur = [0 for i in range(len(matrix[0]))]
# Logic
for j in range(len(matrix[0])):
prev[j] = matrix[0][j]
for i in range(1 ,len(matrix)):
for j in range(len(matrix[0])):
lefdia = up = rigdia = 1e9
if j-1 >= 0:
lefdia = matrix[i][j] + prev[j-1]
up = matrix[i][j] + prev[j]
if j+1 < len(matrix[0]):
rigdia = matrix[i][j] + prev[j+1]
cur[j] = min(lefdia, up, rigdia)
prev = cur.copy()
return min(prev) | minimum-falling-path-sum | [ Python ] β
Simple Python Solution β
β
β
100% Optimal Solution 3 Different Ans | vaibhav0077 | 0 | 19 | minimum falling path sum | 931 | 0.685 | Medium | 15,107 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/2421757/PYTHON-or-IN-PLACE-or-DP-or-EASY | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
r = len(matrix)
c = len(matrix[0])
for i in range(len(matrix)-2,-1,-1):
m = 999999999
for j in range(0,len(matrix[0])):
if i+1<r and j-1>=0:
m = min(m,matrix[i+1][j-1])
if i+1<r:
m = min(m,matrix[i+1][j])
if i+1<r and j+1<c:
m = min(m,matrix[i+1][j+1])
matrix[i][j] += m
m = 999999999
return min(matrix[0]) | minimum-falling-path-sum | PYTHON | IN PLACE | DP | EASY | Brillianttyagi | 0 | 8 | minimum falling path sum | 931 | 0.685 | Medium | 15,108 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/2387466/Python3-Bottom-Up-w-Tabulation | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
n = len(matrix)
tabu = matrix[-1]
for i in range(n-2, -1, -1):
newTabu = matrix[i]
newTabu[0] += min(tabu[0], tabu[1])
newTabu[-1] += min(tabu[-1], tabu[-2])
for j in range(1, n-1):
newTabu[j] += min(tabu[j-1], tabu[j], tabu[j+1])
tabu = newTabu
return min(tabu) | minimum-falling-path-sum | [Python3] Bottom-Up w/ Tabulation | ruosengao | 0 | 6 | minimum falling path sum | 931 | 0.685 | Medium | 15,109 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/2322912/Python-soln-(recursion-%2B-memoization) | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
m, n = len(matrix), len(matrix[0])
lookup = {}
def minFp(i, j, lookup):
if j<0 or j>=n: return float('inf')
if i == 0:
return matrix[i][j]
if (i,j) in lookup:
return lookup[(i,j)]
straight = matrix[i][j] + minFp(i-1, j, lookup)
lD = matrix[i][j] + minFp(i-1, j-1, lookup)
rD = matrix[i][j] + minFp(i-1, j+1, lookup)
lookup[(i,j)] = min(straight, lD, rD)
return lookup[(i,j)]
minimumPath = float('inf')
for j in range(n):
curPath = minFp(n-1, j, lookup)
minimumPath = min(minimumPath, curPath)
return minimumPath | minimum-falling-path-sum | Python soln (recursion + memoization) | logeshsrinivasans | 0 | 24 | minimum falling path sum | 931 | 0.685 | Medium | 15,110 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/2080336/python-3-oror-dp-oror-O(n2)-O(1) | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
n = len(matrix)
for i in range(1, n):
matrix[i][0] += min(matrix[i - 1][0], matrix[i - 1][1])
matrix[i][-1] += min(matrix[i - 1][-2], matrix[i - 1][-1])
for j in range(1, n - 1):
matrix[i][j] += min(matrix[i - 1][j - 1], matrix[i - 1][j], matrix[i - 1][j + 1])
return min(matrix[-1]) | minimum-falling-path-sum | python 3 || dp || O(n^2) / O(1) | dereky4 | 0 | 35 | minimum falling path sum | 931 | 0.685 | Medium | 15,111 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/2066999/Python3-DP-Solution-Explained | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
length = len(matrix)
memo = [[20000] * length for _ in range(length)]
def dp(i, j):
nonlocal memo
if i < 0 or i >= length or j < 0 or j >= length:
return 100000
if i == 0:
return matrix[i][j]
if memo[i][j] != 20000:
return memo[i][j]
memo[i][j] = matrix[i][j] + min(dp(i - 1, j - 1), dp(i - 1, j), dp(i - 1, j + 1))
return memo[i][j]
res = float('inf')
for p in range(length):
res = min(res, dp(length - 1, p))
return res | minimum-falling-path-sum | Python3 DP Solution Explained | TongHeartYes | 0 | 20 | minimum falling path sum | 931 | 0.685 | Medium | 15,112 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/2066790/Python-or-DP | class Solution:
def minFallingPathSum(self, ma: List[List[int]]) -> int:
for i in range(len(ma)-2,-1,-1):
for j in range(len(ma[0])):
if j==0:
ma[i][j] += min(ma[i+1][j],ma[i+1][j+1])
elif j==len(ma[0])-1:
ma[i][j] += min(ma[i+1][j-1],ma[i+1][j])
else:
ma[i][j] += min(ma[i+1][j-1],ma[i+1][j],ma[i+1][j+1])
return min(ma[0]) | minimum-falling-path-sum | Python | DP | Shivamk09 | 0 | 19 | minimum falling path sum | 931 | 0.685 | Medium | 15,113 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/2030273/Python-Solution-or-Easy-To-Understand-or-Explanation-or-Dynamic-Programming | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
rows = len(matrix)
cols = len(matrix[0])
for r in range(rows):
for c in range(cols):
# Non edge column
if r > 0 and 0 <= c - 1 and c + 1 < cols:
matrix[r][c] = min(matrix[r][c] + matrix[r-1][c], matrix[r][c] + matrix[r-1][c+1], matrix[r][c] + matrix[r-1][c-1])
# Left column
elif r > 0 and c - 1 == -1:
matrix[r][c] = min(matrix[r][c] + matrix[r-1][c], matrix[r][c] + matrix[r-1][c+1])
# Right Column
elif r > 0 and c + 1 == cols:
matrix[r][c] = min(matrix[r][c] + matrix[r-1][c], matrix[r][c] + matrix[r-1][c-1])
return min(matrix[rows-1])
``` | minimum-falling-path-sum | Python Solution | Easy To Understand | Explanation | Dynamic Programming | e_claire | 0 | 18 | minimum falling path sum | 931 | 0.685 | Medium | 15,114 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/1887414/WEEB-DOES-PYTHONC%2B%2B-DP-MEMOIZATION | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
row, col = len(matrix), len(matrix[0])
dp = []
result = float("inf")
# edge case
if row == 1:
return matrix[0][0]
for i in range(row):
temp = []
for j in range(col):
if i == 0:
temp.append(matrix[i][j])
else:
temp1 = dp[i-1][j]
temp2, temp3 = float("inf"), float("inf")
if j+1 < col:
temp2 = dp[i-1][j+1]
if j-1 >= 0:
temp3 = dp[i-1][j-1]
curVal = matrix[i][j] + min(temp1, temp2 ,temp3)
temp.append(curVal)
if i == row-1:
if curVal < result:
result = curVal
dp.append(temp)
return result | minimum-falling-path-sum | WEEB DOES PYTHON/C++ DP MEMOIZATION | Skywalker5423 | 0 | 53 | minimum falling path sum | 931 | 0.685 | Medium | 15,115 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/1884846/PYTHON-SOL-oror-QUADRATIC-TIME-oror-EASY-oror-EXPLAINED-oror | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
n = len(matrix)
for i in range(1,n):
for j in range(n):
up = matrix[i-1][j]
left = matrix[i-1][j-1] if j>0 else float('inf')
right = matrix[i-1][j+1] if j+1<n else float('inf')
matrix[i][j] += min(up,left,right)
return min(matrix[-1]) | minimum-falling-path-sum | PYTHON SOL || QUADRATIC TIME || EASY || EXPLAINED || | reaper_27 | 0 | 32 | minimum falling path sum | 931 | 0.685 | Medium | 15,116 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/1833022/python-solution-with-comment | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
m, n = len(matrix), len(matrix[0])
prev, dp = matrix[0], [sys.maxsize for i in range(n)] # dp is going to store the res of mixing previous row and
# current row
for r in range(1, m):
for c in range(0, n):
dp[c] = min(dp[c], # dp always keeps the smallest res
matrix[r][c] + min(prev[max(0, c-1)], # using "max" to avoid out of range
prev[c],
prev[min(n-1, c+1)])) # using "min" to avoid out of range
prev, dp = dp, [sys.maxsize for i in range(n)] # after doing current row, update prev to dp, and set
# dp to"inf" again
return min(prev) | minimum-falling-path-sum | python solution with comment | byroncharly3 | 0 | 27 | minimum falling path sum | 931 | 0.685 | Medium | 15,117 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/1768814/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up) | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
m = len(matrix)
n = len(matrix[0])
@lru_cache(None)
def dp(row: int, column: int) -> int:
ways = matrix[row][column]
if row == 0:
return ways
if column > 0 and column < n-1:
ways += min(
dp(row-1, column-1), dp(row-1, column), dp(row-1, column+1))
elif column > 0:
ways += min(
dp(row-1, column-1), dp(row-1, column))
elif column < n-1:
ways += min(
dp(row-1, column), dp(row-1, column+1))
return ways
return min(dp(m-1, i) for i in range(n)) | minimum-falling-path-sum | β
[Java / Python3] Simple DP Solution (Top-Down & Bottom-Up) | JawadNoor | 0 | 46 | minimum falling path sum | 931 | 0.685 | Medium | 15,118 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/1768814/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up) | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
m, n = len(matrix), len(matrix[0])
dp = [[0]*n for _ in range(m)]
for i in range(n):
dp[0][i] = matrix[0][i]
for row in range(1, m):
for column in range(n):
dp[row][column] += matrix[row][column]
if column > 0 and column < n-1:
dp[row][column] += min(
dp[row-1][column-1], dp[row-1][column], dp[row-1][column+1])
elif column > 0:
dp[row][column] += min(
dp[row-1][column-1], dp[row-1][column])
elif column < n-1:
dp[row][column] += min(
dp[row-1][column], dp[row-1][column+1])
return min(dp[m-1][i] for i in range(n)) | minimum-falling-path-sum | β
[Java / Python3] Simple DP Solution (Top-Down & Bottom-Up) | JawadNoor | 0 | 46 | minimum falling path sum | 931 | 0.685 | Medium | 15,119 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/1723460/Python-3-or-Recursive-and-Iterative-Solutions | class Solution:
def minFallingPathSum(self, m: List[List[int]]) -> int:
#Recursive Solution
n = len(m)
memo = {}
def rec(i, j) :
if (i,j) in memo :
return memo[(i,j)]
if i == n-1 :
return m[i][j]
else:
a = b = math.inf
if j-1>=0 :
a = rec(i+1,j-1)
if j+1 < n :
b = rec(i+1,j+1)
c = rec(i+1,j)
memo[(i,j)] = m[i][j] + min(a, b, c)
return memo[(i,j)]
res = math.inf
for x in range(n) :
res = min(res, rec(0, x))
return res
#Iterative Solution
n = len(m)
for row in range(1,n) :
for col in range(n) :
if col == 0 :
m[row][col] += min(m[row-1][col], m[row-1][col+1])
elif col == n-1 :
m[row][col] += min(m[row-1][col], m[row-1][col-1])
else:
m[row][col] += min(m[row-1][col], m[row-1][col-1], m[row-1][col+1])
return min(m[-1]) | minimum-falling-path-sum | Python 3 | Recursive and Iterative Solutions | abhijeetgupto | 0 | 24 | minimum falling path sum | 931 | 0.685 | Medium | 15,120 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/1529057/99.77-less-memory-usage(but-quite-slow) | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
minEle = 101
for i in range(len(matrix)-1, 0, -1):
for j in range(len(matrix[0])):
minEle = matrix[i][j]
if j-1 >= 0: minEle = min(matrix[i][j-1], minEle)
if j+1 < len(matrix[0]): minEle = min(matrix[i][j+1], minEle)
matrix[i-1][j] += minEle
return min(matrix[0]) | minimum-falling-path-sum | 99.77% less memory usage(but quite slow) | siddp6 | 0 | 42 | minimum falling path sum | 931 | 0.685 | Medium | 15,121 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/1513968/Python-Solution-using-Matrix-Chain-Multiplication | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
dp=[[None for i in range(len(matrix))] for j in range(len(matrix))]
def solve(matrix, i,j):
nonlocal dp
if i<0 or j<0 or j==len(matrix):
return float('inf')
if dp[i][j]:
return dp[i][j]
if i==len(matrix)-1:
dp[i][j] = matrix[i][j]
return matrix[i][j]
for k in range(len(matrix)):
temp_ans = min(solve(matrix, i+1,k-1),
solve(matrix, i+1, k),
solve(matrix, i+1, k+1))
res = matrix[i][k]+temp_ans
dp[i][k] = res
return dp[i][j]
solve(matrix,0,0)
return min(dp[0]) | minimum-falling-path-sum | Python Solution using Matrix Chain Multiplication | OkabeRintaro | 0 | 59 | minimum falling path sum | 931 | 0.685 | Medium | 15,122 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/1498345/Python-O(n2)-time-O(1)-space-solution | class Solution:
def minFallingPathSum(self, arr: List[List[int]]) -> int:
n = len(arr)
for i in range(1, n):
for j in range(0, n):
if j == 0:
arr[i][j] = min(arr[i-1][j], arr[i-1][j+1]) + arr[i][j]
elif j >0 and j < n-1:
arr[i][j] = min(arr[i-1][j-1], arr[i-1][j], arr[i-1][j+1]) + arr[i][j]
else: # j == n-1
arr[i][j] = min(arr[i-1][j-1], arr[i-1][j]) + arr[i][j]
return min(arr[n-1]) | minimum-falling-path-sum | Python O(n^2) time, O(1) space solution | byuns9334 | 0 | 56 | minimum falling path sum | 931 | 0.685 | Medium | 15,123 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/1476279/Easy-DP-solution-with-explanationoror-Python3oror-Dynamic-Programming | class Solution:
def minFallingPathSum(self, mat: List[List[int]]) -> int:
# Creating the DP array
dp = [[0 for _ in range(len(mat))] for _ in range(len(mat))]
# Storing the elements of first row
for j in range(len(mat)):
dp[0][j] = mat[0][j]
for i in range(1,len(mat)):
for j in range(len(mat)):
# valid for len(matrix)<=2 and j==0
if j==0 and j+1<len(mat):
dp[i][j] = mat[i][j]+min(dp[i-1][j],dp[i-1][j+1])
# valid for len(matrix)<=2 and j==len(matrix)-1
if j==(len(mat)-1) and (j-1)>=0:
dp[i][j] = mat[i][j]+min(dp[i-1][j],dp[i-1][j-1])
# checks if matrix length is greater than 3 and index 'j' is between
# 0 and len(matrix)-1
elif len(mat)>=3 and j>0 and j<len(mat)-1:
dp[i][j] = mat[i][j]+min(dp[i-1][j],dp[i-1][j-1],dp[i-1][j+1])
#print(dp)
# Returning the min value of the last row of DP array
return min(dp[-1]) | minimum-falling-path-sum | Easy DP solution with explanation|| Python3|| Dynamic Programming | ce17b127 | 0 | 36 | minimum falling path sum | 931 | 0.685 | Medium | 15,124 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/1434839/Python-3-beginner-friendly-solution-easy-and-concise | class Solution:
def gP(self,matrix,ri,ci):
coords = []
if ci==0:
coords = [ ci,ci+1 ]
elif ci==len(matrix)-1:
coords = [ ci-1,ci ]
else:
coords = [ ci-1,ci,ci+1 ]
points=[]
for cc in coords:
try:
points.append(matrix[ri-1][cc])
except:
print('ee',coords,ri,ci)
return min(points)
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
for ri in range(1,len(matrix)):
for ci in range(0,len(matrix)):
matrix[ri][ci]+=self.gP(matrix,ri,ci)
return min(matrix[-1]) | minimum-falling-path-sum | Python 3 beginner friendly solution easy and concise | mathur17021play | 0 | 57 | minimum falling path sum | 931 | 0.685 | Medium | 15,125 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/1325475/Python3-solution-using-dynamic-programming | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
for i in range(len(matrix)-2,-1,-1):
for j in range(len(matrix)-1,-1,-1):
if j == 0:
matrix[i][j] = matrix[i][j] + min(matrix[i+1][j], matrix[i+1][j+1])
elif j == len(matrix)-1:
matrix[i][j] = matrix[i][j] + min(matrix[i+1][j], matrix[i+1][j-1])
else:
matrix[i][j] = matrix[i][j] + min([matrix[i+1][j], matrix[i+1][j+1], matrix[i+1][j-1]])
return min(matrix[0]) | minimum-falling-path-sum | Python3 solution using dynamic programming | EklavyaJoshi | 0 | 20 | minimum falling path sum | 931 | 0.685 | Medium | 15,126 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/1113047/Python-simple-4-line-DP-solution | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
for r in range(1, len(matrix)):
for c in range(len(matrix[0])):
matrix[r][c] += min(matrix[r-1][max(0, c-1):c+2])
return min(matrix[-1]) | minimum-falling-path-sum | Python simple 4 line DP solution | stom1407 | 0 | 85 | minimum falling path sum | 931 | 0.685 | Medium | 15,127 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/1070925/Python-Easy-Solution-88-memory-efficient-65-faster | class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
n = len(matrix)
dp = [[0] * n for _ in range(n)]
dp[n-1] = [matrix[n-1][j] for j in range(n)]
for i in reversed(range(n-1)):
for j in range(n):
minimumPath = dp[i+1][j]
if j-1 >= 0:
minimumPath = min(minimumPath, dp[i+1][j-1])
if j+1 < n:
minimumPath = min(minimumPath, dp[i+1][j+1])
dp[i][j] = matrix[i][j] + minimumPath
return min(dp[0]) | minimum-falling-path-sum | Python Easy Solution 88% memory efficient 65% faster | reachrishav1 | 0 | 40 | minimum falling path sum | 931 | 0.685 | Medium | 15,128 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/750330/Python-Breakdown-and-optimization | class Solution:
def minFallingPathSum(self, A: List[List[int]]) -> int:
# these are the possible moves
moves = [(-1, 0), (-1, -1), (-1, 1)]
rows = len(A)
cols = len(A[0])
# usual bs
if rows == 0: return 0
if rows == 1: return A[0][0]
# for saving the minimum cost at position
path_sums = [[0 for _ in range(rows)] for _ in range(cols)]
# if we can move from i => i + x and from y => y + j
def can_move(i, j, x, y): return 0 <= i+x < rows and 0 <= j+y < cols
# helper, get value at cell (i+x, y+j)
def get_cell(i, j, x, y): return path_sums[i+x][j+y]
# fill top
for i in range(rows): path_sums[0][i] = A[0][i]
for i in range(1, rows):
for j in range(0, cols):
cell = [i, j]
# get the minimum of the values at position for possibile movements and add the current cell value
values = [get_cell(*cell, *move) for move in moves if can_move(*cell, *move)]
path_sums[i][j] = min(values) + A[i][j]
# the last row will have the fallen values and the minimum of that is the answer
return min(path_sums[-1]) | minimum-falling-path-sum | [Python] Breakdown and optimization | ikouchiha47 | 0 | 67 | minimum falling path sum | 931 | 0.685 | Medium | 15,129 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/750330/Python-Breakdown-and-optimization | class Solution:
def minFallingPathSum(self, A: List[List[int]]) -> int:
# this is the resultant array, initially set to cache the top row
# because top row has no movemenent to compute
min_sums = A[0]
# helpers
# clamp the value to 0
def clamp_zero(i): return max(i, 0)
# get the minimum from start to end
def min_of(arr, start, end): return min(arr[clamp_zero(start):end])
# for all rows from 1th index,
# calculate the minimum at each column and set it as the new resultant array (folding)
for row in A[1:]:
min_sums_row = []
for c, val in enumerate(row):
min_sums_row.append( val + min_of(min_sums, c-1, c+2) )
min_sums = min_sums_row
return min(min_sums) | minimum-falling-path-sum | [Python] Breakdown and optimization | ikouchiha47 | 0 | 67 | minimum falling path sum | 931 | 0.685 | Medium | 15,130 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/461783/Python3-simple-fast-solution | class Solution:
def minFallingPathSum(self, A: List[List[int]]) -> int:
for i in range(1,len(A)):
for j in range(len(A[0])):
left,right = A[i-1][j-1] if j-1>=0 else float("inf"),A[i-1][j+1] if j+1<len(A[0]) else float("inf")
A[i][j] += min(A[i-1][j],left,right)
return min(A[-1]) | minimum-falling-path-sum | Python3 simple fast solution | jb07 | -1 | 46 | minimum falling path sum | 931 | 0.685 | Medium | 15,131 |
https://leetcode.com/problems/minimum-falling-path-sum/discuss/390878/Solution-in-Python-3-(beats-~99)-(three-lines)-(DP)-(-O(1)-space-) | class Solution:
def minFallingPathSum(self, A: List[List[int]]) -> int:
L, A, m = len(A), [[math.inf] + i + [math.inf] for i in A], math.inf
for i,j in itertools.product(range(1,L),range(1,L+1)): A[i][j] += min(A[i-1][j-1],A[i-1][j],A[i-1][j+1])
return min(A[-1])
- Junaid Mansuri
(LeetCode ID)@hotmail.com | minimum-falling-path-sum | Solution in Python 3 (beats ~99%) (three lines) (DP) ( O(1) space ) | junaidmansuri | -1 | 125 | minimum falling path sum | 931 | 0.685 | Medium | 15,132 |
https://leetcode.com/problems/beautiful-array/discuss/1368125/Detailed-Explanation-with-Diagrams.-A-Collection-of-Ideas-from-Multiple-Posts.-Python3 | class Solution:
def recurse(self, nums):
if len(nums) <= 2: return nums
return self.recurse(nums[::2]) + self.recurse(nums[1::2])
def beautifulArray(self, n: int) -> List[int]:
return self.recurse([i for i in range(1, n+1)]) | beautiful-array | Detailed Explanation with Diagrams. A Collection of Ideas from Multiple Posts. [Python3] | chaudhary1337 | 45 | 1,500 | beautiful array | 932 | 0.651 | Medium | 15,133 |
https://leetcode.com/problems/beautiful-array/discuss/1368125/Detailed-Explanation-with-Diagrams.-A-Collection-of-Ideas-from-Multiple-Posts.-Python3 | class Solution:
def beautifulArray(self, n: int) -> List[int]:
return sorted(range(1, n+1), key=lambda x: bin(x)[:1:-1]) | beautiful-array | Detailed Explanation with Diagrams. A Collection of Ideas from Multiple Posts. [Python3] | chaudhary1337 | 45 | 1,500 | beautiful array | 932 | 0.651 | Medium | 15,134 |
https://leetcode.com/problems/beautiful-array/discuss/644612/Python3-solution-with-detailed-explanation-Beautiful-Array | class Solution:
def beautifulArray(self, N: int) -> List[int]:
nums = list(range(1, N+1))
def helper(nums) -> List[int]:
if len(nums) < 3:
return nums
even = nums[::2]
odd = nums[1::2]
return helper(even) + helper(old)
return helper(nums) | beautiful-array | Python3 solution with detailed explanation - Beautiful Array | r0bertz | 13 | 1,100 | beautiful array | 932 | 0.651 | Medium | 15,135 |
https://leetcode.com/problems/beautiful-array/discuss/1184882/Python3-divide-and-conquer | class Solution:
def beautifulArray(self, N: int) -> List[int]:
def fn(nums):
"""Return beautiful array by rearraning elements in nums."""
if len(nums) <= 1: return nums
return fn(nums[::2]) + fn(nums[1::2])
return fn(list(range(1, N+1))) | beautiful-array | [Python3] divide & conquer | ye15 | 3 | 329 | beautiful array | 932 | 0.651 | Medium | 15,136 |
https://leetcode.com/problems/beautiful-array/discuss/1184882/Python3-divide-and-conquer | class Solution:
def beautifulArray(self, n: int) -> List[int]:
ans = [1]
while len(ans) < n:
ans = [2*x-1 for x in ans] + [2*x for x in ans]
return [x for x in ans if x <= n] | beautiful-array | [Python3] divide & conquer | ye15 | 3 | 329 | beautiful array | 932 | 0.651 | Medium | 15,137 |
https://leetcode.com/problems/beautiful-array/discuss/1368199/Python3-recursive-one-liner | class Solution:
def beautifulArray(self, n: int) -> List[int]:
return (
[1, 2][:n]
if n < 3
else [x * 2 - 1 for x in self.beautifulArray((n + 1) // 2)]
+ [x * 2 for x in self.beautifulArray(n // 2)]
) | beautiful-array | Python3, recursive one-liner | MihailP | 2 | 247 | beautiful array | 932 | 0.651 | Medium | 15,138 |
https://leetcode.com/problems/shortest-bridge/discuss/958926/Python3-DFS-and-BFS | class Solution:
def shortestBridge(self, A: List[List[int]]) -> int:
m, n = len(A), len(A[0])
i, j = next((i, j) for i in range(m) for j in range(n) if A[i][j])
# dfs
stack = [(i, j)]
seen = set(stack)
while stack:
i, j = stack.pop()
seen.add((i, j)) # mark as visited
for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):
if 0 <= ii < m and 0 <= jj < n and A[ii][jj] and (ii, jj) not in seen:
stack.append((ii, jj))
seen.add((ii, jj))
# bfs
ans = 0
queue = list(seen)
while queue:
newq = []
for i, j in queue:
for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):
if 0 <= ii < m and 0 <= jj < n and (ii, jj) not in seen:
if A[ii][jj] == 1: return ans
newq.append((ii, jj))
seen.add((ii, jj))
queue = newq
ans += 1 | shortest-bridge | [Python3] DFS & BFS | ye15 | 7 | 512 | shortest bridge | 934 | 0.54 | Medium | 15,139 |
https://leetcode.com/problems/shortest-bridge/discuss/1885160/PYTHON-SOL-oror-BFS-%2B-DFS-oror-WELL-WRITTEN-oror-EXPLAINED-oror | class Solution:
def shortestBridge(self, grid: List[List[int]]) -> int:
n = len(grid)
island = []
def dfs(row,col):
grid[row][col] = 2
island.append((row,col,0))
moves = ((row+1,col),(row-1,col),(row,col+1),(row,col-1))
for x,y in moves:
if 0<=x<n and 0<=y<n and grid[x][y] == 1:
dfs(x,y)
flag = True
for i in range(n):
for j in range(n):
if grid[i][j] == 1:
dfs(i,j)
flag = False
break
if not flag:break
queue = island
while queue:
r,c,dis = queue.pop(0)
if grid[r][c] == 1:return dis
moves = ((r+1,c),(r-1,c),(r,c-1),(r,c+1))
for x,y in moves:
if 0<=x<n and 0<=y<n and grid[x][y]!=2:
if grid[x][y] == 1:return dis
grid[x][y] = 2
queue.append((x,y,dis+1))
return -1 | shortest-bridge | PYTHON SOL || BFS + DFS || WELL WRITTEN || EXPLAINED || | reaper_27 | 2 | 277 | shortest bridge | 934 | 0.54 | Medium | 15,140 |
https://leetcode.com/problems/shortest-bridge/discuss/1674552/Python-Easy-understanding-solution-Find-smallest-distance-between-2-disconnected-components | class Solution:
def isBoundary(self, grid, point) -> bool:
x,y = point[0], point[1]
if x-1 < 0 or y-1 < 0 or x+1 >= len(grid) or y+1 >= len(grid[x]): return True
if grid[x-1][y] == 0: return True
if grid[x+1][y] == 0: return True
if grid[x][y-1] == 0: return True
if grid[x][y+1] == 0: return True
return False
def dfs(self, grid, start, visited):
x, y = start[0], start[1]
if x < 0 or y < 0 or x >= len(grid) or y >= len(grid[x]) or grid[x][y] != 1: return
if start not in visited:
visited.add(start)
self.dfs(grid, (x+1, y), visited)
self.dfs(grid, (x, y+1), visited)
self.dfs(grid, (x-1, y), visited)
self.dfs(grid, (x, y-1), visited)
def shortestBridge(self, grid: List[List[int]]) -> int:
# find the shortest distance between 2 disconnected components
island1, island2, positionsOfLand = set(), set(), set()
for x in range(len(grid)):
for y in range(len(grid[x])):
if grid[x][y] == 1: positionsOfLand.add((x,y))
for each in positionsOfLand:
self.dfs(grid, each, island1)
break
for each in positionsOfLand - island1:
self.dfs(grid, each, island2)
break
boundary1 = [each for each in island1 if self.isBoundary(grid, each)]
boundary2 = [each for each in island2 if self.isBoundary(grid, each)]
answer = float("inf")
for each1 in boundary1:
for each2 in boundary2:
x1, y1 = each1[0], each1[1]
x2, y2 = each2[0], each2[1]
answer = min(answer, (abs(x1-x2) + abs(y1-y2) - 1))
if answer == 1: break
return answer | shortest-bridge | [Python] Easy-understanding solution - Find smallest distance between 2 disconnected components | freetochoose | 2 | 247 | shortest bridge | 934 | 0.54 | Medium | 15,141 |
https://leetcode.com/problems/shortest-bridge/discuss/2286355/DFS-to-get-island1-and-BFS-to-get-the-steps(similar-to-rotten-oranges) | class Solution:
def shortestBridge(self, grid: List[List[int]]) -> int:
n, result, queue = len(grid), 0, []
def dfs(i,j):
queue.append((i,j))
grid[i][j] = -1
for x,y in [(0,-1), (0,1), (-1, 0), (1,0)]:
xi,yj = x+i,y+j
if 0<=xi< n and 0<=yj< n and grid[xi][yj] == 1:
dfs(xi, yj)
found = False
for i in range(n):
if found:
break
j = 0
while not found and j<n:
if grid[i][j] == 1:
dfs(i,j)
found = True
break
j+=1
while queue:
for _ in range(len(queue)):
i,j = queue.pop(0)
for x,y in [(0,-1), (0,1), (-1, 0), (1,0)]:
xi,yj = x+i,y+j
if 0<=xi<n and 0<=yj<n and grid[xi][yj] != -1:
if grid[xi][yj] == 1:
return result
elif grid[xi][yj] == 0:
queue.append((xi,yj))
grid[xi][yj] = -1
result+=1 | shortest-bridge | π DFS to get island1 and BFS to get the steps(similar to rotten oranges) | Dark_wolf_jss | 1 | 53 | shortest bridge | 934 | 0.54 | Medium | 15,142 |
https://leetcode.com/problems/shortest-bridge/discuss/2260402/oror-Python-oror-SPLIT-ISLAND-METHODoror-logic-explainedoror-Explanation-and-comments | class Solution:
def shortestBridge(self, grid: List[List[int]]) -> int:
n=len(grid)
#to print the grid current state
#def printgrid():
#for i in range(n):
#for j in range(n):
#print(grid[i][j],end=" ")
#print()
#print()
# printgrid()
i1=[]
#to make a island
def dfs(i,j):
#print(i,j)
if 0<=i<n and 0<=j<n and grid[i][j]==1:
i1.append((i,j,0))
grid[i][j]=2
dfs(i+1,j)
dfs(i-1,j)
dfs(i,j+1)
dfs(i,j-1)
return
return
#this finds the 1st 1 and we call the dfs and the island is created
#breaker is to make sure that we only run the dfs function once
breaker =False
for i in range(n):
for j in range(n):
if grid[i][j]:
dfs(i,j)
breaker=True
break
if breaker:
break
# printgrid()
# print(i1)
dir=[(1,0),(-1,0),(0,1),(0,-1)]
while i1:
i,j,d=i1.pop(0)
# print(f"i={i} j={j} d={d}")
#base condition for the case where we find the ans
if grid[i][j]==1:
return d
for dc,dr in dir:
p,q=dr+i,dc+j
if 0<=p<n and 0<=q<n and grid[p][q]!=2:
if grid[p][q]==1:
return d
grid[p][q]=2
i1.append((p,q,d+1))
# printgrid() | shortest-bridge | β
|| Python || SPLIT ISLAND METHOD|| logic explained|| Explanation and comments | HarshVardhan71 | 1 | 74 | shortest bridge | 934 | 0.54 | Medium | 15,143 |
https://leetcode.com/problems/shortest-bridge/discuss/1474075/WEEB-DOES-PYTHON-BFS | class Solution:
def shortestBridge(self, grid: List[List[int]]) -> int:
row, col = len(grid), len(grid[0])
queue1, queue2 = deque([]), deque([])
count = 0
for x in range(row):
if count == 1: break
for y in range(col):
if grid[x][y] == 1:
count+=1
queue1.append((x,y))
queue2.append((x,y))
while queue1:
x,y = queue1.popleft()
if grid[x][y] == "X": continue
grid[x][y] = "X"
for nx,ny in [[x+1,y],[x-1,y],[x,y+1],[x,y-1]]:
if 0<=nx<row and 0<=ny<col and grid[nx][ny] == 1:
queue1.append((nx,ny))
queue2.append((nx,ny))
break
return self.bfs(grid, row, col, queue2)
def bfs(self, grid, row, col, queue):
steps = 0
while queue:
for _ in range(len(queue)):
x,y = queue.popleft()
if grid[x][y] == "V": continue
grid[x][y] = "V"
for nx,ny in [[x+1,y],[x-1,y],[x,y+1],[x,y-1]]:
if 0<=nx<row and 0<=ny<col:
if grid[nx][ny] == 0:
queue.append((nx,ny))
if grid[nx][ny] == 1:
return steps
steps+=1 | shortest-bridge | WEEB DOES PYTHON BFS | Skywalker5423 | 1 | 207 | shortest bridge | 934 | 0.54 | Medium | 15,144 |
https://leetcode.com/problems/shortest-bridge/discuss/2166714/Unique-Solution-oror-No-Expanding-Required-oror-Only-DFS-oror-No-BFS-oror-Manhattan-Distance | class Solution:
def isBoundary(self, grid, point):
x = point[0]
y = point[1]
n = len(grid)
if x - 1 < 0 or y - 1 < 0 or x + 1 >= n or y + 1 >= n:
return True
if grid[x-1][y] == 0:
return True
elif grid[x+1][y] == 0:
return True
elif grid[x][y-1] == 0:
return True
elif grid[x][y+1] == 0:
return True
return False
def isSafe(self,i,j,grid):
n = len(grid)
if 0 <= i < n and 0 <= j < n:
return True
else:
return False
def dfs(self,i,j,grid,coordinates):
if not self.isSafe(i,j,grid) or grid[i][j] != 1:
return
coordinates.append([i,j])
grid[i][j] = 2
self.dfs(i - 1, j, grid, coordinates)
self.dfs(i + 1, j, grid, coordinates)
self.dfs(i, j - 1, grid, coordinates)
self.dfs(i, j + 1, grid, coordinates)
return
def shortestBridge(self, grid: List[List[int]]) -> int:
coordinateList = []
n = len(grid)
for i in range(n):
for j in range(n):
if grid[i][j] == 1:
coordinates = []
self.dfs(i,j,grid,coordinates)
coordinateList.append(coordinates)
island1 = coordinateList[0]
island2 = coordinateList[1]
island1 = [point for point in island1 if self.isBoundary(grid,point)]
island2 = [point for point in island2 if self.isBoundary(grid,point)]
minZeros = float('inf')
for coor1 in island1:
x1 = coor1[0]
y1 = coor1[1]
for coor2 in island2:
x2 = coor2[0]
y2 = coor2[1]
distance = abs(x2 -x1) + abs(y2 - y1) - 1
minZeros = min(minZeros, distance)
if minZeros == 1:
break
return minZeros | shortest-bridge | Unique Solution || No Expanding Required || Only DFS || No BFS || Manhattan Distance | Vaibhav7860 | 0 | 52 | shortest bridge | 934 | 0.54 | Medium | 15,145 |
https://leetcode.com/problems/shortest-bridge/discuss/1905045/Python-Bread-First-Search-for-Graph | class Solution:
def shortestBridge(self, grid: List[List[int]]) -> int:
# ==== use BFS obtain positions of one land. Start from the land, and do BFS to find another land. Layer cost is the minimum distance ====
directions = [(0,1), (0,-1), (1,0), (-1,0)] # right, left, up, down
len_x = len(grid)
len_y = len(grid[0])
# find one point of a land
def one_land(grid):
for in_x, row in enumerate(grid):
for in_y, val in enumerate(row):
if val:
return (in_x, in_y)
# start from one point and get all position of a land
in_x, in_y = one_land(grid)
queue = [(in_x, in_y)]
first_land = [(in_x, in_y)] # temp queue to find the first land
from collections import defaultdict
visited = defaultdict(lambda:False, {})
visited[(in_x, in_y)] = True
# find positions of the first land
while first_land:
x, y = first_land.pop(0)
for dir_x, dir_y in directions:
nei_x = x + dir_x
nei_y = y + dir_y
if nei_x in range(len_x) and nei_y in range(len_y): # point in range
if grid[nei_x][nei_y]: # it is land
if not visited[(nei_x, nei_y)]:
first_land.append((nei_x, nei_y))
queue.append((nei_x, nei_y))
visited[(nei_x, nei_y)] = True
# # show first land
# for x, y in queue:
# print(x, y)
# print(grid[x][y])
# print("visited", visited)
# BFS
cost = 0
layer_size = 0
while queue:
layer_size = len(queue)
for i in range(layer_size):
x, y = queue.pop(0)
for dir_x, dir_y in directions:
nei_x = x + dir_x
nei_y = y + dir_y
if nei_x in range(len_x) and nei_y in range(len_y): # point in range
if not visited[(nei_x, nei_y)]:
if grid[nei_x][nei_y]: # it is land (second land)
return cost
else: # it is water
queue.append((nei_x, nei_y))
visited[(nei_x, nei_y)] = True
cost += 1
return None | shortest-bridge | Python - Bread First Search for Graph | wanzelin007 | 0 | 91 | shortest bridge | 934 | 0.54 | Medium | 15,146 |
https://leetcode.com/problems/shortest-bridge/discuss/1817649/Python-BFS | class Solution:
def shortestBridge(self, grid: List[List[int]]) -> int:
N = len(grid)
def get_neighbors(i, j):
for ni, nj in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):
if 0 <= ni < N and 0 <= nj < N:
yield ni, nj
# Find a piece of an island
start = None
for i in range(N):
for j in range(N):
if grid[i][j] == 1:
start = (i, j)
break
if start:
break
# BFS to find perimeter around one island
q = deque([start])
seen = set()
water = set()
while q:
i, j = q.popleft()
if (i, j) in seen:
continue
seen.add((i, j))
for ni, nj in get_neighbors(i, j):
if grid[ni][nj] == 0:
water.add((ni, nj))
else:
q.append((ni, nj))
# BFS from the perimeter out, until the other island is reached
q = deque(water)
res = 0
while q:
for _ in range(len(q)):
i, j = q.popleft()
if grid[i][j] == 1:
return res
for ni, nj in get_neighbors(i, j):
if (ni, nj) in seen:
continue
seen.add((ni, nj))
q.append((ni, nj))
res += 1 | shortest-bridge | Python BFS | mjgallag | 0 | 110 | shortest bridge | 934 | 0.54 | Medium | 15,147 |
https://leetcode.com/problems/shortest-bridge/discuss/1811777/Python-DFS-and-Multi-Source-BFS | class Solution:
def shortestBridge(self, grid: List[List[int]]) -> int:
rows, cols = len(grid), len(grid[0])
Coordinate = namedtuple('Coordinate', ['x', 'y'])
def withinBounds(pos):
return 0 <= pos.x < rows and 0 <= pos.y < cols
def dfs(pos, island, mark):
if withinBounds(pos) and grid[pos.x][pos.y] == 1:
island.append(pos)
grid[pos.x][pos.y] = mark
up = Coordinate(pos.x - 1, pos.y)
left = Coordinate(pos.x, pos.y - 1)
right = Coordinate(pos.x, pos.y + 1)
down = Coordinate(pos.x + 1, pos.y)
dfs(up, island, mark), dfs(left, island, mark), dfs(right, island, mark), dfs(down, island, mark)
# search and mark the first island as 4
# then change the mark to 8 and mark the second island as 8 and break
mark = 4
secondIsland = deque()
for i in range(rows):
for j in range(cols):
if grid[i][j] == 1:
dfs(Coordinate(i,j), secondIsland, mark) # this will only run twice
if mark == 8: break
else:
# clear first island data so we only append second island data in second iteration
secondIsland.clear()
mark = 8
else: continue
break
flips = 0
directions = ((0,1),(1,0),(-1,0),(0,-1))
grid[secondIsland[0].x][secondIsland[0].y] = 8
# just multisource bfs
while secondIsland:
for _ in range(len(secondIsland)):
pos = secondIsland.popleft()
for r, c in directions:
neigh = Coordinate(pos.x + r, pos.y + c)
if withinBounds(neigh) and grid[neigh.x][neigh.y] != 8:
if grid[neigh.x][neigh.y] == 4: # if a first island land is found then return the level
return flips
grid[neigh.x][neigh.y] = 8 # mark neighbors so we don't visit them again
secondIsland.append(neigh)
flips += 1
return -1 | shortest-bridge | Python DFS and Multi-Source BFS | Rush_P | 0 | 42 | shortest bridge | 934 | 0.54 | Medium | 15,148 |
https://leetcode.com/problems/shortest-bridge/discuss/1313900/python-dfs-to-mark-first-island-then-bfs-to-expand-from-it | class Solution:
def shortestBridge(self, grid: List[List[int]]) -> int:
rows, cols = len(grid), len(grid[0])
# Mark the first island with '#'s
def dfs(row, col):
if row not in range(rows) or col not in range(cols) or grid[row][col] != 1:
return False
grid[row][col] = '#'
dfs(row+1, col)
dfs(row-1, col)
dfs(row, col+1)
dfs(row, col-1)
# If the inner loop does not break, the outer loop will not either.
# The for-else clause only happens if the inner loop does not break. Then continue avoids the outer break too.
for row in range(rows):
for col in range(cols):
if grid[row][col] == 1:
dfs(row,col)
break
else:
continue # only executed if the inner loop did NOT break
break # only executed if the inner loop DID break
# Now let's expand from the first island we just marked and return the second we see the second island
shortest_bridge_distance = 0
q = deque([(r,c,shortest_bridge_distance) for r in range(rows) for c in range(cols) if grid[r][c] == '#'])
visited = set()
while q:
row, col, shortest_bridge_distance = q.popleft()
directions = ((row+1,col),(row-1,col),(row,col+1),(row,col-1))
for new_row, new_col in directions:
if new_row in range(rows) and new_col in range(cols) and (new_row,new_col) not in visited:
if grid[new_row][new_col] == 1:
return shortest_bridge_distance
q.append((new_row, new_col, shortest_bridge_distance+1))
visited.add((new_row,new_col)) | shortest-bridge | python dfs to mark first island then bfs to expand from it | uzumaki01 | 0 | 222 | shortest bridge | 934 | 0.54 | Medium | 15,149 |
https://leetcode.com/problems/knight-dialer/discuss/1544986/Python-simple-dp-O(n)-time-O(1)-space | class Solution:
def knightDialer(self, n: int) -> int:
arr = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
for _ in range(n-1):
dp = [0 for _ in range(10)]
dp[0] = arr[5] + arr[7]
dp[1] = arr[6] + arr[8]
dp[2] = arr[3] + arr[7]
dp[3] = arr[2] + arr[8] + arr[9]
dp[4] = 0
dp[5] = arr[0] + arr[6] + arr[9]
dp[6] = arr[1] + arr[5]
dp[7] = arr[0] + arr[2]
dp[8] = arr[1] + arr[3]
dp[9] = arr[3] + arr[5]
arr = dp
return sum(arr) % (10**9+7) | knight-dialer | Python simple dp, O(n) time O(1) space | byuns9334 | 3 | 493 | knight dialer | 935 | 0.5 | Medium | 15,150 |
https://leetcode.com/problems/knight-dialer/discuss/2761128/Python-DP.-Time%3A-O(N)-Space%3A-O(1) | class Solution:
def knightDialer(self, n: int) -> int:
dp = [1] * 10
moves = [[4, 6], [6, 8], [7, 9], [4, 8], [3, 9, 0], [],
[1, 7, 0], [2, 6], [1, 3], [2, 4]]
for _ in range(n-1):
dp_next = [0] * 10
for digit in range(10):
for move_digit in moves[digit]:
dp_next[digit] += dp[move_digit]
dp = dp_next
return sum(dp) % (10**9 + 7) | knight-dialer | Python, DP. Time: O(N), Space: O(1) | blue_sky5 | 2 | 145 | knight dialer | 935 | 0.5 | Medium | 15,151 |
https://leetcode.com/problems/knight-dialer/discuss/2136453/Python-somewhat-ok-solution | class Solution:
def knightDialer(self, n: int) -> int:
Mod = 10**9 + 7
pad = [
(4, 6), (8, 6), (7, 9), (4, 8), (3, 9, 0),
(), (1, 7, 0), (2, 6), (1, 3), (2, 4)
]
@cache
def dfs(i, n):
# search reached the end, found 1 solution
if n == 0: return 1
# search not reach the end, keep looking for solution for n - 1
return sum(dfs(nxt, n - 1) for nxt in pad[i]) % Mod
# starting from each number, count the total solution to n
# because placing the chess to i takes 1 count, so search for n - 1
return sum(dfs(i, n - 1) for i in range(10)) % Mod | knight-dialer | Python somewhat ok solution | t136280 | 1 | 98 | knight dialer | 935 | 0.5 | Medium | 15,152 |
https://leetcode.com/problems/knight-dialer/discuss/1923343/python3-DP-Top-Down | class Solution:
def knightDialer(self, n: int) -> int:
MOD = 10**9 + 7
adj = {
0: [6, 4],
1: [6, 8],
2: [9, 7],
3: [4, 8],
4: [9, 3, 0],
5: [],
6: [7, 1, 0],
7: [6, 2],
8: [3, 1],
9: [4, 2]
}
@cache
def res(k, num):
if k == 1:
return 1
else:
ret = 0
for i in adj[num]:
ret = (ret + res(k - 1, i)) % MOD
return ret
ans = 0
for i in range(10):
ans = (ans + res(n, i)) % MOD
return ans | knight-dialer | python3 DP Top-Down | DheerajGadwala | 1 | 149 | knight dialer | 935 | 0.5 | Medium | 15,153 |
https://leetcode.com/problems/knight-dialer/discuss/958867/Python3-dp-O(N) | class Solution:
def knightDialer(self, n: int) -> int:
mp = {0: [4, 6], 1: [6, 8], 2: [7, 9], 3: [4, 8], 4: [0, 3, 9],
5: [], 6: [0, 1, 7], 7: [2, 6], 8: [1, 3], 9: [2, 4]}
@lru_cache(None)
def fn(n, k):
"""Return """
if n == 1: return 1
ans = 0
for kk in mp[k]: ans += fn(n-1, kk)
return ans % 1_000_000_007
return sum(fn(n, k) for k in range(10)) % 1_000_000_007 | knight-dialer | [Python3] dp O(N) | ye15 | 1 | 202 | knight dialer | 935 | 0.5 | Medium | 15,154 |
https://leetcode.com/problems/knight-dialer/discuss/958867/Python3-dp-O(N) | class Solution:
def knightDialer(self, n: int) -> int:
mp = {0: [4, 6], 1: [6, 8], 2: [7, 9], 3: [4, 8], 4: [0, 3, 9],
5: [], 6: [0, 1, 7], 7: [2, 6], 8: [1, 3], 9: [2, 4]}
ans = [1]*10
for _ in range(n-1):
temp = [0]*10
for i in range(10):
for ii in mp[i]: temp[i] += ans[ii]
temp[i] %= 1_000_000_007
ans = temp
return sum(ans) % 1_000_000_007 | knight-dialer | [Python3] dp O(N) | ye15 | 1 | 202 | knight dialer | 935 | 0.5 | Medium | 15,155 |
https://leetcode.com/problems/knight-dialer/discuss/2476420/Python-or-MEMO-or-Solution | class Solution:
def knightDialer(self, n: int) -> int:
li = [(4, 6), (8, 6), (7, 9), (4, 8), (3, 9, 0),(), (1, 7, 0), (2, 6), (1, 3), (2, 4)]
Mod = 10**9 + 7
def dp(crt,memo,s):
if s==0:
return 1
elif (crt,s) in memo:
return memo[(crt,s)]
else:
k = 0
for j in li[crt]:
k+=dp(j,memo,s-1)
memo[(crt,s)] = k%Mod
return memo[(crt,s)]
ans = 0
memo = {}
for i in range(10):
ans+=dp(i,memo,n-1)
return ans%Mod | knight-dialer | Python | MEMO | Solution | Brillianttyagi | 0 | 112 | knight dialer | 935 | 0.5 | Medium | 15,156 |
https://leetcode.com/problems/knight-dialer/discuss/1885287/PYTHON-SOL-oror-RECURSION-%2B-MEMO-oror-EASY-oror-EXPLAINED-oror | class Solution:
def knightDialer(self, n: int) -> int:
can_go = {0:(4,6),1:(8,6),2:(7,9),3:(4,8),4:(0,3,9),\
5:(),6:(0,1,7),7:(2,6),8:(1,3),9:(2,4)}
dp = {}
def recursion(size,cr):
if size == 0:return 1
if (size,cr) in dp:return dp[(size,cr)]
ans = 0
for x in can_go[cr]:
ans += recursion(size-1,x)
dp[(size,cr)] = ans
return ans
res = 0
for i in range(10):
res += recursion(n-1,i)
return res%1000000007 | knight-dialer | PYTHON SOL || RECURSION + MEMO || EASY || EXPLAINED || | reaper_27 | 0 | 225 | knight dialer | 935 | 0.5 | Medium | 15,157 |
https://leetcode.com/problems/knight-dialer/discuss/1868495/Python3-RECURSION | class Solution:
def knightDialer(self, n: int) -> int:
if n == 1: return 10
MOD = 10**9 + 7
adj = {
1: (6, 8),
2: (9, 7),
3: (4, 8),
4: (0, 3, 9),
5: (),
6: (0, 1, 7),
7: (2, 6),
8: (1, 3),
9: (2, 4),
0: (4, 6)
}
@cache
def recurs(start, n):
if n == 1:
return 1
res = 0
for next in adj[start]:
res += recurs(next, n - 1)
return res % MOD
ans = 0
for num in adj:
ans += recurs(num, n)
return ans % MOD | knight-dialer | [Python3] RECURSION | artod | 0 | 137 | knight dialer | 935 | 0.5 | Medium | 15,158 |
https://leetcode.com/problems/knight-dialer/discuss/1850220/Clean-Python-DP | class Solution:
def knightDialer(self, n: int) -> int:
table = {'-1': '1234567890', '0': '46', '1': '86', '2': '79', '3': '48',
'4': '390', '5': '', '6': '170', '7': '26', '8': '13', '9': '24'}
@cache
def dp(i, cnt):
if cnt == n:
return 1
res = 0
for k in table[i]:
res += dp(k, cnt+1)
return res
return dp('-1', 0) % 1000000007 | knight-dialer | Clean Python DP | r_vaghefi | 0 | 128 | knight dialer | 935 | 0.5 | Medium | 15,159 |
https://leetcode.com/problems/knight-dialer/discuss/1078579/python3-%3A-recursion-%2B-memos-into-tabulation! | class Solution:
def knightDialer1(self, n: int) -> int:
# observe pattern of knight moves and store in lookup table
# 0 -> 4, 6
# 1 -> 6, 8
# 2 -> 7, 9
# 3 -> 4, 8
# 4 -> 3, 9, 0
# 5 -> -
# 6 -> 1, 7, 0
# 7 -> 2, 6
# 8 -> 1, 3
# 9 -> 2, 4
# approach #1: recursive with memo
# helper function takes (curr, left),
# returns number of possible moves based on (curr)ent value and moves (left)
# if left is 1, return 1
# otherwise, recursive call into next value based on lookup dict
lut = { 0 : [4,6],
1 : [6,8],
2 : [7,9],
3 : [4,8],
4 : [0,3,9],
5 : [],
6 : [0,1,7],
7 : [2,6],
8 : [1,3],
9 : [2,4] }
def hlpr(curr: int, left: int) -> int:
if left == 1: return 1
if (curr, left) in memo: return memo[(curr, left)]
res = 0
for next in lut[curr]:
res += hlpr(next, left-1)
memo[(curr, left)] = res
return res
# setup and recursive call
memo = {}
res = 0
for i in [0,1,2,3,4,5,6,7,8,9]:
res += hlpr(i, n)
return res % (10**9 + 7)
def knightDialer2(self, n: int) -> int:
# tabulate the solution above
# two dimensional table
# dp[i][j] is total moves starting from j, with i moves left
# curr, which can be from 0-9 (cols)
# left, which is strictly decreasing (rows)
# O(N) time and space
lut = { 0 : [4,6],
1 : [6,8],
2 : [7,9],
3 : [4,8],
4 : [0,3,9],
5 : [],
6 : [0,1,7],
7 : [2,6],
8 : [1,3],
9 : [2,4] }
dp = [[0 for _ in range(10)] for __ in range(n)]
for i in range(10):
dp[0][i] = 1
for i in range(1,n):
for j in range(10):
tmp = 0
for next in lut[j]:
tmp += dp[i-1][next]
dp[i][j] += tmp
return sum(dp[-1]) % (10**9 + 7)
def knightDialer(self, n: int) -> int:
# last trick, only need a single row of array rather than N rows
# dp[i] represents total moves starting from i
# make a copy of current dp row, and refer to that
# using the actual dp row to store subproblem result
# O(N) time, O(1) space
lut = { 0 : [4,6],
1 : [6,8],
2 : [7,9],
3 : [4,8],
4 : [0,3,9],
5 : [],
6 : [0,1,7],
7 : [2,6],
8 : [1,3],
9 : [2,4] }
dp = [1 for _ in range(10)]
for _ in range(1,n):
last = dp[:]
for j in range(10):
tmp = 0
for next in lut[j]:
tmp += last[next]
dp[j] = tmp
return sum(dp) % (10**9 + 7) | knight-dialer | python3 : recursion + memos into tabulation! | dachwadachwa | 0 | 134 | knight dialer | 935 | 0.5 | Medium | 15,160 |
https://leetcode.com/problems/knight-dialer/discuss/792986/Clean-Recursive-Solution-with-Memoization.-Help-needed!! | class Solution:
NEIGHBORS_MAP = {
1: (6, 8),
2: (7, 9),
3: (4, 8),
4: (3, 9, 0),
5: tuple(),
6: (1, 7, 0),
7: (2, 6),
8: (1, 3),
9: (2, 4),
0: (4, 6),
}
def getNeighbors(self, position):
return self.NEIGHBORS_MAP[position]
def knightDialer(self, N: int, memo={}) -> int:
return sum(self.helper(neigh, N-1, memo) for neigh in self.NEIGHBORS_MAP.keys()) % (10**9 + 7)
def helper(self, current, hops, memo):
if (current, hops) in memo:
return memo[(current, hops)]
if hops == 0:
return 1
res = sum(self.helper(neigh, hops - 1, memo) for neigh in self.getNeighbors(current))
memo[(current, hops)] = res
return res | knight-dialer | Clean Recursive Solution with Memoization. Help needed!! | faizulhai | 0 | 110 | knight dialer | 935 | 0.5 | Medium | 15,161 |
https://leetcode.com/problems/stamping-the-sequence/discuss/1888562/PYTHON-SOL-oror-WELL-EXPLAINED-oror-SIMPLE-ITERATION-oror-EASIEST-YOU-WILL-FIND-EVER-!!-oror | class Solution:
def movesToStamp(self, stamp: str, target: str) -> List[int]:
N,M = len(target),len(stamp)
move = 0
maxmove = 10*N
ans = []
def check(string):
for i in range(M):
if string[i] == stamp[i] or string[i] == '?':
continue
else:
return False
return True
while move < maxmove:
premove = move
for i in range(N-M+1):
if check(target[i:i+M]):
move += 1
ans.append(i)
target = target[:i] + "?"*M + target[i+M:]
if target == "?"*N : return ans[::-1]
if premove == move:return []
return [] | stamping-the-sequence | PYTHON SOL || WELL EXPLAINED || SIMPLE ITERATION || EASIEST YOU WILL FIND EVER !! || | reaper_27 | 7 | 258 | stamping the sequence | 936 | 0.633 | Hard | 15,162 |
https://leetcode.com/problems/stamping-the-sequence/discuss/1136481/Python-Simple-Greedy-Solution | class Solution:
def movesToStamp(self, s: str, t: str) -> List[int]:
options = {i*'*' + s[i:j] + (len(s)-j)*'*' for i in range(len(s)) for j in range(i, len(s)+1)} - {'*'*len(s)}
res = []
target = list(t)
updates = -1
while updates:
i = updates = 0
t = ''.join(target)
while i <= len(t) - len(s):
if t[i:i+len(s)] in options:
res.append(i)
target[i:i+len(s)] = ['*']*len(s)
updates += 1
i += 1
return res[::-1] if set(target) == {'*'} else [] | stamping-the-sequence | [Python] Simple Greedy Solution | rowe1227 | 6 | 204 | stamping the sequence | 936 | 0.633 | Hard | 15,163 |
https://leetcode.com/problems/stamping-the-sequence/discuss/2456466/Stamping-The-Sequence | class Solution:
def movesToStamp(self, s: str, t: str) -> List[int]:
options = {i*'*' + s[i:j] + (len(s)-j)*'*' for i in range(len(s)) for j in range(i, len(s)+1)} - {'*'*len(s)}
res = []
target = list(t)
updates = -1
while updates:
i = updates = 0
t = ''.join(target)
while i <= len(t) - len(s):
if t[i:i+len(s)] in options:
res.append(i)
target[i:i+len(s)] = ['*']*len(s)
updates += 1
i += 1
return res[::-1] if set(target) == {'*'} else [] | stamping-the-sequence | Stamping The Sequence | klu_2100031497 | 1 | 194 | stamping the sequence | 936 | 0.633 | Hard | 15,164 |
https://leetcode.com/problems/stamping-the-sequence/discuss/2814981/Python-with-stamp-covers-and-the-use-of-bounding-variables-beats-90-on-average | class Solution:
def movesToStamp(self, stamp: str, target: str) -> List[int]:
# edge case consideration
if stamp == target :
return [0]
# get stamp and target length
stamp_length, target_length = len(stamp), len(target)
result = []
# keep count and max iter for less overhead calculating and processing valuation queries
count = 0
max_iter = 10*target_length
# set of permutation covers of the stamp
stamp_covers = set()
# inner outer loop of stamp_length and stamp_length - outer length
# falls in O(stamp_length)^2 and O(stamp_length)
# somewhere in that range
for outer_index in range(stamp_length):
for inner_index in range(stamp_length - outer_index):
# add a stamp cover of # * outer_index + stamp[outer_index to stamp_length - inner_index] + # * inner_index
# this builds our stamp set over time to include shifting permutations of stamp as our cover
stamp_covers.add('#' * outer_index + stamp[outer_index : stamp_length - inner_index] + '#' * inner_index)
# print(s_covers)
# finish criteria is back to wild card all
done = '#' * target_length
# post fix positioning is of size target_length - s_length
post_fix = target_length - stamp_length
# ensure post fix is of the appropriate sizing according to problem
if post_fix > max_iter :
post_fix = max_iter
# loop in range up to and including post_fix
for index in range(post_fix + 1):
# if target for index to index + stamp length in stamp covers
if target[index: index + stamp_length] in stamp_covers :
# update target, moving backwards towards our goal, by placing the mask on the target
target = target[ : index] + '#' * stamp_length + target[index + stamp_length : ]
# add the index to the result
result.append(index)
count += 1
# if we are done
if target == done :
# if we are within range of solution
if count <= max_iter + 1 :
return result[ : : -1]
else :
# otherwise, return false
return []
# if we are not done, but are too long already
elif count > max_iter + 1 :
# return false
return []
# loop backwards at this point
for index in range(post_fix, -1, -1) :
# if we have stamp cover, place stamp cover and append index
if target[index : index + stamp_length] in stamp_covers:
target = target[ : index] + '#' * stamp_length + target[index + stamp_length : ]
result.append(index)
count += 1
# if done, check if in bounds and return as appropriate
if target == done :
if count <= max_iter + 1 :
return result[ : : -1]
else :
return []
return [] | stamping-the-sequence | Python with stamp covers and the use of bounding variables beats 90% on average | laichbr | 0 | 1 | stamping the sequence | 936 | 0.633 | Hard | 15,165 |
https://leetcode.com/problems/stamping-the-sequence/discuss/2681350/Python-or-Same-as-everyone-else | class Solution:
def movesToStamp(self, stamp: str, target: str) -> List[int]:
l_s, l_t = len(stamp), len(target)
s = '?'*l_t
res = []
perm = set()
for i in range(l_s):
for j in range(l_s-i):
perm.add('?'*i + stamp[i:l_s-j] + '?'*j)
while target != s:
found = False
for i in range(l_t-l_s, -1, -1):
if target[i:i+l_s] in perm:
target = target[:i]+'?'*l_s+target[i+l_s:]
res.append(i)
found = True
if not found:
return []
return res[::-1] | stamping-the-sequence | Python | Same as everyone else | jainsiddharth99 | 0 | 5 | stamping the sequence | 936 | 0.633 | Hard | 15,166 |
https://leetcode.com/problems/stamping-the-sequence/discuss/2472845/reverse-approach | class Solution:
def movesToStamp(self, stamp: str, target: str) -> List[int]:
indices = []; turn = 0
t = [c for c in target]
L = len(stamp); T = len(target)
while turn <= 10*T and any(c != '?' for c in t):
i = T - L
while i >= 0 :
if all(c == '?' for c in t):
return indices[::-1]
if all((t[i+j] == stamp[j] or t[i+j] == '?') for j in range(L)):
turn += 1
indices.append(i)
t[i : i + L] = '?' * L
i -= 1
if not turn:
break
return indices[::-1] if all(c == '?' for c in t) else [] | stamping-the-sequence | reverse approach | sinha_meenu | 0 | 11 | stamping the sequence | 936 | 0.633 | Hard | 15,167 |
https://leetcode.com/problems/stamping-the-sequence/discuss/2460996/Easy-and-Clear-Solution-Python3 | class Solution:
def movesToStamp(self, stamp: str, target: str) -> List[int]:
res=[]
sl=len(stamp)
tl=len(target)
done=tl*'*'
klem=[]
for i in range(sl):
for j in range(sl - i):
klem.append('*' * i + stamp[i:sl-j] + '*' * j)
old = -1
while target!= done and old<len(res):
old=len(res)
for w in klem:
indice = target.find(w)
while indice !=-1:
res.append(indice)
etoiles = '*'*sl
target=target[:indice]+etoiles+target[indice+sl:]
indice = target.find(w)
if len(res)>10*tl:
return []
if target!= done :
return []
res.reverse()
return res | stamping-the-sequence | Easy and Clear Solution Python3 | moazmar | 0 | 10 | stamping the sequence | 936 | 0.633 | Hard | 15,168 |
https://leetcode.com/problems/stamping-the-sequence/discuss/2460359/Python3-oror-Easy-own-code-oror-92-Faster-oror-Explained | class Solution:
def corresponds(self, stamp, target, idx):
for s in stamp:
if s == target[idx] or target[idx] == '*': idx += 1
else: return False
return True
def movesToStamp(self, stamp: str, target: str) -> List[int]:
n = len(stamp)
m = len(target)
if n == m:
if stamp == target: return [0]
return []
initial = '*'*m
res = []
updated = True
while updated:
updated = False
l, r = 0, n-1
while r < m:
if '*'*n != target[l:r+1] and self.corresponds(stamp, target,l):
res.append(l)
target = target[:l] + "*"*n + target[l+n:]
updated = True
l += 1; r += 1
if target == initial:
return res[::-1]
return [] | stamping-the-sequence | Python3 π|| Easy own code || 92% Faster π₯π§― || Explained | Dewang_Patil | 0 | 20 | stamping the sequence | 936 | 0.633 | Hard | 15,169 |
https://leetcode.com/problems/stamping-the-sequence/discuss/2459906/Python3-oror-98ms-Fast-and-easy-Solution-to-%22Stamping-The-sequence-%3A)' | class Solution:
def movesToStamp(self, stamp: str, target: str) -> List[int]:
slen, tlen = len(stamp), len(target)
res = []
s_covers = set()
for i in range(slen):
for j in range(slen - i):
s_covers.add('#' * i + stamp[i:slen-j] + '#' * j)
# print(s_covers)
done = '#' * tlen
p = tlen - slen
while target != done:
found = False
for i in range(p, -1, -1):
if target[i: i+slen] in s_covers:
target = target[:i] + '#' * slen + target[i+slen:]
res.append(i)
found = True
if not found:
return []
return res[::-1] | stamping-the-sequence | Python3 || 98ms Fast and easy Solution to "Stamping The sequence :)' | WhiteBeardPirate | 0 | 15 | stamping the sequence | 936 | 0.633 | Hard | 15,170 |
https://leetcode.com/problems/stamping-the-sequence/discuss/2457954/Sliding-window-python3-solution | class Solution:
# O(n(n-m) * m) time,
# O(n-m) space,
# Approach: sliding window,
def movesToStamp(self, stamp: str, target: str) -> List[int]:
n = len(target)
m = len(stamp)
target = list(target)
ans = []
vstd_indexes = set()
def isStamped(subarray):
for index,ch in enumerate(subarray):
if not (ch == '?' or ch == stamp[index]):
return False
return True
def replaceToPlaceholder(start):
non_questionmark = 0
for i in range(m):
if target[start+i] != '?':
non_questionmark += 1
target[start+i] = '?'
return non_questionmark
reversed = 0 # number of reversed characters back to '?'
l, r = 0, m
stampExists = False # if stamp exists in one traversal of target
while reversed != n:
while r <= n:
if l not in vstd_indexes and isStamped(target[l:r]):
stampExists = True
ans.append(l)
vstd_indexes.add(l)
break
l +=1
r +=1
if stampExists:
reversed +=replaceToPlaceholder(ans[-1])
stampExists = False
l, r = 0, m
else:
return []
ans.reverse()
return ans | stamping-the-sequence | Sliding window python3 solution | destifo | 0 | 16 | stamping the sequence | 936 | 0.633 | Hard | 15,171 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/1135934/Python3-simple-solution | class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
l = []
d = []
for i in logs:
if i.split()[1].isdigit():
d.append(i)
else:
l.append(i)
l.sort(key = lambda x : x.split()[0])
l.sort(key = lambda x : x.split()[1:])
return l + d | reorder-data-in-log-files | Python3 simple solution | EklavyaJoshi | 12 | 495 | reorder data in log files | 937 | 0.564 | Medium | 15,172 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/382667/Solution-in-Python-3-(beats-~100)-(five-lines) | class Solution:
def reorderLogFiles(self, G: List[str]) -> List[str]:
A, B, G = [], [], [i.split() for i in G]
for g in G:
if g[1].isnumeric(): B.append(g)
else: A.append(g)
return [" ".join(i) for i in sorted(A, key = lambda x: x[1:]+[x[0]]) + B]
- Junaid Mansuri
(LeetCode ID)@hotmail.com | reorder-data-in-log-files | Solution in Python 3 (beats ~100%) (five lines) | junaidmansuri | 8 | 3,700 | reorder data in log files | 937 | 0.564 | Medium | 15,173 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/694018/PythonBests-99-O(1)-Space-and-O(NLogN)-Time-Readable-with-comments | class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
return logs.sort(key= lambda log: self.customSort(log))
def customSort(self, log: str) -> tuple:
#seperate identifer and suffix into two seperate arrays
log_info = log.split(" ", 1)
#check if log is a letter or digital log by checking index in suffix array
# we return 1 as tuple so that digits will always appear after letters and so that when to digits are compared
# we can leave them in their original position
if log_info[1][0].isdigit():
return 1,
#We use a zero to make sure that when compared against a digit we can guranatee that our letter will appear first
#We use the suffix as the next condition and the identifier as the last condition if theres a tie
return 0,log_info[1],log_info[0] | reorder-data-in-log-files | PythonBests 99% O(1) Space and O(NLogN) Time - Readable with comments | Prince_Zamunda | 4 | 1,300 | reorder data in log files | 937 | 0.564 | Medium | 15,174 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/1366672/Easily-understandable-Python-Code!! | class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
if not logs:
return
logs_l = []
logs_d = []
logs_sorted = []
for log in logs:
if log.split()[1].isdigit():
logs_d.append(log)
else:
logs_l.append(log)
m = log.split()[1:]
m = ' '.join(m)
print(m)
logs_sorted.append(m)
logs_sorted, logs_l = zip(*sorted(zip(logs_sorted, logs_l)))
return list(logs_l) + logs_d | reorder-data-in-log-files | Easily understandable Python Code!! | adityarichhariya7879 | 3 | 476 | reorder data in log files | 937 | 0.564 | Medium | 15,175 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/2580452/Python-Solution | class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
digit = []
letter = []
for log in logs:
if log[-1].isdigit():
digit.append(log)
else:
letter.append(log)
letter = [x.split(" ", maxsplit=1) for x in letter]
letter = sorted(letter, key = lambda x: (x[1], x[0]))
letter = [' '.join(map(str, x)) for x in letter]
return letter + digit | reorder-data-in-log-files | Python Solution | MushroomRice | 1 | 74 | reorder data in log files | 937 | 0.564 | Medium | 15,176 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/1958488/Intuitive-Approach | class Solution(object):
def reorderLogFiles(self, logs):
"""
:type logs: List[str]
:rtype: List[str]
"""
all_letter_logs = []
all_digit_logs = []
for log in logs:
temp = log.split()
if all(map(str.isdigit, temp[1:])):
all_digit_logs.append(log)
else:
all_letter_logs.append([temp[0], ' '.join(temp[1:])])
all_letter_logs.sort(key=lambda x : (x[1],x[0]) )
res = []
for item in all_letter_logs:
res.append(' '.join(item))
for item in all_digit_logs:
res.append(item)
return res
``` | reorder-data-in-log-files | Intuitive Approach | rishav-ish | 1 | 121 | reorder data in log files | 937 | 0.564 | Medium | 15,177 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/1912127/Easy-Python-beats-93.96 | class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
digLog = [log for log in logs if log.split()[1].isdigit()]
letLog = [log for log in logs if log not in digLog]
letLog.sort(key=lambda x: (x.split()[1:], x.split()[0]))
return letLog + digLog | reorder-data-in-log-files | Easy Python beats 93.96% | weiting-ho | 1 | 330 | reorder data in log files | 937 | 0.564 | Medium | 15,178 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/1871835/Simple-one-liner-sort | class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
a = []
b = []
for i in logs:
if i.split()[1].isalpha():
a.append(i)
else:
b.append(i)
a.sort(key=lambda x:(x.split()[1:len(x)],x.split()[0]))
return a + b | reorder-data-in-log-files | Simple one liner sort | sushmitha0127 | 1 | 203 | reorder data in log files | 937 | 0.564 | Medium | 15,179 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/1605196/Python3-simple-solution | class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
letter_list = []
digit_list = []
for i in range(len(logs)):
tokens = logs[i].split()
if tokens[1].isalpha():
letter_list.append(logs[i])
else:
digit_list.append(logs[i])
letter_list = sorted(letter_list, key = lambda x:x.split()[0])
letter_list = sorted(letter_list, key = lambda x:x.split()[1:])
return letter_list + digit_list | reorder-data-in-log-files | Python3 simple solution | evancao1429 | 1 | 215 | reorder data in log files | 937 | 0.564 | Medium | 15,180 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/1557101/Super-easy-to-understand-python-3-beats-93 | class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
# filter out all the logs where the second part of the log is a letter
# (because first part is an identifier than can be anything)
ll = list(filter(lambda x: x.split()[1].isalpha(), logs))
# filter out all the logs where the second part of the log is a digit.
#This is since we need to keep its relative ordering and dont have to change anything
ld = list(filter(lambda x: x.split()[1].isnumeric(), logs))
# Now we sort. We generate a tuple key where the first element is the content of log.
# and the second element is the identifier. This ensures that python first sorts the content
# and then uses the ID as a tie breaker.
ll.sort(key=lambda x: (' '.join(x.split()[1:]), x.split()[0]))
# Concatinate the 2 lists and your done. Super simple
return ll + ld | reorder-data-in-log-files | Super easy to understand python 3 beats 93% | Daniele122898 | 1 | 238 | reorder data in log files | 937 | 0.564 | Medium | 15,181 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/1444650/Python3Python-Solution-using-isdigit-method-and-sorting-w-comments | class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
# Init list to contain letter and digit logs
letter_logs = []
digit_logs = []
# For each log separate and put them into separate logs
for log in logs:
l = log.split(" ")
if l[1].isdigit():
digit_logs.append(l)
else:
letter_logs.append(l)
# Sort letter logs as required
letter_logs = sorted(letter_logs, key=lambda x: (x[1:],x[0]))
# re-combine and return
return [" ".join(l) for l in letter_logs] + [" ".join(l) for l in digit_logs] | reorder-data-in-log-files | [Python3/Python] Solution using isdigit method and sorting w/ comments | ssshukla26 | 1 | 304 | reorder data in log files | 937 | 0.564 | Medium | 15,182 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/469546/Python%3A-Easy-to-understand-solution | class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
letterLogs = []
letterDict = {}
digitLogs = []
for log in logs:
split_list = log.split(" ")
# If the second word is alphabetic, add it to a dictionary,
# replacing whitespaces with "," and appending the key to the end:
# Example: let1 hi hello how => hi,hello,how,let1
if split_list[1].isalpha():
key = log[log.index(" "):].replace(" ", ",")+ "," + split_list[0]
letterDict[key] = split_list[0]
# If second word is numeric, append it to the digit list
elif split_list[1].isdigit():
digitLogs.append(log)
# Sort the dictionary keys and append to a list after reformatting
for key in sorted(letterDict.keys()):
letter_log = letterDict[key] + key.replace(",", " ")
letterLogs.append(letter_log[:letter_log.rfind(" ")])
return letterLogs + digitLogs | reorder-data-in-log-files | Python: Easy to understand solution | rafaelvalle | 1 | 508 | reorder data in log files | 937 | 0.564 | Medium | 15,183 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/2847725/Separating-logs-sorting-then-combining | class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
# create two seperate data structures for letter logs and digits logs
# iterate through logs and see if it's a letter log or a digit log.
# if it's a digit log append it to the dlogs array to maintain it's order
# otherwise, it's a letter log. If it's not in the llogs mappings then add it
# with it's value as the logs it stores.
# if the key is already present, add a space to the name to workaround duplicate log identifiers
# sort the letter logs by their log identifiers lexicographically to have them ordered, then sort
# them by the logs they store. This will keep them sorted by their contents first, then their
# log identifiers.
# to handle adding a space split the log identifier to make sure it's always just the identifier name
# join the identifiers with their logs in the map
# concat the sorted letter logs with the digit logs
# time O(nlogn) space O(n)
llogs = dict()
dlogs = []
for log in logs:
names = log.split()
if names[1].isdigit():
dlogs.append(log)
else:
if names[0] in llogs:
llogs[names[0] + " "] = names[1:]
else:
llogs[names[0]] = names[1:]
res = sorted(llogs)
res.sort(key=llogs.get)
for i in range(len(res)):
name = res[i]
logs = llogs[res[i]]
res[i] = f"{name.split()[0]} {' '.join(logs)}"
return res + dlogs | reorder-data-in-log-files | Separating logs, sorting, then combining | andrewnerdimo | 0 | 1 | reorder data in log files | 937 | 0.564 | Medium | 15,184 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/2678189/easy-python-ssolution | class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
dig = []
let = []
for log in logs:
if log.rsplit(" ",1)[-1].isnumeric():
dig.append(log)
else:
let.append(log.split(" ",1))
let.sort(key= lambda x: (x[1],x[0]))
ans = [x[0]+" "+x[1] for x in let]
ans.extend(dig)
return ans | reorder-data-in-log-files | easy python ssolution | abhi2411 | 0 | 8 | reorder data in log files | 937 | 0.564 | Medium | 15,185 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/2646704/Python-Easy-Custom-sort | class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
digit = []
letter = []
for i in logs:
if i[-1].isdigit():
digit.append(i)
else:
letter.append(i)
letter = [x.split(' ',maxsplit=1) for x in letter]
letter = sorted(letter,key = lambda x:(x[1],x[0]))
letter = [' '.join(x) for x in letter]
return letter+digit | reorder-data-in-log-files | Python Easy Custom sort | Brillianttyagi | 0 | 45 | reorder data in log files | 937 | 0.564 | Medium | 15,186 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/2542973/Python-runtime-O(mn-logn)-memory-O(mn) | class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
letterLog = []
digitLog = []
for i, log in enumerate(logs):
s = log.split(" ")
if s[1].isdigit():
digitLog.append(log)
else:
letterLog.append((s[1:], s[0], log))
letterLog = sorted(letterLog, key= lambda x: x[1])
letterLog = sorted(letterLog, key= lambda x: x[0])
ans = []
for l, key, log in letterLog:
ans.append(log)
return ans + digitLog | reorder-data-in-log-files | Python, runtime O(mn logn), memory O(mn) | tsai00150 | 0 | 79 | reorder data in log files | 937 | 0.564 | Medium | 15,187 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/2066933/Python3-Custom-Comparator-Concise | class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
digit_logs = []
letter_logs_indices = []
letter_log_map = {}
for i, log in enumerate(logs):
if log[-1] >= 'a'and log[-1] <= 'z':
words = log.split()
identifier = words[0]
content = ' '.join(words[1:])
letter_logs_indices.append(i)
letter_log_map[i] = (identifier, content)
else:
digit_logs.append(log)
def cmp(index_a, index_b):
content_a = letter_log_map[index_a][1]
content_b = letter_log_map[index_b][1]
if content_a < content_b:
return -1
elif content_a > content_b:
return 1
else:
identifier_a = letter_log_map[index_a][0]
identifier_b = letter_log_map[index_b][0]
if identifier_a < identifier_b:
return -1
elif identifier_a > identifier_b:
return 1
else:
return 0
result = []
letter_logs_indices.sort(key=functools.cmp_to_key(cmp))
for log_index in letter_logs_indices:
result.append(logs[log_index])
result += digit_logs
return result | reorder-data-in-log-files | Python3 Custom Comparator Concise | shtanriverdi | 0 | 121 | reorder data in log files | 937 | 0.564 | Medium | 15,188 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/2036399/SIMPLE-PYTHON-SOLUTION-USING-SORTED | class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
nl = sorted(logs,key = lambda x:self.srt(x))
return nl
def srt(self, item):
ig = item.split()
i = list(ig)
idd = i[0]
if i[1][0] in ['0','1','2','3','4','5','6','7','8','9']:
return 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'
sr = ""
for s in i[1:]:
sr+=s
sr+= " " # seperate each part of the log in the sort key string
sr+= "aaaaa" # add prevent id from being confused as part of log
sr+= idd
return sr
``` | reorder-data-in-log-files | SIMPLE PYTHON SOLUTION USING SORTED | byyoung3 | 0 | 172 | reorder data in log files | 937 | 0.564 | Medium | 15,189 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/1968290/Python-3-Solution | class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
digit_log = []
letter_log = []
d = {}
for log in logs:
for i in range(len(log)):
if log[i] == ' ':
if log[i+1] in '0123456789':
digit_log.append(log)
else:
if log[i+1:] in d:
d[log[i+1:]].append(log[:i])
else:
d[log[i+1:]] = [log[:i]]
break
dval = sorted(d.keys())
for i in dval:
for j in sorted(d[i]):
x = j + ' ' + i
letter_log.append(x)
return (letter_log + digit_log) | reorder-data-in-log-files | Python 3 Solution | DietCoke777 | 0 | 173 | reorder data in log files | 937 | 0.564 | Medium | 15,190 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/1934320/Python3 | class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
letter_logs = []
digit_logs = []
for log in logs:
elems = log.split(' ')
if elems[1].isalpha():
heapq.heappush(letter_logs, (elems[1:], elems[0], log))
else:
digit_logs.append(log)
return [heapq.heappop(letter_logs)[2] for _ in range(len(letter_logs))] + digit_logs | reorder-data-in-log-files | Python3 | AlphaMonkey9 | 0 | 166 | reorder data in log files | 937 | 0.564 | Medium | 15,191 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/1453221/My-approach-using-Python3 | class Solution:
def sortHelperKey(self, log):
return log.split()[0]
def sortHelperContent(self, log):
return log.split()[1:]
def reorderLogFiles(self, logs: List[str]) -> List[str]:
letter_logs = []
digit_logs = []
for log in logs:
current_log = log.split()
if current_log[1].isalpha():
letter_logs.append(log)
else:
digit_logs.append(log)
letter_logs.sort(key = self.sortHelperKey)
letter_logs.sort(key = self.sortHelperContent)
return letter_logs + digit_logs | reorder-data-in-log-files | My approach using Python3 | pcv | 0 | 337 | reorder data in log files | 937 | 0.564 | Medium | 15,192 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/1420277/Python3-Faster-Than-96.86-Memory-Less-Than-96.72 | class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
digit, words = [], []
for i in logs:
if i.split()[1].isnumeric():
digit += [i]
else:
words += [i]
return sorted(words, key = lambda x : (x.split()[1:], x.split()[0])) + digit | reorder-data-in-log-files | Python3 Faster Than 96.86%, Memory Less Than 96.72% | Hejita | 0 | 142 | reorder data in log files | 937 | 0.564 | Medium | 15,193 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/1316336/Python3-Solution-using-sorting-and-split | class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
letters=[]
digits=[]
for x in logs:
xx=x.split()
ident=xx[1]
t=" ".join(xx[1:])
if ident.isdigit():
digits.append(x)
else:
letters.append([t,xx[0]])
letters.sort()
res=[]
for x,y in letters:
temp=y+" " + "".join(x)
res.append(temp)
for x in digits:
res.append(x)
return res | reorder-data-in-log-files | Python3 Solution using sorting and split | atm1504 | 0 | 113 | reorder data in log files | 937 | 0.564 | Medium | 15,194 |
https://leetcode.com/problems/reorder-data-in-log-files/discuss/315213/Python-solution-using-dictionary | class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
res=[]
digi=[]
letter=[]
for i in logs:
k=i.split()
if k[1].isdigit():
digi.append(i)
else:
letter.append(i)
d={}
for i in letter:
k=i.split()
m=d.get(tuple(k[1:]),[])
m.append(k[0])
d[tuple(k[1:])]=m
for i in sorted(list(d.keys())):
x=[x for x in i]
s=''
for j in x:
s+=j+' '
s=s.strip()
for j in sorted(d[i]):
res.append(j+' '+s)
return(res+digi) | reorder-data-in-log-files | Python solution using dictionary | ketan35 | 0 | 570 | reorder data in log files | 937 | 0.564 | Medium | 15,195 |
https://leetcode.com/problems/range-sum-of-bst/discuss/1627963/Python3-ITERATIVE-BFS-Explained | class Solution:
def rangeSumBST(self, root: Optional[TreeNode], lo: int, hi: int) -> int:
res = 0
q = deque([root])
while q:
c = q.popleft()
v, l, r = c.val, c.left, c.right
if lo <= v and v <= hi:
res += v
if l and (lo < v or v > hi):
q.append(l)
if r and (lo > v or v < hi):
q.append(r)
return res | range-sum-of-bst | βοΈ [Python3] ITERATIVE BFS, Explained | artod | 3 | 237 | range sum of bst | 938 | 0.854 | Easy | 15,196 |
https://leetcode.com/problems/range-sum-of-bst/discuss/1627797/Python3-Clean-or-7-Lines-or-O(n)-Time-(beats-94.28-)-or-O(n)-Space-or-DFS | class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
if not root: return 0
res = root.val if low <= root.val <= high else 0
if root.val <= low: return res + self.rangeSumBST(root.right, low, high)
if root.val >= high: return res + self.rangeSumBST(root.left, low, high)
return res + self.rangeSumBST(root.right, low, high) + self.rangeSumBST(root.left, low, high) | range-sum-of-bst | [Python3] Clean | 7 Lines | O(n) Time (beats 94.28 %) | O(n) Space | DFS | PatrickOweijane | 3 | 353 | range sum of bst | 938 | 0.854 | Easy | 15,197 |
https://leetcode.com/problems/range-sum-of-bst/discuss/1438473/Recursive-88-speed | class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
ans = 0
def traverse(node: Optional[TreeNode]):
nonlocal ans
if node:
if low <= node.val <= high:
ans += node.val
if node.left and node.val > low:
traverse(node.left)
if node.right and node.val < high:
traverse(node.right)
traverse(root)
return ans | range-sum-of-bst | Recursive, 88% speed | EvgenySH | 2 | 303 | range sum of bst | 938 | 0.854 | Easy | 15,198 |
https://leetcode.com/problems/range-sum-of-bst/discuss/1198589/Python-3-or-DFS-or-Easy-Understand | class Solution:
def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
result = []
self.dfs(root, low, high, result)
return sum(result)
def dfs(self, root, low, high, result):
if root:
if root.val < low:
self.dfs(root.right, low, high, result)
if root.val > high:
self.dfs(root.left, low, high, result)
if low <= root.val <= high:
result.append(root.val)
self.dfs(root.left, low, high, result)
self.dfs(root.right, low, high, result) | range-sum-of-bst | Python 3 | DFS | Easy Understand | itachieve | 2 | 120 | range sum of bst | 938 | 0.854 | Easy | 15,199 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.