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/shift-2d-grid/discuss/1937219/Python-two-easy-approaches-or-O(N)-times | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
arr = []
m = len(grid)
n = len(grid[0])
for i in range(m):
for j in range(n):
arr.append(grid[i][j])
grid.clear()
for _ in range(k):
last_element = arr.pop()
arr.insert(0, last_element)
for i in range(0, m*n, n):
grid.append(arr[i:i+n])
return grid | shift-2d-grid | [Python] two easy approaches | O(N) times | jamil117 | 0 | 37 | shift 2d grid | 1,260 | 0.68 | Easy | 18,800 |
https://leetcode.com/problems/shift-2d-grid/discuss/1937219/Python-two-easy-approaches-or-O(N)-times | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
arr = []
m = len(grid)
n = len(grid[0])
for i in range(m):
for j in range(n):
arr.append(grid[i][j])
grid.clear()
for _ in range(k):
last_element = arr.pop()
arr.insert(0, last_element)
temp = []
for _ in range(m):
temp.clear()
for _ in range(n):
temp.append(arr.pop(0))
val = temp.copy()
grid.append(val)
return grid | shift-2d-grid | [Python] two easy approaches | O(N) times | jamil117 | 0 | 37 | shift 2d grid | 1,260 | 0.68 | Easy | 18,801 |
https://leetcode.com/problems/shift-2d-grid/discuss/1937197/Fast-solution-transposing-the-matrix-and-reducing-k | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
rows = len(grid)
cols = len(grid[0])
k = k % (rows*cols)
# Horizontal shifts
for i in range(rows):
grid[i] = grid[i][-k%cols:] + grid[i][:-k%cols]
# Transpose the matrix
grid = list(zip(*grid))
# Vertical shifts
for i in range(k):
grid[i%cols] = grid[i%cols][-1:] + grid[i%cols][:-1]
# Transpose it back
return list(zip(*grid)) | shift-2d-grid | Fast solution transposing the matrix and reducing k | eduardocereto | 0 | 8 | shift 2d grid | 1,260 | 0.68 | Easy | 18,802 |
https://leetcode.com/problems/shift-2d-grid/discuss/1937158/O(m*n)-time-without-looping-k-times | class Solution:
#O(m*n) with O(m*n) extra space
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m=len(grid)
n = len(grid[0])
oneD = [0]*(m*n)
#Convert grid to canonicalform in one D
#O(m*n)
for i in range(m):
for j in range(n):
l = (i*n) +j
oneD[l]=grid[i][j]
# print(oneD)
#O(m*n)
#shift the array by k times its basically takin k elements from oneD array and prefix it with oneDarray
#if k is greater than m*n size ideally if we shift the array for m*n times it will be same as original
#hence instead of shifting k number of tiems just find the remainder which will be in range of m*n and shift only that
if k>m*n:
k = k%(m*n)
oneD = oneD[-k:] + oneD[:-k]
# print(oneD)
#O(m*n)
#Convert 1D to 2D array
for i in range(len(oneD)):
i2 = i//n
j2= i%n
grid[i2][j2] = oneD[i]
return grid | shift-2d-grid | O(m*n) time without looping k times | spraks | 0 | 16 | shift 2d grid | 1,260 | 0.68 | Easy | 18,803 |
https://leetcode.com/problems/shift-2d-grid/discuss/1936926/Python3-Time-O(n)-Space-O(1) | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
max_row = len(grid)
max_col = len(grid[0])
k = k % (max_row*max_col)
reverse(grid, 0, max_row*max_col-1)
reverse(grid, 0, k-1)
reverse(grid, k, max_row*max_col-1)
return grid
def reverse(grid, start, end):
max_row = len(grid)
max_col = len(grid[0])
while start<end:
start_row, start_col = get_row_col(start, max_row, max_col)
end_row, end_col = get_row_col(end, max_row, max_col)
temp = grid[start_row][start_col]
grid[start_row][start_col] = grid[end_row][end_col]
grid[end_row][end_col] = temp
start += 1
end -=1
def get_row_col(index, max_row, max_col):
row = index // max_col
col = index % max_col
return row, col | shift-2d-grid | Python3 Time O(n), Space O(1) | a1994831005 | 0 | 24 | shift 2d grid | 1,260 | 0.68 | Easy | 18,804 |
https://leetcode.com/problems/shift-2d-grid/discuss/1936831/Python-Easy-To-Understand-Solution-with-Comments | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
unPack = [n for sublist in grid for n in sublist] # flattens the grid
lenGrid = len(grid[0]) # gets the dimensions of the grid
res = []
# moves the last item of the list to the beginning 'k' times
for i in range(k):
unPack.insert(0, unPack[-1])
unPack.pop()
idx = 0
idx2 = lenGrid
# re-packs the flattened grid
for i in range(len(grid)):
res.append(unPack[idx:idx2])
idx += lenGrid
idx2 += lenGrid
return res | shift-2d-grid | [Python] Easy To Understand Solution with Comments | kandrews650 | 0 | 34 | shift 2d grid | 1,260 | 0.68 | Easy | 18,805 |
https://leetcode.com/problems/shift-2d-grid/discuss/1936669/Python-very-simple-solution | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
length = len(grid[0])
heigth = len(grid)
counter = 0
if k%(heigth*length) == 0: # if k modulus i*j == 0 we do not need to shift at all, end result would be the same.
return grid
while counter < k: # repeat it k times
temp = []
for items in grid: # first make it 1dimension list
for item in items:
temp.append(item)
temp.insert(0, temp.pop()) # here, we shift it
counter += 1
grid = [temp[i:i + length] for i in range(0, len(temp), length)]
return grid
``` | shift-2d-grid | Python very simple solution | caneryikar | 0 | 31 | shift 2d grid | 1,260 | 0.68 | Easy | 18,806 |
https://leetcode.com/problems/shift-2d-grid/discuss/1936409/Python-easy-to-understand-solution | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m = len(grid)
n = len(grid[0])
def twoDimToOneDim(i,j):
return i*n+j
def oneDimToTwoDim(pos):
return [pos//n,pos%n]
res = [[0]*n for _ in range(m)]
for i in range(m):
for j in range(n):
newPos = (twoDimToOneDim(i,j) + k) % (m*n)
newR, newC = oneDimToTwoDim(newPos)
res[newR][newC] = grid[i][j]
return res | shift-2d-grid | Python easy to understand solution | aashnachib17 | 0 | 17 | shift 2d grid | 1,260 | 0.68 | Easy | 18,807 |
https://leetcode.com/problems/shift-2d-grid/discuss/1936327/Python3-Solution-with-using-shifting | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
n, m = len(grid), len(grid[0])
for _ in range(k):
prev = grid[-1][-1]
for i in range(n):
for j in range(m):
prev, grid[i][j] = grid[i][j], prev
return grid | shift-2d-grid | [Python3] Solution with using shifting | maosipov11 | 0 | 14 | shift 2d grid | 1,260 | 0.68 | Easy | 18,808 |
https://leetcode.com/problems/shift-2d-grid/discuss/1935987/Python-or-Faster-than-92.20-or-O(kn)-time-or-O(1)-space | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
for _ in range(k):
for i in range(len(grid)):
if i > 0:
grid[i].insert(0, temp)
temp = grid[i].pop()
grid[0].insert(0, temp)
return grid | shift-2d-grid | Python | Faster than 92.20% | O(kn) time | O(1) space | khaydaraliev99 | 0 | 38 | shift 2d grid | 1,260 | 0.68 | Easy | 18,809 |
https://leetcode.com/problems/shift-2d-grid/discuss/1935318/Python3-List-Comprehension | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
while k:
[i.insert(0, grid[grid.index(i)-1].pop()) for i in grid]
k -= 1
return grid | shift-2d-grid | Python3 List Comprehension | user6239mb | 0 | 20 | shift 2d grid | 1,260 | 0.68 | Easy | 18,810 |
https://leetcode.com/problems/shift-2d-grid/discuss/1935318/Python3-List-Comprehension | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
[[i.insert(0, grid[grid.index(i)-1].pop()) for i in grid] for k in range(k)]
return grid | shift-2d-grid | Python3 List Comprehension | user6239mb | 0 | 20 | shift 2d grid | 1,260 | 0.68 | Easy | 18,811 |
https://leetcode.com/problems/shift-2d-grid/discuss/1935136/Direct-Simulation-with-3-version-improvements-or-Python3 | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m = len(grid)
n = len(grid[0])
k = k % (m * n)
for _ in range(k):
temp = [[0] * n for _ in range(m)]
temp[0][0] = grid[m - 1][n - 1]
# i,m:row
for i in range(m):
# j,n:col
for j in range(n):
if j < n - 1:
temp[i][(j + 1) % n] = grid[i][j]
else:
temp[(i + 1) % m][0] = grid[i][n - 1]
grid = temp
return grid | shift-2d-grid | Direct Simulation with 3 version improvements | Python3 | qihangtian | 0 | 17 | shift 2d grid | 1,260 | 0.68 | Easy | 18,812 |
https://leetcode.com/problems/shift-2d-grid/discuss/1935136/Direct-Simulation-with-3-version-improvements-or-Python3 | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m = len(grid)
n = len(grid[0])
k = k % (m * n)
for _ in range(k):
temp = [[0] * n for _ in range(m)]
temp[0][0] = grid[m - 1][n - 1]
# i,m:row
for i in range(m):
# j,n:col
for j in range(n - 1):
temp[i][(j + 1) % n] = grid[i][j]
# 剪枝,相比v1减少if判断,小幅优化
temp[(i + 1) % m][0] = grid[i][n - 1]
grid = temp
return grid | shift-2d-grid | Direct Simulation with 3 version improvements | Python3 | qihangtian | 0 | 17 | shift 2d grid | 1,260 | 0.68 | Easy | 18,813 |
https://leetcode.com/problems/shift-2d-grid/discuss/1935136/Direct-Simulation-with-3-version-improvements-or-Python3 | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m = len(grid)
n = len(grid[0])
k = k % (m * n)
for _ in range(k):
temp = [[0] * n for _ in range(m)]
# i,m:row
for i in range(m):
# n:col
# 这里继续剪枝,把一次次的遍历赋值改为了一整段的拼接
# 问题的关键是理解shift操作的本质,是把每一行向下“循环推动”一格
# 所以不需要拘泥于定义的3个操作,可以合并为这一个赋值
temp[i] = [grid[i - 1][n - 1], *grid[i][0:n - 1]]
grid = temp
return grid | shift-2d-grid | Direct Simulation with 3 version improvements | Python3 | qihangtian | 0 | 17 | shift 2d grid | 1,260 | 0.68 | Easy | 18,814 |
https://leetcode.com/problems/shift-2d-grid/discuss/1935136/Direct-Simulation-with-3-version-improvements-or-Python3 | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m = len(grid)
n = len(grid[0])
k = k % (m * n)
# 提取到循环外降低一点点的开销
temp = [[0] * n for _ in range(m)]
for _ in range(k):
# i,m:row
for i in range(m):
# n:col
# 这里继续剪枝,把一次次的遍历赋值改为了一整段的拼接
# 问题的关键是理解shift操作的本质,是把每一行向下“循环推动”一格
# 所以不需要拘泥于定义的3个操作,可以合并为这一个赋值
temp[i] = [grid[i - 1][n - 1], *grid[i][0:n - 1]]
# 这里就需要深拷贝了,又增加了一点点开销
# 也可以用 grid = temp.copy(),性能差不多
grid = [*temp]
return grid | shift-2d-grid | Direct Simulation with 3 version improvements | Python3 | qihangtian | 0 | 17 | shift 2d grid | 1,260 | 0.68 | Easy | 18,815 |
https://leetcode.com/problems/shift-2d-grid/discuss/1935101/Python3-Simple-O(m*n)-space-and-time-solution-or-168ms-beats-92 | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
M, N = len(grid), len(grid[0])
k = k % (M*N)
res = [[0 for _ in range(N)] for _ in range(M)]
r, c = k//N, k%N
for i in range(M):
for j in range(N):
res[r][c] = grid[i][j]
if r == M-1 and c == N-1:
r, c = 0, 0
elif c == N-1:
r+=1
c = 0
else:
c+=1
return res
``` | shift-2d-grid | [Python3] Simple O(m*n) space and time solution | 168ms beats 92% | nandhakiran366 | 0 | 22 | shift 2d grid | 1,260 | 0.68 | Easy | 18,816 |
https://leetcode.com/problems/shift-2d-grid/discuss/1934916/Python3-oror-Solution-using-a-single-loop-and-Modulo-arithmetic | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
rows = len(grid)
columns = len(grid[0])
length = rows * columns
new_grid = [[0] * columns for _ in range(rows)]
for i in range(length):
curr_row = i // columns
curr_col = i % columns
new_row = ((i + k) % length) // columns
new_col = ((i + k) % length) % columns
new_grid[new_row][new_col] = grid[curr_row][curr_col]
return new_grid | shift-2d-grid | Python3 || Solution using a single loop and Modulo arithmetic | constantine786 | 0 | 41 | shift 2d grid | 1,260 | 0.68 | Easy | 18,817 |
https://leetcode.com/problems/shift-2d-grid/discuss/1934581/python3-easy | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
rows = len(grid)
cols = len(grid[0])
k = k % (rows * cols)
all = []
for i in grid:
all += i
laste = all[len(all)-k:]
all[k:] = all[:len(all)-k]
all[:k] = laste[::]
for i in range(rows):
grid[i] = all[i*cols:i*cols+cols]
return grid | shift-2d-grid | python3 easy | user2613C | 0 | 42 | shift 2d grid | 1,260 | 0.68 | Easy | 18,818 |
https://leetcode.com/problems/shift-2d-grid/discuss/1856302/Python-(Simple-Approach-and-Beginner-Friendly) | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
leng = len(grid[0])
numbers = []
output = []
arr = []
for i in grid:
for j in i:
numbers.append(j)
for i in range(k):
numbers.insert(0, numbers.pop())
print(numbers)
for j in range(0,len(numbers)):
arr.append(numbers[j])
if (j+1)%leng == 0:
output.append(arr)
arr = []
return output | shift-2d-grid | Python (Simple Approach and Beginner-Friendly) | vishvavariya | 0 | 72 | shift 2d grid | 1,260 | 0.68 | Easy | 18,819 |
https://leetcode.com/problems/shift-2d-grid/discuss/1824997/3-Lines-Python-Solution-oror-65-Faster-oror-Memory-less-than-65 | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
n=len(grid[0]) ; m=len(grid) ; ans=[] ; k=k%(n*m) ; G=list(chain(*grid)) ; G=G[-k:]+G[:-k]
for i in range(0,n*m,n): ans.append(G[i:i+n])
return ans | shift-2d-grid | 3-Lines Python Solution || 65% Faster || Memory less than 65% | Taha-C | 0 | 58 | shift 2d grid | 1,260 | 0.68 | Easy | 18,820 |
https://leetcode.com/problems/shift-2d-grid/discuss/1724839/Python-dollarolution(fast%3A-55-oror-mem%3A-99-) | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
grid = list(zip(*grid))
for _ in range(k):
grid = [grid[-1]] + grid
grid.pop()
grid[0] = (grid[0][-1],) + grid[0]
grid[0] = grid[0][:-1]
grid = list(zip(*grid))
return grid | shift-2d-grid | Python $olution(fast: 55% || mem: 99% ) | AakRay | 0 | 93 | shift 2d grid | 1,260 | 0.68 | Easy | 18,821 |
https://leetcode.com/problems/shift-2d-grid/discuss/1082374/Python3-simple-solution | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
n = len(grid[0])
m = len(grid)
l = []
for i in range(m):
for j in range(n):
l.append(grid[i][j])
k = k%(n*m)
l = l[len(l)-k:] + l[:len(l)-k]
for i in range(m):
for j in range(n):
grid[i][j] = l.pop(0)
return grid | shift-2d-grid | Python3 simple solution | EklavyaJoshi | 0 | 119 | shift 2d grid | 1,260 | 0.68 | Easy | 18,822 |
https://leetcode.com/problems/shift-2d-grid/discuss/457219/Python3-super-simple-solution-using-a-1-D-array | class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
temp, m, n = [], len(grid), len(grid[0])
for item in grid:
temp.extend(item)
for i in range(k):
temp = [temp.pop()] + temp
res = []
for i in range(0,m*n,n):
res.append(temp[i:i+n])
return res | shift-2d-grid | Python3 super simple solution using a 1-D array | jb07 | 0 | 76 | shift 2d grid | 1,260 | 0.68 | Easy | 18,823 |
https://leetcode.com/problems/greatest-sum-divisible-by-three/discuss/497058/Python-3-(four-lines)-(Math-Solution)-(no-DP)-(beats-~92) | class Solution:
def maxSumDivThree(self, N: List[int]) -> int:
A, B, S = heapq.nsmallest(2,[n for n in N if n % 3 == 1]), heapq.nsmallest(2,[n for n in N if n % 3 == 2]), sum(N)
if S % 3 == 0: return S
if S % 3 == 1: return S - min(A[0], sum(B) if len(B) > 1 else math.inf)
if S % 3 == 2: return S - min(B[0], sum(A) if len(A) > 1 else math.inf)
- Junaid Mansuri
- Chicago, IL | greatest-sum-divisible-by-three | Python 3 (four lines) (Math Solution) (no DP) (beats ~92%) | junaidmansuri | 5 | 731 | greatest sum divisible by three | 1,262 | 0.509 | Medium | 18,824 |
https://leetcode.com/problems/greatest-sum-divisible-by-three/discuss/2419612/PYTHON-or-RECURSION-%2B-MEMO-or-EXPLAINED-or-MOD-or-CLEAR-and-CONCISE-or | class Solution:
def maxSumDivThree(self, nums: List[int]) -> int:
dp,n = {} , len(nums)
def recursion(index,mod):
if index == n:
return 0 if mod == 0 else -inf
if (index,mod) in dp: return dp[(index,mod)]
a = recursion(index + 1, (mod + nums[index]) % 3) + nums[index]
b = recursion(index + 1 , mod)
ans = max(a,b)
dp[(index,mod)] = ans
return ans
return recursion(0,0) | greatest-sum-divisible-by-three | PYTHON | RECURSION + MEMO | EXPLAINED | MOD | CLEAR & CONCISE | | reaper_27 | 1 | 104 | greatest sum divisible by three | 1,262 | 0.509 | Medium | 18,825 |
https://leetcode.com/problems/greatest-sum-divisible-by-three/discuss/2258670/Python-100-Optimized | class Solution(object):
def maxSumDivThree(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
prev= [0]*3
early = None
for i in nums:
early = prev[::]
for j in range(3):
val = prev[j]+i
if early[val%3]<val:
early[val%3] = val
prev = early[::]
return(early[0]) | greatest-sum-divisible-by-three | Python 100% Optimized | Abhi_009 | 1 | 133 | greatest sum divisible by three | 1,262 | 0.509 | Medium | 18,826 |
https://leetcode.com/problems/greatest-sum-divisible-by-three/discuss/1266267/Python3-solution-using-dynamic-programming | class Solution:
def maxSumDivThree(self, nums: List[int]) -> int:
dp = []
for i in range(3):
z = []
for j in range(len(nums)):
z.append(0)
dp.append(z)
dp[nums[0]%3][0] = nums[0]
for i in range(1,len(nums)):
for j in range(3):
x = dp[j][i-1] + nums[i]
dp[x%3][i] = max([dp[x%3][i], x, dp[x%3][i-1]])
dp[j][i] = max(dp[j][i-1],dp[j][i])
return dp[0][-1] | greatest-sum-divisible-by-three | Python3 solution using dynamic programming | EklavyaJoshi | 1 | 172 | greatest sum divisible by three | 1,262 | 0.509 | Medium | 18,827 |
https://leetcode.com/problems/minimum-moves-to-move-a-box-to-their-target-location/discuss/2643673/Python3-Double-BFS-or-O(m2-*-n2) | class Solution:
def minPushBox(self, grid: List[List[str]]) -> int:
neighbors = [(0, -1), (0, 1), (-1, 0), (1, 0)]
def player_bfs(st_row, st_col, tgt_row, tgt_col):
nonlocal rows, cols
if (st_row, st_col) == (tgt_row, tgt_col):
return True
q = deque([(st_row, st_col)])
seen = [[False] * cols for _ in range(rows)]
seen[st_row][st_col] = True
while q:
row, col = q.pop()
for r, c in neighbors:
if 0 <= row+r < rows and 0 <= col+c < cols and not seen[row+r][col+c] and grid[row+r][col+c] == '.':
if row+r == tgt_row and col+c == tgt_col:
return True
seen[row+r][col+c] = True
q.appendleft((row+r, col+c))
return False
def box_bfs(st_row, st_col):
nonlocal rows, cols, target
q = deque([(st_row, st_col, start[0], start[1], 0)])
seen = {st_row, st_col, start[0], start[1]}
while q:
row, col, prow, pcol, moves = q.pop()
grid[row][col] = 'B'
for r, c in neighbors:
box_can_move = 0 <= row+r < rows and 0 <= col+c < cols and (row+r, col+c, row-r, col-c) not in seen and grid[row+r][col+c] == '.'
if box_can_move and player_bfs(prow, pcol, row-r, col-c):
if (row+r, col+c) == target:
return moves + 1
seen.add((row+r, col+c, row-r, col-c))
q.appendleft((row+r, col+c, row-r, col-c, moves+1))
grid[row][col] = '.'
return -1
start = target = box = None
rows, cols = len(grid), len(grid[0])
for r, row in enumerate(grid):
for c, pos in enumerate(row):
if pos == 'S':
start = (r, c)
grid[r][c] = '.'
elif pos == 'T':
target = (r, c)
grid[r][c] = '.'
elif pos == 'B':
box = (r, c)
grid[r][c] = '.'
return box_bfs(*box) | minimum-moves-to-move-a-box-to-their-target-location | Python3 Double BFS | O(m^2 * n^2) | ryangrayson | 0 | 24 | minimum moves to move a box to their target location | 1,263 | 0.49 | Hard | 18,828 |
https://leetcode.com/problems/minimum-moves-to-move-a-box-to-their-target-location/discuss/2279461/Python-BFS-*-DFS | class Solution:
def minPushBox(self, grid: List[List[str]]) -> int:
# dfs to move person
# bfs to move box
m = len(grid)
n = len(grid[0])
dirc = [(1, 0), (-1, 0), (0, 1), (0, -1)]
si, sj, bi, bj, tari, tarj = -1, -1, -1, -1, -1, -1
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == "S":
si, sj = i, j
if grid[i][j] == "B":
bi, bj = i, j
if grid[i][j] == "T":
tari, tarj = i, j
def ok(i, j, bi=-1, bj=-1):
if i < 0 or j < 0 or i >= m or j >= n:
return False
if grid[i][j] == "#" or (i == bi and j == bj):
return False
return True
def p_reachable(si, sj, ti, tj, bi, bj):
if not ok(ti, tj, bi, bj):
return False
vis = set()
def dfs(i, j):
vis.add((i, j))
if i == ti and j == tj:
return True
flag = False
for d in dirc:
newi, newj = i + d[0], j + d[1]
if ok(newi, newj, bi, bj) and (newi, newj) not in vis:
flag = flag or dfs(newi, newj)
return flag
return dfs(si, sj)
queue = deque()
queue.append(((bi, bj), (si, sj)))
bvis = set()
cnt = 0
while queue:
l = len(queue)
for i in range(l):
cur = queue.popleft()
if cur[0][0] == tari and cur[0][1] == tarj:
return cnt
for d in dirc:
newbi = cur[0][0] + d[0]
newsi = cur[0][0] - d[0]
newbj = cur[0][1] + d[1]
newsj = cur[0][1] - d[1]
if ok(newbi, newbj) and ((newbi, newbj), (cur[0][0], cur[0][1])) not in bvis and p_reachable(cur[1][0], cur[1][1], newsi, newsj, cur[0][0], cur[0][1]):
queue.append(((newbi, newbj), (cur[0][0], cur[0][1])))
bvis.add(((newbi, newbj), (cur[0][0], cur[0][1])))
cnt += 1
return -1 | minimum-moves-to-move-a-box-to-their-target-location | [Python] BFS * DFS | van_fantasy | 0 | 33 | minimum moves to move a box to their target location | 1,263 | 0.49 | Hard | 18,829 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/1114113/Python3-solution-with-explaination | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
timer = 0
for i in range(len(points)-1):
dx = abs(points[i+1][0] - points[i][0])
dy = abs(points[i+1][1] - points[i][1])
timer = timer + max(dx,dy)
return timer | minimum-time-visiting-all-points | Python3 solution with explaination | shreytheshreyas | 4 | 285 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,830 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/942851/Python-Easy-Solution | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
d=0
for i in range(len(points)-1):
d+=max(abs(points[i][0]-points[i+1][0]),abs(points[i][1]-points[i+1][1]))
return d | minimum-time-visiting-all-points | Python Easy Solution | lokeshsenthilkumar | 3 | 378 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,831 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/1724876/Python-dollarolution | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
count = 0
for i in range(1,len(points)):
count += max(abs(points[i-1][0] - points[i][0]), abs(points[i-1][1] - points[i][1]))
return count | minimum-time-visiting-all-points | Python $olution | AakRay | 2 | 125 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,832 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/1633510/Simple-python-destructure-solution | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
answer =0
for i in range(len(points)-1):
x, y = points[i]
x1, y1 = points[i+1]
answer += max(abs(x1-x), abs(y1-y))
return answer | minimum-time-visiting-all-points | Simple python destructure solution | Buyanjargal | 2 | 123 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,833 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/1225126/36ms-Python-(with-comments) | class Solution(object):
def minTimeToVisitAllPoints(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
#We initiate a variable to store the output
distance = 0
#we initialise the start point with the 1st point in the list, so that we can iterate all the points using this variable
start_point = points[0]
#for loop to iterate through all the points
for point in points[1:]:
#for the logic behind this formuala, see below in this post
distance += max(abs(start_point[0]-point[0]),abs(start_point[1]-point[1]))
#we add up the shortest distances between each points to get the shortest traversal distance
start_point = point
return distance | minimum-time-visiting-all-points | 36ms, Python (with comments) | Akshar-code | 1 | 226 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,834 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/538833/Python3%3A-Greedy-approach-using-Max-with-commentary | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
# Check Edge Cases
length = len(points)
if length <= 1:
return 0
index, result = 0, 0
while index < length - 1:
# Grab current point and next one to visit
start, destination = points[index], points[index+1]
# We can simply rely on max of x or y delta
result += max(abs(start[0] - destination[0]), abs(start[1] - destination[1]))
index += 1 | minimum-time-visiting-all-points | Python3: Greedy approach using Max with commentary | dentedghost | 1 | 84 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,835 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/2847306/python3 | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
counter = 0
for i in range(len(points) - 1):
if abs(points[i+1][0] - points[i][0]) > abs(points[i+1][1] - points[i][1]):
counter += abs(points[i+1][0] - points[i][0])
else:
counter += abs(points[i+1][1] - points[i][1])
return counter | minimum-time-visiting-all-points | python3 | Geniuss87 | 0 | 1 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,836 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/2825220/Simple-python | class Solution:
def minTimeToVisitAllPoints(self, A: List[List[int]]) -> int:
ans = 0
for i in range(1, len(A)):
dx = abs(A[i][0] - A[i-1][0])
dy = abs(A[i][1] - A[i-1][1])
ans += max(dx, dy)
return ans | minimum-time-visiting-all-points | Simple python | js44lee | 0 | 1 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,837 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/2799111/1-liner-beats-Time-greater-99-Space-greater-77 | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
return sum([max(abs(points[i][0] - points[i+1][0]), abs(points[i][1] - points[i+1][1])) for i in range(len(points) - 1)]) | minimum-time-visiting-all-points | 1-liner beats Time -> 99% Space -> 77% | RandomNPC | 0 | 6 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,838 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/2777992/python-super-easy | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
s_x, s_y = points[0]
ans = 0
for i in range(1, len(points)):
x, y = points[i]
ans += max(abs(x-s_x), abs(y-s_y))
s_x, s_y = x, y
return ans | minimum-time-visiting-all-points | python super easy | harrychen1995 | 0 | 1 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,839 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/2774632/Python-Solution-Time-Complexity-O(len(points)) | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
distance = 0
for i in range(len(points)-1):
dx = abs(points[i][0] - points[i+1][0])
dy = abs(points[i][1] - points[i+1][1])
distance = distance + max(dx,dy)
return distance | minimum-time-visiting-all-points | Python Solution - Time Complexity - O(len(points)) | danishs | 0 | 1 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,840 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/2671896/Simply-written-easy-to-understand-python-code... | class Solution(object):
def minTimeToVisitAllPoints(self, p):
c=0
for i in range(len(p)-1):
m=abs(p[i][0]-p[i+1][0])
n=abs(p[i][1]-p[i+1][1])
c+=max(m,n)
return c
"""
:type points: List[List[int]]
:rtype: int
""" | minimum-time-visiting-all-points | Simply written, easy to understand python code... | Hashir311 | 0 | 4 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,841 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/2573394/SIMPLE-PYTHON3-SOLUTION-FASTer | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
s = 0
for i in range(len(points)-1):
s += max(abs(points[i+1][1]-points[i][1]),
abs(points[i+1][0]-points[i][0]))
return s | minimum-time-visiting-all-points | ✅✔ SIMPLE PYTHON3 SOLUTION ✅✔ FASTer | rajukommula | 0 | 26 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,842 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/2407578/python-solution-91.15-faster | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
total_time = 0
for i in range(len(points)-1):
if abs(points[i+1][0] - points[i][0]) > abs(points[i+1][1] - points[i][1]):
total_time += abs(points[i+1][0] - points[i][0])
else:
total_time += abs(points[i+1][1] - points[i][1])
return total_time | minimum-time-visiting-all-points | python solution 91.15% faster | samanehghafouri | 0 | 53 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,843 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/2385285/simple-Python3 | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
ans = 0
for i in range(len(points)-1):
x_dif = points[i][0] - points[i+1][0]
y_dif = points[i][1] - points[i+1][1]
ans += max(abs(x_dif), abs(y_dif))
return ans | minimum-time-visiting-all-points | simple Python3 | ellie_aa | 0 | 28 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,844 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/2061779/Simple-Python-beats-95 | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
time = 0
prev = points[0]
for p in points[1::]:
time += max(abs(prev[0]-p[0]), abs(prev[1]-p[1]))
prev=p
return time | minimum-time-visiting-all-points | Simple Python beats 95% | mman22 | 0 | 72 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,845 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/1921418/very-easy-commented-basic-level-python-code | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
actp = points[0]
count = 0
i = 1
while(i<len(points)):
#equal
if actp[0]==points[i][0] and actp[1]==points[i][1]:
i+=1
#up
elif actp[0]==points[i][0] and actp[1]<points[i][1]:
actp[1] += 1
count += 1
#down
elif actp[0]==points[i][0] and actp[1]>points[i][1]:
actp[1] -= 1
count += 1
#left
elif actp[0]>points[i][0] and actp[1]==points[i][1]:
actp[0] -= 1
count += 1
#right
elif actp[0]<points[i][0] and actp[1]==points[i][1]:
actp[0] += 1
count += 1
#digonal right up
elif actp[0]<points[i][0] and actp[1]<points[i][1]:
actp[0] += 1
actp[1] += 1
count += 1
#digonal left up
elif actp[0]>points[i][0] and actp[1]<points[i][1]:
actp[0] -= 1
actp[1] += 1
count += 1
#digonal left down
elif actp[0]>points[i][0] and actp[1]>points[i][1]:
actp[0] -= 1
actp[1] -= 1
count += 1
#digonal right down
elif actp[0]<points[i][0] and actp[1]>points[i][1]:
actp[0] += 1
actp[1] -= 1
count += 1
return count | minimum-time-visiting-all-points | very easy commented basic level python code | dakash682 | 0 | 74 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,846 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/1862062/Python-(Simple-Approach-and-Beginner-Friendly) | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
diff = 0
op = 0
for i in range(0, len(points)-1):
diff1 = abs(points[i][0] - points[i+1][0])
diff2 = abs(points[i][1] - points[i+1][1])
diff = max(diff1, diff2)
op+=diff
return op | minimum-time-visiting-all-points | Python (Simple Approach and Beginner-Friendly) | vishvavariya | 0 | 137 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,847 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/1834344/3-Lines-Python-Solution-oror-92-Faster-(60ms)oror-Memory-less-than-90 | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
ans=0
for i in range(len(points)-1): ans+=max(abs(points[i+1][0]-points[i][0]), abs(points[i+1][1]-points[i][1]))
return ans | minimum-time-visiting-all-points | 3-Lines Python Solution || 92% Faster (60ms)|| Memory less than 90% | Taha-C | 0 | 88 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,848 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/1814827/Python-Solution | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
steps = 0
for i in range(0,len(points)-1):
xdiff = abs(points[i][0] - points[i+1][0])
ydiff = abs(points[i][1] - points[i+1][1])
steps += max(xdiff,ydiff)
return steps | minimum-time-visiting-all-points | Python Solution | MS1301 | 0 | 88 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,849 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/1722883/python-solution | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
minTime = 0
if len(points) == 1:
return 0
for i in range(1, len(points)):
minTime += max(abs(points[i][0]-points[i-1][0]), abs(points[i][1]-points[i-1][1]))
return minTime | minimum-time-visiting-all-points | python solution | alexxu666 | 0 | 43 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,850 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/1609608/One-pass-99-speed | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
return sum(max(abs(i - x), abs(j - y)) for (i, j), (x, y)
in zip(points, points[1:])) | minimum-time-visiting-all-points | One pass, 99% speed | EvgenySH | 0 | 141 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,851 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/1597462/Python-3-fast-easy-solution | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
res = 0
for i in range(len(points) - 1):
res += max(abs(points[i][0] - points[i+1][0]),
abs(points[i][1] - points[i+1][1]))
return res | minimum-time-visiting-all-points | Python 3, fast, easy solution | dereky4 | 0 | 125 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,852 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/1399941/Runtime%3A-40-ms-faster-than-100.00-of-Python3-online-submissions | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
c=0
for i in range(len(points)-1):
a,b=points[i][0],points[i][1]
p,q=points[i+1][0],points[i+1][1]
c+=max(abs(p-a),abs(q-b))
return c | minimum-time-visiting-all-points | Runtime: 40 ms, faster than 100.00% of Python3 online submissions | harshmalviya7 | 0 | 76 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,853 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/1356145/Python-Explained-with-simple-logic.-Outperform-99-with-O(n)-TC-and-O(1)-SC | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
td = 0
for p in range(len(points)-1):
point1 , point2 = points[p] , points[p+1]
td += max(abs(point1[0] - point2[0]) , abs(point1[1] - point2[1])
return td | minimum-time-visiting-all-points | [Python] Explained with simple logic. Outperform 99% with O(n) TC and O(1) SC | er1shivam | 0 | 102 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,854 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/1214900/Python-Easy-logical-solution | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
time = 0
for i in range(len(points)-1):
x = points[i][0] - points[i+1][0]
y = points[i][1] - points[i+1][1]
time+= max(abs(x),abs(y))
return time | minimum-time-visiting-all-points | Python Easy logical solution | bagdaulet881 | 0 | 103 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,855 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/1153749/Runtime%3A-60-ms-faster-than-54.59-of-Python3-.-Memory-Usage%3A-14.1-MB-less-than-88.27-of-Python3 | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
TimeisTime = 0
for coordinates in range(1, len(points)):
TimeisTime += max(abs(points[coordinates][0] - points[coordinates - 1][0]),
abs(points[coordinates][1] - points[coordinates - 1][1]))
return TimeisTime | minimum-time-visiting-all-points | Runtime: 60 ms, faster than 54.59% of Python3 . Memory Usage: 14.1 MB, less than 88.27% of Python3 | aashutoshjha21022002 | 0 | 59 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,856 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/1061017/Python-Easy-and-Fast-Solution | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
distance = 0
for i in range(1,len(points)):
distance+= max(abs(points[i][0]-points[i-1][0]),abs(points[i][1]-points[i-1][1]))
return distance | minimum-time-visiting-all-points | Python Easy and Fast Solution | Akarsh_B | 0 | 108 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,857 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/813533/Python-3-Solution-faster-than-98 | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
seconds = 0
for x in range(len(points)-1):
seconds += max(abs(points[x][0] - points[x + 1][0]), abs(points[x][1] - points[x + 1][1]))
return seconds | minimum-time-visiting-all-points | Python 3 Solution, faster than 98% | justxn | 0 | 78 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,858 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/437805/Python3-two-solutions-(one-short-1-liner-and-one-fast-99.72) | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
return sum(max(abs(points[i][0]-points[i-1][0]), abs(points[i][1]-points[i-1][1])) for i in range(1, len(points))) | minimum-time-visiting-all-points | Python3 two solutions (one short 1-liner & one fast 99.72%) | ye15 | 0 | 143 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,859 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/437805/Python3-two-solutions-(one-short-1-liner-and-one-fast-99.72) | class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
ans = 0
x0, x1 = points[0]
for i in range(1, len(points)):
(y0, y1) = points[i]
ans += max(abs(x0-y0), abs(x1-y1))
x0, x1 = y0, y1
return ans | minimum-time-visiting-all-points | Python3 two solutions (one short 1-liner & one fast 99.72%) | ye15 | 0 | 143 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,860 |
https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/436224/Python-3-(five-lines)-(beats-100) | class Solution:
def minTimeToVisitAllPoints(self, P: List[List[int]]) -> int:
L, t = len(P), 0
for i in range(L-1):
(a,b), (c,d) = P[i], P[i+1]
t += max(abs(a-c),abs(b-d))
return t
- Junaid Mansuri | minimum-time-visiting-all-points | Python 3 (five lines) (beats 100%) | junaidmansuri | 0 | 300 | minimum time visiting all points | 1,266 | 0.791 | Easy | 18,861 |
https://leetcode.com/problems/count-servers-that-communicate/discuss/1587912/93-faster-oror-Well-Explained-oror-Thought-Process-oror-Clean-and-Concise | class Solution:
def countServers(self, grid: List[List[int]]) -> int:
m,n = len(grid),len(grid[0])
rows = [0]*m
cols = [0]*n
total = 0
for i in range(m):
for j in range(n):
if grid[i][j]==1:
rows[i]+=1
cols[j]+=1
total+=1
cnt = 0
for i in range(m):
for j in range(n):
if grid[i][j]==1 and rows[i]==1 and cols[j]==1:
cnt+=1
return total-cnt | count-servers-that-communicate | 📌📌 93% faster || Well-Explained || Thought Process || Clean and Concise 🐍 | abhi9Rai | 2 | 147 | count servers that communicate | 1,267 | 0.593 | Medium | 18,862 |
https://leetcode.com/problems/count-servers-that-communicate/discuss/1944177/Python-3-Easy-DFS-solution | class Solution:
def countServers(self, grid: List[List[int]]) -> int:
#DFS
def solve(r,c):
grid[r][c]=-1
nonlocal ans
ans+=1
for i in range(len(grid)):
if grid[i][c]==1:
solve(i, c)
for j in range(len(grid[0])):
if grid[r][j]==1:
solve(r, j)
count=0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]==1:
ans=0
solve(i,j)
if ans>1:
count+=ans
return count | count-servers-that-communicate | [Python 3] Easy DFS solution✔ | RaghavGupta22 | 1 | 162 | count servers that communicate | 1,267 | 0.593 | Medium | 18,863 |
https://leetcode.com/problems/count-servers-that-communicate/discuss/1697079/Python-simple-O(mn)-time-O(max(m-n))-space-solution | class Solution:
def countServers(self, grid):
m, n = len(grid), len(grid[0])
row = defaultdict(int)
col = defaultdict(int)
tot = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
row[i] += 1
col[j] += 1
tot += 1
res = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1 and row[i] ==1 and col[j] == 1:
res += 1
return tot - res | count-servers-that-communicate | Python simple O(mn) time, O(max(m, n)) space solution | byuns9334 | 1 | 81 | count servers that communicate | 1,267 | 0.593 | Medium | 18,864 |
https://leetcode.com/problems/count-servers-that-communicate/discuss/2656594/Python-Solution-w-comments | class Solution:
def countServers(self, grid: List[List[int]]) -> int:
ROWS, COLS = len(grid), len(grid[0])
# store num servers seen in row
rows = {}
# store num servers seen in col
cols = {}
res = 0
# loop through grid and if server in cell, increment the current row and column server count by 1
for row in range(ROWS):
for col in range(COLS):
if grid[row][col] == 1:
rows[row] = rows.get(row, 0) + 1
cols[col] = cols.get(col, 0) + 1
# loop through grid and if cell is a server and count of servers in row or col is greater than 1, increment res
for row in range(ROWS):
for col in range(COLS):
if grid[row][col] == 1 and (rows.get(row, 0) > 1 or cols.get(col, 0) > 1):
res += 1
return res | count-servers-that-communicate | Python Solution w/ comments | Mark5013 | 0 | 9 | count servers that communicate | 1,267 | 0.593 | Medium | 18,865 |
https://leetcode.com/problems/count-servers-that-communicate/discuss/2247928/Python-short-concise-solution-(-9-lines-) | class Solution:
def countServers(self, grid: List[List[int]]) -> int:
M, N = len(grid), len(grid[0])
# count number of servers in a row / col
rows = defaultdict(int)
cols = defaultdict(int)
for r in range(M):
for c in range(N):
rows[r] += grid[r][c]
cols[c] += grid[r][c]
# not isolated if grid[r][c] == 1 and there's more than 1 server in same row or col
notIsolated = lambda r, c: grid[r][c] and (rows[r] > 1 or cols[c] > 1)
return sum(notIsolated(r, c) for r in range(M) for c in range(N)) | count-servers-that-communicate | Python short concise solution ( 9 lines ) | SmittyWerbenjagermanjensen | 0 | 25 | count servers that communicate | 1,267 | 0.593 | Medium | 18,866 |
https://leetcode.com/problems/count-servers-that-communicate/discuss/2166097/Easiest-Solution | class Solution:
def countServers(self, grid: List[List[int]]) -> int:
serverCount = 0
n = len(grid)
m = len(grid[0])
cols = [0]*n
rows = [0]*m
totalServers = 0
for i in range(n):
for j in range(m):
if grid[i][j] == 1:
totalServers += 1
cols[i] += 1
rows[j] += 1
singleServers = 0
for i in range(n):
for j in range(m):
if grid[i][j] == 1 and cols[i] == 1 and rows[j] == 1:
singleServers += 1
return totalServers - singleServers | count-servers-that-communicate | Easiest Solution | Vaibhav7860 | 0 | 45 | count servers that communicate | 1,267 | 0.593 | Medium | 18,867 |
https://leetcode.com/problems/count-servers-that-communicate/discuss/2089324/Python3-Solution | class Solution:
def countServers(self, grid):
positions = self.check_ones(grid)
count = 0
for i in range(0,len(positions)):
if self.check_(positions[i],positions[0:i] + positions[i+1:]):
count +=1
return count
def check_(self,current,positions):
x = current[0]
y = current[1]
x_match = len([item for item in positions if item[0] == x])
y_match = len([item for item in positions if item[1] == y])
return (y_match + x_match) > 0
def check_ones(self,grid):
ones_array =[]
for row in range(0,len(grid)):
for column in range(0,len(grid[row])):
if grid[row][column] == 1:
ones_array.append([row,column])
return ones_array | count-servers-that-communicate | Python3 Solution | xevb | 0 | 35 | count servers that communicate | 1,267 | 0.593 | Medium | 18,868 |
https://leetcode.com/problems/count-servers-that-communicate/discuss/1937683/Python3-Code-Easy-Implementation-DO-CHECK-OUT!!! | class Solution:
def countServers(self, grid: List[List[int]]) -> int:
rows=[0]*len(grid)
cols=[0]*len(grid[0])
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]==1:
rows[i]+=1
cols[j]+=1
visited=[[False for j in range(len(grid[0]))]for i in range(len(grid))]
count=0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]==1 and rows[i]>1 and not visited[i][j]:
visited[i][j]=True
count+=1
if grid[i][j]==1 and cols[j]>1 and not visited[i][j]:
visited[i][j]=True
count+=1
return count | count-servers-that-communicate | Python3 Code -Easy Implementation DO CHECK OUT!!! | shambhavi_gupta | 0 | 38 | count servers that communicate | 1,267 | 0.593 | Medium | 18,869 |
https://leetcode.com/problems/count-servers-that-communicate/discuss/1892732/Python-easy-to-read-and-understand | class Solution:
def countServers(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
row, col = [0 for _ in range(m)], [0 for _ in range(n)]
for i in range(m):
for j in range(n):
row[i] += grid[i][j]
col[j] += grid[i][j]
ans = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1 and (row[i] > 1 or col[j] > 1):
ans += 1
return ans | count-servers-that-communicate | Python easy to read and understand | sanial2001 | 0 | 35 | count servers that communicate | 1,267 | 0.593 | Medium | 18,870 |
https://leetcode.com/problems/count-servers-that-communicate/discuss/1276346/71-faster-Python-solution-w-comments | class Solution:
def countServers(self, grid: List[List[int]]) -> int:
N = len(grid)
M = len(grid[0])
# 1. set up two dictionaries.
# rows[i] denotes server number on i-th row
# cols[j] denotes server number on j-th column
rows = {}
cols = {}
for i in range(N):
for j in range(M):
if grid[i][j] == 1:
try: rows[i] += 1
except KeyError:rows[i] = 1
try: cols[j] += 1
except KeyError:cols[j] = 1
ServerCount = 0 # total server number
AloneCount = 0 # servers that cannot communicate with other servers
for i in range(N):
for j in range(M):
if grid[i][j] == 1:
ServerCount += 1
# check its row and its column
# if both rows[i] and cols[j] are 1, it means the server is the only one on the cross (has no other friend in either row or column)
if rows[i] == 1 and cols[j] == 1:
AloneCount +=1
return ServerCount-AloneCount | count-servers-that-communicate | 71% faster Python solution w/ comments | LemonHerbs | 0 | 46 | count servers that communicate | 1,267 | 0.593 | Medium | 18,871 |
https://leetcode.com/problems/count-servers-that-communicate/discuss/790812/Simple-Solution-using-DFS-with-explanation | class Solution:
def countServers(self, grid: List[List[int]]) -> int:
R = len(grid)
C = len(grid[0])
visited = set()
def neighbours(r, c, grid):
nei = set()
for i in range(C):
nei.add((r,i))
for j in range(R):
nei.add((j,c))
nei.discard((r,c))
return nei
def dfs(grid,i,j, visited):
for nei in neighbours(i,j, grid):
x, y = nei
if nei not in visited and grid[x][y] == 1:
visited.add(nei)
for i, row in enumerate(grid):
for j, val in enumerate(row):
if val == 1:
dfs(grid, i, j, visited)
return len(visited) | count-servers-that-communicate | Simple Solution using DFS with explanation | cppygod | 0 | 231 | count servers that communicate | 1,267 | 0.593 | Medium | 18,872 |
https://leetcode.com/problems/search-suggestions-system/discuss/436564/Python-A-simple-approach-without-using-Trie | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
list_ = []
products.sort()
for i, c in enumerate(searchWord):
products = [ p for p in products if len(p) > i and p[i] == c ]
list_.append(products[:3])
return list_ | search-suggestions-system | [Python] A simple approach without using Trie | crosserclaws | 39 | 3,500 | search suggestions system | 1,268 | 0.665 | Medium | 18,873 |
https://leetcode.com/problems/search-suggestions-system/discuss/436564/Python-A-simple-approach-without-using-Trie | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
list_ = []
products.sort()
for i, c in enumerate(searchWord):
products = list(filter(lambda p: p[i] == c if len(p) > i else False, products))
list_.append(products[:3])
return list_ | search-suggestions-system | [Python] A simple approach without using Trie | crosserclaws | 39 | 3,500 | search suggestions system | 1,268 | 0.665 | Medium | 18,874 |
https://leetcode.com/problems/search-suggestions-system/discuss/864637/Python-3-or-Two-Methods-(Sort-Trie)-or-Explanation | class Solution:
def suggestedProducts(self, A: List[str], searchWord: str) -> List[List[str]]:
A.sort()
res, cur = [], ''
for c in searchWord:
cur += c
i = bisect.bisect_left(A, cur)
res.append([w for w in A[i:i+3] if w.startswith(cur)])
return res | search-suggestions-system | Python 3 | Two Methods (Sort, Trie) | Explanation | idontknoooo | 24 | 2,300 | search suggestions system | 1,268 | 0.665 | Medium | 18,875 |
https://leetcode.com/problems/search-suggestions-system/discuss/2169028/Simple-Easy-Approach | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
product = []
for i in range(len(searchWord)):
p = []
for prod in products:
if prod.startswith(searchWord[:i+1]):
p.append(prod)
p = sorted(p)[:3]
product.append(p)
return product | search-suggestions-system | Simple Easy Approach | Vaibhav7860 | 4 | 158 | search suggestions system | 1,268 | 0.665 | Medium | 18,876 |
https://leetcode.com/problems/search-suggestions-system/discuss/1597537/Python-Using-Trie | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
products.sort()
obj = Trie()
for product in products:
obj.insert(product)
final = []
word = ''
for char in searchWord:
word += char
final.append(obj.search(word))
return final
class Trie:
def __init__(self):
self.root = dict()
def insert(self, word):
current = self.root
for char in word:
if char not in current:
current[char] = dict()
current = current[char]
current['*'] = '*'
def search(self, word):
current = self.root
for char in word:
if char not in current:
return []
current = current[char]
self.result = []
self.dfs(current, word)
if len(self.result) > 3:
return self.result[:3]
return self.result
def dfs(self, node, word):
for value in node:
if value == '*':
self.result.append(word)
else:
self.dfs(node[value], word+value) | search-suggestions-system | Python Using Trie | Call-Me-AJ | 4 | 410 | search suggestions system | 1,268 | 0.665 | Medium | 18,877 |
https://leetcode.com/problems/search-suggestions-system/discuss/1015508/Python-7-line-solution | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
result = []
products.sort()
for x in range(len(searchWord)):
word = searchWord[:x+1]
products = [item for item in products if item.startswith(word)]
result.append(products[:3])
return result | search-suggestions-system | Python 7-line solution | JulesCui | 4 | 327 | search suggestions system | 1,268 | 0.665 | Medium | 18,878 |
https://leetcode.com/problems/search-suggestions-system/discuss/2168095/Python3-Easy-to-Understand | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
result = []
for idx, _ in enumerate(searchWord):
temp_result = [item for item in products if searchWord[:idx+1] == item[:idx+1]]
temp_result.sort()
result.append(temp_result[:3])
return result | search-suggestions-system | Python3 - Easy - to - Understand | thesauravs | 1 | 69 | search suggestions system | 1,268 | 0.665 | Medium | 18,879 |
https://leetcode.com/problems/search-suggestions-system/discuss/2167903/Python3-or-Very-easy-to-understand-or-Basic-approach | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
products.sort()
list_suggested_products=[]
search_word = ''
for e in searchWord:
search_word += e
list_suggested_products.append(self.search(products, search_word))
return list_suggested_products
def search(self, products, word):
index=0
for i, w in enumerate(products):
if word == w[:len(word)]:
index=i
break
similar_elements = []
for i in range(index, min(index+3, len(products))):
if word == products[i][:len(word)]:
similar_elements.append(products[i])
return similar_elements | search-suggestions-system | Python3 | Very easy to understand | Basic approach | H-R-S | 1 | 72 | search suggestions system | 1,268 | 0.665 | Medium | 18,880 |
https://leetcode.com/problems/search-suggestions-system/discuss/1915217/Python-Dictionary-Easy-Solution | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
products.sort()
res = []
searchDict = defaultdict(list)
for i in range(1, len(searchWord)+1):
search = searchWord[:i]
searchDict[search] = [p for p in products if p[:i] == search]
res.append(searchDict[search][:3])
return res | search-suggestions-system | Python Dictionary Easy Solution | weiting-ho | 1 | 112 | search suggestions system | 1,268 | 0.665 | Medium | 18,881 |
https://leetcode.com/problems/search-suggestions-system/discuss/1243362/Python-solution-for-Search-Suggestions | class Solution(object):
def suggestedProducts(self, products, searchWord):
s = ""
l = []
products.sort()
for n, c in enumerate(searchWord):
s = s+c
count = 0
sl = []
for p in products:
if p.startswith(s):
if count <= 2:
sl.append(p)
count+=1
l.append(sl)
count = 0
return l | search-suggestions-system | Python solution for Search Suggestions | sqdude5000 | 1 | 85 | search suggestions system | 1,268 | 0.665 | Medium | 18,882 |
https://leetcode.com/problems/search-suggestions-system/discuss/967920/Python3-Brute-Force-Solution | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
searchedResult = []
products.sort()
for i in range(len(searchWord)):
serchCh = searchWord[:i+1]
result = []
for prd in products:
flag = True
if len(prd)>=len(serchCh):
for k in range(len(serchCh)):
if serchCh[k] != prd[k]:
flag = False
break
else:
flag = False
if flag and len(result)<3:
result.append(prd)
searchedResult.append(result)
return searchedResult | search-suggestions-system | Python3 Brute Force Solution | swap2001 | 1 | 116 | search suggestions system | 1,268 | 0.665 | Medium | 18,883 |
https://leetcode.com/problems/search-suggestions-system/discuss/2684711/Python3-Straight-forward-Solution | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
d = {}
prefix = ''
for idx in range(len(searchWord)):
prefix += searchWord[idx]
d[prefix] = []
for word in products:
prefix = ''
idx = 0
while idx < len(word) and idx < len(searchWord) and prefix + word[idx] in d:
prefix += word[idx]
d[prefix].append(word)
idx += 1
res = []
for k in d:
d[k].sort()
res.append(d[k][0:3])
return res | search-suggestions-system | Python3 Straight-forward Solution | Mbarberry | 0 | 13 | search suggestions system | 1,268 | 0.665 | Medium | 18,884 |
https://leetcode.com/problems/search-suggestions-system/discuss/2549948/Simple-Solution-to-understand | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
# funtion gets valid suggestion compare the prefix each iteration
def validWords(products, prefix):
x = [ word for word in products if word[:len(prefix)] == prefix]
if len(x) > 3:
x.sort()
selected = [ x[i] for i in range(3)]
return selected
else:
x.sort()
return x
result = []
# loop the len of searchWord which the number of suggestion
for i in range(1, len(searchWord)+1):
suggest = validWords(products, searchWord[:i])
result.append(suggest)
return result | search-suggestions-system | Simple Solution to understand | standard_frequency09 | 0 | 15 | search suggestions system | 1,268 | 0.665 | Medium | 18,885 |
https://leetcode.com/problems/search-suggestions-system/discuss/2488303/easy-python-solution | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
ans = []
products.sort()
for i in range(1, len(searchWord)+1) :
subArr = []
for word in products :
# print(searchWord[:i], word[:i])
if searchWord[:i] == word[:i] :
subArr.append(word)
if len(subArr) == 3 :
break
ans.append(subArr)
return ans | search-suggestions-system | easy python solution | sghorai | 0 | 50 | search suggestions system | 1,268 | 0.665 | Medium | 18,886 |
https://leetcode.com/problems/search-suggestions-system/discuss/2426437/Python-Solution-using-only-dictionary | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
mem = collections.defaultdict(list)
for p_name in products:
prefix = ''
for c in p_name:
prefix += c
mem[prefix].append(p_name)
ans = []
prefix = ''
for c in searchWord:
prefix += c
potential_ans = sorted(mem[prefix])
ans.append(potential_ans[:3])
return ans | search-suggestions-system | Python Solution using only dictionary | ihson | 0 | 64 | search suggestions system | 1,268 | 0.665 | Medium | 18,887 |
https://leetcode.com/problems/search-suggestions-system/discuss/2314791/Python-Easy-Solution | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
res = []
products.sort()
print(products)
for k,ch in enumerate(searchWord):
i = 0
j = len(products)-1
while i<=j and ( len(products[i])<=k or products[i][0:k+1]!=searchWord[0:k+1]):
i+=1
while i<=j and (len(products[j])<=k or products[j][0:k+1]!=searchWord[0:k+1]):
j-=1
temp = []
len_ = (j-i+1)
for t in range(min(3,len_)):
temp.append(products[t+i])
res.append(temp)
return res | search-suggestions-system | Python Easy Solution | Abhi_009 | 0 | 87 | search suggestions system | 1,268 | 0.665 | Medium | 18,888 |
https://leetcode.com/problems/search-suggestions-system/discuss/2292306/Python-super-easy-solution | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
products.sort()
ans = []
for i, c in enumerate(searchWord):
ans.append([])
j = 0
while j < len(products):
if i >= len(products[j]) or products[j][i] != c:
# print(x)
products = products[:j] + products[j+1:]
else:
j += 1
ans[-1] = products.copy() if len(products) <= 3 else products[:3]
return ans | search-suggestions-system | Python super easy solution | Melindaaaaa | 0 | 65 | search suggestions system | 1,268 | 0.665 | Medium | 18,889 |
https://leetcode.com/problems/search-suggestions-system/discuss/2187928/Python3-or-BinarySearch | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
ans=[]
products.sort()
for i in range(len(searchWord)):
temp=[]
for j in range(len(products)):
if products[j][:i+1]==searchWord[:i+1]:
temp.append(products[j])
ans.append(temp[:min(3,len(temp))])
products=temp
return ans | search-suggestions-system | [Python3] | BinarySearch | swapnilsingh421 | 0 | 38 | search suggestions system | 1,268 | 0.665 | Medium | 18,890 |
https://leetcode.com/problems/search-suggestions-system/discuss/2172342/Python-a-concise-binary-search | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
products.sort()
left, right = 0, len(products)
result = []
for i, c in enumerate(searchWord):
left = bisect_left(products, c, left, right, key=lambda word: word[i] if i < len(word) else '')
right = bisect_right(products, c, left, right, key=lambda word: word[i] if i < len(word) else '')
result.append(products[left:min(right, left+3)])
return result | search-suggestions-system | Python, a concise binary search | blue_sky5 | 0 | 12 | search suggestions system | 1,268 | 0.665 | Medium | 18,891 |
https://leetcode.com/problems/search-suggestions-system/discuss/2172144/Python-sort-%2B-single-pass-Easy-solution | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
tree = [[] for _ in range(len(searchWord))]
products.sort()
for product in products:
for i, l in enumerate(searchWord):
if i < len(product) and l == product[i]:
tree[i].append(product)
else:
break
return [s[:3] for s in tree] | search-suggestions-system | Python sort + single-pass Easy solution | hcks | 0 | 19 | search suggestions system | 1,268 | 0.665 | Medium | 18,892 |
https://leetcode.com/problems/search-suggestions-system/discuss/2171619/Python-or-7-Liner | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
suggestions, ans = defaultdict(list), []
for p in sorted(products):
for i in range(1,len(p)+1):
if len(suggestions[p[:i]]) < 3: suggestions[p[:i]].append(p)
for i in range(1,len(searchWord)+1):
ans.append(suggestions[searchWord[:i]])
return ans | search-suggestions-system | ✅ Python | 7 Liner | dhananjay79 | 0 | 29 | search suggestions system | 1,268 | 0.665 | Medium | 18,893 |
https://leetcode.com/problems/search-suggestions-system/discuss/2171106/Search-Suggestion-System | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
op = []
for i in range(0, len(searchWord)):
x = searchWord[:i+1]
searched_result = []
for y in products:
if y.startswith(x):
searched_result.append(y)
searched_result.sort()
searched_result = searched_result[:3]
op.append(searched_result)
return op
``` | search-suggestions-system | Search Suggestion System | vaibhav0077 | 0 | 12 | search suggestions system | 1,268 | 0.665 | Medium | 18,894 |
https://leetcode.com/problems/search-suggestions-system/discuss/2171101/Python-or-Commented-or-Dictionary-or-O(nlogn) | # Dictionary Solution
# Time: O(nlogn), Sorts prodcuts once, iterates through products once and searchWord length once (k = length of search word).
# Space: O(n), Dictionary storing list of products.
class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
products.sort() # Sort products lexigraphically.
prefixToProducts = defaultdict(list) # Maps prefix to products.
prefix = ''
for word in products: # Iterates through each word in products list.
for character in word: # Iterates through each character in product word.
prefix += character # Appends character to the current prefix.
prefixToProducts[prefix].append(word) # Appends prefix -> word maping to dictionary.
prefix = '' # Resets prefix for next word.
results = [] # List to hold the search results.
for character in searchWord: # Iterates through each character in searchWord.
prefix += character # Appends character to current prefix.
results.append(prefixToProducts[prefix][:3]) # Appends at most 3 words to list using current prefix.
return results # Returns results list containing products found with searchWord. | search-suggestions-system | Python | Commented | Dictionary | O(nlogn) | bensmith0 | 0 | 21 | search suggestions system | 1,268 | 0.665 | Medium | 18,895 |
https://leetcode.com/problems/search-suggestions-system/discuss/2170500/Python-oror-Simplified-Solution-and-Explanation | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
# sort the products list lexicographically
products.sort()
# initialize an result array
result = []
# iterating through the length of searchWord
for i in range(len(searchWord)):
# filter through each word that starts with searchWord from start, to the current iteration index (taking a slice of searchword)
temp = list(filter(lambda x: x.startswith(searchWord[:i+1]), products))
# append the first 3 element if the filter result is longer than 3 else append the entire filter resutl
result.append(temp[:min(len(temp), 3)])
# update the new search list to the previous result to reduce the search space
products = temp
return result | search-suggestions-system | Python || Simplified Solution and Explanation | Tobi_Akin | 0 | 21 | search suggestions system | 1,268 | 0.665 | Medium | 18,896 |
https://leetcode.com/problems/search-suggestions-system/discuss/2170458/Simple-Trie-Solution-or-Faster-than-77-or-Python | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
trie = self.createTrie(sorted(products))
words = [[] for _ in range(len(searchWord))]
self.search(trie, searchWord, words)
return words
def createTrie(self, products: List[str]):
trie = dict()
for product in products:
curr = trie
for i in product:
if i not in curr:
curr[i] = {'word_list':[product]}
else:
curr[i]['word_list'].append(product)
curr = curr[i]
return trie
def search(self, trie, searchWord, words):
curr = trie
for i, char in enumerate(searchWord):
if char not in curr:
break
curr = curr[char]
words[i] = curr['word_list'][:3]
return words | search-suggestions-system | Simple Trie Solution | Faster than 77% | Python | reJuicy | 0 | 81 | search suggestions system | 1,268 | 0.665 | Medium | 18,897 |
https://leetcode.com/problems/search-suggestions-system/discuss/2170352/python-easy-to-understand-better-than-76-of-runtime | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
answer = [[] for i in range(len(searchWord))]
flag = False;
products = sorted(products)
for i in products:
if (i[0]==searchWord[0]):
flag = True
for j in range(1,len(searchWord)+1):
if (i[0:j]==searchWord[0:j]):
if(len(answer[j-1])<3):
answer[j-1].append(i)
else:
continue
else:
break
elif(flag):
break
return answer | search-suggestions-system | python-easy to understand-better than 76% of runtime | rojanrookhosh | 0 | 16 | search suggestions system | 1,268 | 0.665 | Medium | 18,898 |
https://leetcode.com/problems/search-suggestions-system/discuss/2168710/Python-2-Lines-(Slow) | class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
products.sort()
return [[product for product in products if product.startswith(searchWord[:i + 1])][:3] for i in range(len(searchWord))] | search-suggestions-system | Python 2 Lines (Slow) | Pootato | 0 | 27 | search suggestions system | 1,268 | 0.665 | Medium | 18,899 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.