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/maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/discuss/2401947/Python-easy-to-read-and-understand-or-prefix-sum | class Solution:
def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:
m, n = len(mat), len(mat[0])
t = [[0 for _ in range(n+1)] for _ in range(m+1)]
for i in range(1, m+1):
for j in range(1, n+1):
t[i][j] = t[i][j-1] + t[i-1][j] - t[i-1][j-1] + mat[i-1][j-1]
ans = 0
for i in range(1, m+1):
for j in range(1, n+1):
start = 1
end = min(i, j)
while start <= end:
mid = (start+end) // 2
sums = t[i][j] - t[i-mid][j] - t[i][j-mid] + t[i-mid][j-mid]
if sums <= threshold:
ans = max(ans, mid)
start = mid+1
else:
end = mid-1
return ans | maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold | Python easy to read and understand | prefix-sum | sanial2001 | 0 | 100 | maximum side length of a square with sum less than or equal to threshold | 1,292 | 0.532 | Medium | 19,200 |
https://leetcode.com/problems/maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/discuss/1708213/Python-or-Prefix-Sum-%2B-Binary-Search-or-Template | class Solution:
def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:
m, n = len(mat), len(mat[0])
prefix = copy.deepcopy(mat)
rsum = 0
for i in range(m):
rsum += mat[i][0]
prefix[i][0] = rsum
csum = 0
for j in range(n):
csum += mat[0][j]
prefix[0][j] = csum
for i in range(1, m):
for j in range(1, n):
prefix[i][j] += prefix[i - 1][j] + prefix[i][j - 1] - prefix[i - 1][j - 1]
#print(prefix)
def calculate(i, j, mid):
r, c = i + mid - 1, j + mid - 1
this = prefix[r][c]
if j - 1 > -1:
this -= prefix[r][j - 1]
if i - 1 > -1:
this -= prefix[i - 1][c]
if i - 1 > -1 and j - 1 > -1:
this += prefix[i - 1][j - 1]
return this
def check(mid):
i, j = 0, 0
while i <= m - mid:
j = 0
while j <= n - mid:
this = calculate(i, j, mid)
if this <= threshold:
#print(i, j, mid, this)
return True
j += 1
i += 1
return False
l, r = 0, threshold
ans = -1
while l <= r:
mid = (l + r) // 2
if check(mid):
ans = mid
l = mid + 1
else:
r = mid - 1
return ans | maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold | Python | Prefix Sum + Binary Search | Template | detective_dp | 0 | 169 | maximum side length of a square with sum less than or equal to threshold | 1,292 | 0.532 | Medium | 19,201 |
https://leetcode.com/problems/maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/discuss/1652656/python-simple-solution-or-83.92 | class Solution:
def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:
m,n = len(mat),len(mat[0])
# 2-dimention prefix sum array
P = [[0]*(n+1) for _ in range(m+1)]
for i in range(1, m+1):
for j in range(1, n+1):
P[i][j] = P[i-1][j] + P[i][j-1] - P[i-1][j-1] + mat[i-1][j-1]
def getSumOfSqr(x1, y1, x2, y2):
return P[x2][y2] - P[x1-1][y2] - P[x2][y1-1] + P[x1-1][y1-1]
r,ans = min(m,n),0
for i in range(1, m+1):
for j in range(1, n+1):
# increase the side-length of square
for c in range(ans+1, r+1):
if i+c-1<=m and j+c-1<=n and getSumOfSqr(i,j,i+c-1,j+c-1)<=threshold:
ans += 1
else:
break
return ans | maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold | python simple solution | 83.92% | 1579901970cg | 0 | 158 | maximum side length of a square with sum less than or equal to threshold | 1,292 | 0.532 | Medium | 19,202 |
https://leetcode.com/problems/maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/discuss/451902/Python-3-(beats-100)-(ten-lines) | class Solution:
def maxSideLength(self, G: List[List[int]], t: int) -> int:
M, N, m = len(G), len(G[0]), 0; S = [[0]*(N+1) for _ in range(M+1)]
S[1] = list(itertools.accumulate([0]+G[0]))
for i in range(1,M):
s = list(itertools.accumulate(G[i]))
for j in range(N): S[i+1][j+1] = s[j] + S[i][j+1]
for i,j in itertools.product(range(M),range(N)):
for L in range(m+1, min(M-i+1,N-j+1)):
if S[i+L][j+L]-S[i][j+L]-S[i+L][j]+S[i][j] <= t: m = max(m,L)
else: break
return m
- Junaid Mansuri
- Chicago, IL | maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold | Python 3 (beats 100%) (ten lines) | junaidmansuri | 0 | 344 | maximum side length of a square with sum less than or equal to threshold | 1,292 | 0.532 | Medium | 19,203 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/2758292/Python-Simple-and-Easy-Way-to-Solve-or-95-Faster | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
m, n = len(grid), len(grid[0])
# x, y, obstacles, steps
q = deque([(0,0,k,0)])
seen = set()
while q:
x, y, left, steps = q.popleft()
if (x,y,left) in seen or left<0:
continue
if (x, y) == (m-1, n-1):
return steps
seen.add((x,y,left))
if grid[x][y] == 1:
left-=1
for dx, dy in [(1,0), (-1,0), (0,1), (0,-1)]:
new_x, new_y = x+dx, y+dy
if 0<=new_x<m and 0<=new_y<n:
q.append((new_x, new_y, left, steps+1))
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | ✔️ Python Simple and Easy Way to Solve | 95% Faster 🔥 | pniraj657 | 14 | 995 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,204 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/2759679/Python-or-95-faster-or-Easy-and-clean-code-using-BFS-approach | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
if len(grid) == 1 and len(grid[0]) == 1:
return 0
q = deque([(0,0,k,0)])
visited = set([(0,0,k)])
if (len(grid)-1) + (len(grid[0])-1) < k:
return (len(grid)-1) + (len(grid[0])-1)
while q:
r, c, e, steps = q.popleft()
for new_r,new_c in [(r-1,c), (r+1,c), (r,c-1), (r,c+1)]:
if (new_r >= 0 and
new_r < len(grid) and
new_c >= 0 and
new_c < len(grid[0])):
if grid[new_r][new_c] == 1 and e > 0 and (new_r,new_c,e-1) not in visited:
visited.add((new_r,new_c,e-1))
q.append((new_r,new_c,e-1,steps+1))
if grid[new_r][new_c] == 0 and (new_r,new_c,e) not in visited:
if new_r == len(grid) - 1 and new_c == len(grid[0]) - 1:
return steps + 1
visited.add((new_r,new_c,e))
q.append((new_r,new_c,e,steps+1))
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | Python | 95% faster | Easy and clean code using BFS approach | __Asrar | 5 | 289 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,205 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/1485029/easy-understand-python-bfs-solution | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
m = len(grid)
n = len(grid[0])
if m == 1 and n == 1:
return 0
ans = 1
visited = [[-1] * n for _ in range(m)]
visited[0][0] = k
queue = [(0, 0, k)]
while queue:
tmp = []
for i in queue:
for x, y in [(i[0] - 1, i[1]), (i[0], i[1] - 1), (i[0] + 1, i[1]), (i[0], i[1] + 1)]:
if 0 <= x < m and 0 <= y < n and i[2] >= grid[x][y] and i[2] - grid[x][y] > visited[x][y]:
visited[x][y] = (i[2] - grid[x][y])
tmp.append((x, y, i[2] - grid[x][y]))
if x == m - 1 and y == n - 1:
return ans
queue = tmp
ans += 1
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | easy understand python bfs solution | alex391a | 5 | 130 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,206 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/1854463/Python-3-Easy-and-clear-solution. | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
queue=deque()
queue.append([0,0,k,0])
visited=set()
steps=-1
while queue:
i,j,r,steps=queue.popleft()
if (i,j,r) not in visited:
if i-1>=0 and grid[i-1][j]!=1:
queue.append([i-1,j,r,steps+1])
if i-1>=0 and grid[i-1][j]==1 and r>0:
queue.append([i-1,j,r-1,steps+1])
if i+1<len(grid) and grid[i+1][j]!=1:
queue.append([i+1,j,r,steps+1])
if i+1<len(grid) and grid[i+1][j]==1 and r>0:
queue.append([i+1,j,r-1,steps+1])
if j-1>=0 and grid[i][j-1]!=1:
queue.append([i,j-1,r,steps+1])
if j-1>=0 and grid[i][j-1]==1 and r>0:
queue.append([i,j-1,r-1,steps+1])
if j+1<len(grid[0]) and grid[i][j+1]!=1:
queue.append([i,j+1,r,steps+1])
if j+1<len(grid[0]) and grid[i][j+1]==1 and r>0:
queue.append([i,j+1,r-1,steps+1])
if i==len(grid)-1 and j==len(grid[0])-1:
return steps
visited.add((i,j,r))
return-1 | shortest-path-in-a-grid-with-obstacles-elimination | [Python 3] Easy and clear solution. | RaghavGupta22 | 4 | 647 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,207 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/1771716/Python-Simple-BFS | class Solution:
def shortestPath(self, grid: list[list[int]], k: int) -> int:
R, C = len(grid), len(grid[0])
queue = [(0, 0, 0, 0)]
visited = {(0, 0, 0)}
for r, c, obstacleCnt, stepCnt in queue:
if r + 1 == R and c + 1 == C:
return stepCnt
for nr, nc in [(r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)]:
if 0 <= nr < R and 0 <= nc < C:
if grid[nr][nc]: # Blocked.
if (
obstacleCnt < k and
(nr, nc, obstacleCnt + 1) not in visited
):
visited.add((nr, nc, obstacleCnt + 1))
queue.append(
(nr, nc, obstacleCnt + 1, stepCnt + 1)
)
else: # Not blocked.
if (nr, nc, obstacleCnt) not in visited:
visited.add((nr, nc, obstacleCnt))
queue.append((nr, nc, obstacleCnt, stepCnt + 1))
return -1 # Not possible. | shortest-path-in-a-grid-with-obstacles-elimination | [Python] Simple BFS | eroneko | 3 | 214 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,208 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/2760734/Python-Cleanest-Crisp-Solution-or-Brain-Friedly-or-Understand-in-One-Read-or-With-IMP-comments | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
m, n = len(grid), len(grid[0])
directions = [[-1,0],[0,1],[1,0],[0,-1]]
# in vis list, we will store "number of obstacles we can still remove" further
visited = [[-1]*n for _ in range(m)]
# x, y, current steps, number of obstacles we can still remove
q = collections.deque([(0,0,0,k)])
while q:
x, y, steps, obst = q.popleft()
# Exit if current position is outside of the grid
if x<0 or y<0 or x>=m or y>=n:
continue
# Destination Found
if x==m-1 and y==n-1:
return steps
if grid[x][y]:
if obst:
obst-=1
else: # Exit if we encounter obstacle and we can not remove it
continue
# Exit currentt path, if cell was visited and in previous path it was able to remove more number of obstacles further,
# means it had more chane to reach destination
if visited[x][y]!=-1 and visited[x][y]>=obst:
continue
visited[x][y]=obst
for dx, dy in directions:
q.append((x+dx,y+dy,steps+1,obst))
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | Python Cleanest Crisp Solution | Brain Friedly | Understand in One Read | With IMP comments | dhanrajbhosale7797 | 2 | 53 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,209 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/2758876/python3-code-explained | class Solution:
def shortestPath(self, grid: list[list[int]], k: int) -> int:
m, n = len(grid), len(grid[0])
# [1] this check significantly improves runtime, i.e.,
# we can use path (0,0) -> (0,n-1) -> (m-1,n-1)
if k >= m + n - 2: return m + n - 2
# [2] we use deque to store and update a BFS state that is
# (x, y, obstacles we can destroy, steps done so far)
dq = deque([(0, 0, k, 0)])
# [3] we also keep track of visited cells
seen = set()
while dq:
i, j, k, s = dq.popleft()
# [4] successfully reached lower right corner
if (i,j) == (m-1,n-1) : return s
# [5] scan all possible directions
for ii, jj in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]:
# [6] check boundaries and obstacles
if 0 <= ii < m and 0 <= jj < n and k >= grid[ii][jj]:
# [7] make (and remember) a step
step = (ii, jj, k-grid[ii][jj], s+1)
if step[0:3] not in seen:
seen.add(step[0:3])
dq.append(step)
# [8] failed to reach lower right corner
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | python3 code explained | rupamkarmakarcr7 | 1 | 75 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,210 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/2834632/Function-based-A*-search-style | class Solution:
# manhattan distance function
def mh_distance(self, row, col) :
return (self.target_row - row) + (self.target_col - col)
# get next state singular
def get_next_state(self, new_row, new_col, current_state) :
new_eliminations = current_state[2] - self.grid[new_row][new_col]
# negative eliminations is not possible, return None, None
if new_eliminations < 0 :
return None, None
# otherwise, get new state
new_state = (new_row, new_col, new_eliminations)
# if we have seen this, don't add it
if new_state in self.seen :
return None, None
# add it
return new_eliminations, new_state
def get_next_states(self, current_row, current_col, current_state, current_steps) :
for new_row, new_col in [(current_row + 1, current_col), (current_row, current_col + 1), (current_row - 1, current_col), (current_row, current_col-1)]:
if (0 <= new_row <= self.target_row) and (0 <= new_col <= self.target_col) :
new_eliminations, new_state = self.get_next_state(new_row, new_col, current_state)
if new_eliminations is not None :
# add to seen
self.seen.add(new_state)
# get next heuristic
next_heuristic = self.mh_distance(new_row, new_col) + current_steps + 1
# add to frontier, prioritizing on next heuristic minimal first
heapq.heappush(self.frontier, (next_heuristic, current_steps+1, new_state))
def shortestPath(self, grid: List[List[int]], k: int) -> int:
# key values needed
self.rows = len(grid)
self.cols = len(grid[0])
self.target_row = self.rows - 1
self.target_col = self.cols - 1
self.grid = grid
self.max_steps = (self.rows*self.cols)
# state definition
# row, col, remaining_k
# any state with k < 0 is not viable as it means we used more brick breaks than we have
start = (0, 0, k)
# node definition
# heuristic, steps, state
# heuristic is estimation - steps
# we keep a priority queue of a min heap of our self.mh distance as the key valuation
# those closer end up being more valuable
self.frontier = [(self.mh_distance(start[0], start[1]), 0, start)]
# keep a seen set from the start
self.seen = set([start])
# while you have a priority queue
while self.frontier :
# get the current estimation, the current steps and the current state
estimation, steps, state = heapq.heappop(self.frontier)
# heuristic check (never need more steps than the whole grid)
# this helps ensure optimality
if steps > self.max_steps :
break
# set heuristic to estimation minus steps
heuristic = estimation - steps
# if heuristic is less than remaining k or equal to remaining k return estimation
if heuristic <= state[2] :
return estimation
# get the current row and col to use in the function
row = state[0]
col = state[1]
# get next possible states based on your current state and steps
self.get_next_states(row, col, state, steps)
# return -1 on failure
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | Function based A* search style | laichbr | 0 | 1 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,211 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/2761165/Easy-to-Understand-BFS-Solution | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
rows, columns = len(grid), len(grid[0])
seen = set()
steps = 0
q = deque([(0, 0, k)])
while q:
length = len(q)
for i in range(length):
x, y, r = q.popleft()
if (x, y, r) in seen or r < 0:
continue
//base condition
if (x, y) == (rows - 1, columns - 1):
return steps
seen.add((x, y, r))
if grid[x][y] == 1:
r -= 1
//get all neighbouring coordinates
for dx, dy in [(0, 1), (1, 0), (-1, 0), (0, -1)]:
nx, ny = x + dx, y + dy
if 0 <= nx < rows and 0 <= ny < columns:
q.append((nx, ny, r))
steps += 1
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | Easy to Understand, BFS Solution | user6770yv | 0 | 18 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,212 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/2761159/Python!-As-short-as-it-gets! | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
n , m = len(grid), len(grid[0])
k = min(k, n + m + 1)
adj, dp, mark = defaultdict(list), defaultdict(lambda: n * m + 1), defaultdict(bool)
for z in range(k+1):
for x in range(n):
for y in range(m):
adj[z, x, y].append((z + grid[x][y], x + 1, y))
adj[z, x, y].append((z + grid[x][y], x - 1, y))
adj[z, x, y].append((z + grid[x][y], x, y - 1))
adj[z, x, y].append((z + grid[x][y], x, y + 1))
q = deque();
q.append((0, 0, 0))
mark[(0, 0, 0)], dp[(0, 0, 0)] = True, 0
while q:
u = q.popleft()
for v in adj[u]:
if mark[v] != True:
dp[v] = dp[u] + 1
mark[v] = True
q.append(v)
ans = min(dp[i, n-1, m-1] for i in range(k+1))
return ans if ans != n * m + 1 else -1 | shortest-path-in-a-grid-with-obstacles-elimination | 😎Python! As short as it gets! | aminjun | 0 | 13 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,213 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/2760996/Python-solution-using-BFS-and-Memoisation.-Breadth-First-Search | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
m, n = len(grid), len(grid[0])
flag = [[[0]*n for i in range(m)]for j in range(k+1)]
steps = 0
q = [[0,0,k]]
di = [[0,1], [1,0], [-1,0], [0,-1]]
while q:
size = len(q)
while size > 0:
cur = q.pop(0)
if cur[0] == m-1 and cur[1] == n-1:
return steps
for i,j in di:
newi = cur[0] + i
newj = cur[1] + j
obs = cur[2]
#print(newi, newj, obs)
if newi >= 0 and newi < m and newj<n and newj>=0:
if grid[newi][newj] == 0 and not flag[obs][newi][newj]:
flag[obs][newi][newj] = 1
q.append([newi, newj, obs])
elif grid[newi][newj] == 1 and obs>0 and not flag[obs-1][newi][newj]:
flag[obs-1][newi][newj] = 1
q.append([newi, newj, obs-1])
size -= 1
steps += 1
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | Python solution using BFS and Memoisation. [Breadth First Search] | abhishekgoel1999 | 0 | 9 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,214 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/2760671/Python3-Solution-with-using-bfs | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
if len(grid) == 1 and len(grid[0]) == 1:
return 0
if k > (len(grid) - 1 + len(grid[0]) - 1):
return len(grid) + len(grid[0]) - 2
"""
begin_state:
begin_x_pos
begin_y_pos
cur_eliminates
cur_steps
"""
begin_state = (0,0,k,0)
q = collections.deque([begin_state])
visited = set([(0, 0, k)])
while q:
x, y, e, s = q.popleft()
for new_x, new_y in [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]:
if new_x < 0 or new_x >= len(grid) or new_y < 0 or new_y >= len(grid[0]):
continue
new_e = e - grid[new_x][new_y]
if new_e >= 0 and (new_x, new_y, new_e) not in visited:
if new_x == len(grid) - 1 and new_y == len(grid[0]) - 1:
return s + 1
visited.add((new_x, new_y, new_e))
q.append((new_x, new_y, new_e, s + 1))
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | [Python3] Solution with using bfs | maosipov11 | 0 | 6 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,215 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/2760467/Python-or-BFS-solution | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
rows, cols = len(grid), len(grid[0])
q = deque()
# r, c, pathLength, remaining_k
q.append((0, 0, 0, k))
seen = set()
while q:
r, c, pathLength, kRemain = q.popleft()
if (r, c, kRemain) in seen or kRemain < 0:
continue
if r == (rows - 1) and c == (cols - 1):
return pathLength
seen.add((r, c, kRemain))
if grid[r][c] == 1:
kRemain -= 1
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
for dr, dc in directions:
nr, nc = r + dr, c + dc
if nr in range(rows) and nc in range(cols):
q.append((nr, nc, pathLength + 1, kRemain))
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | Python | BFS solution | KevinJM17 | 0 | 9 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,216 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/2760023/Help-BFS-TLE-what's-wrong-and-where-to-improve | class Solution:
def shortestPath(self, grid: List[List[int]], K: int) -> int:
def inbound(r, c):
if r<0 or c<0 or r>=len(grid) or c>=len(grid[0]): return False
return True
q = collections.deque([(0, 0, K)])
seen = set()
path = 0
while len(q)>0:
for i in range(len(q)):
(r, c, k) = q.popleft()
if r==len(grid)-1 and c==len(grid[0])-1:
return path
seen.add((r, c, k))
for rr, cc in [(r+1, c), (r, c+1), (r-1, c), (r, c-1)]:
if inbound(rr, cc):
kk = k-grid[rr][cc]
if kk >= 0 and (rr, cc, kk) not in seen:
q.append((rr, cc, kk))
path += 1
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | [Help] BFS TLE, what's wrong and where to improve ? | dyxuki | 0 | 8 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,217 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/2759836/Python-BFS-Check-if-the-visited-cell-has-moreless-remaining_k-count | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
dirs = [(0,1), (1,0), (0,-1), (-1,0)]
m, n = len(grid), len(grid[0])
def inbound(x, y):
return 0 <= x < m and 0 <= y < n
# row, col, remaining_k, steps
q = collections.deque( [(0, 0, k, 0)] )
# initialize to -1, cause remaining_k will never go below 0.
# so it'll always be less than remaining_k in the beginning
visited = [[-1 for _ in range(n)] for _ in range(m)]
while q:
x, y, rem_k, steps = q.popleft()
if (x, y) == (m-1, n-1):
return steps
# check if we've already visited this tile and if we had more/less rem_k
# if we have more rem_k now, then proceed.
# otherwise, continue to next q item
if rem_k <= visited[x][y]: continue
visited[x][y] = rem_k
for dx, dy in dirs:
nx, ny = x+dx, y+dy
if not inbound(nx, ny): continue
if grid[nx][ny] == 1 and rem_k > 0:
q.append((nx, ny, rem_k-1, steps+1))
elif grid[nx][ny] == 0:
q.append((nx, ny, rem_k, steps+1))
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | [Python] BFS - Check if the visited cell has more/less `remaining_k` count | Paranoidx | 0 | 16 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,218 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/2759377/Python-solution-with-explaination | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
m, n = len(grid), len(grid[0])
# [1] this check significantly improves runtime, i.e.,
# we can use path (0,0) -> (0,n-1) -> (m-1,n-1)
if k >= m + n - 2: return m + n - 2
# [2] we use deque to store and update a BFS state that is
# (x, y, obstacles we can destroy, steps done so far)
dq = deque([(0, 0, k, 0)])
# [3] we also keep track of visited cells
seen = set()
while dq:
i, j, k, s = dq.popleft()
# [4] successfully reached lower right corner
if (i,j) == (m-1,n-1) : return s
# [5] scan all possible directions
for ii, jj in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]:
# [6] check boundaries and obstacles
if 0 <= ii < m and 0 <= jj < n and k >= grid[ii][jj]:
# [7] make (and remember) a step
step = (ii, jj, k-grid[ii][jj], s+1)
if step[0:3] not in seen:
seen.add(step[0:3])
dq.append(step)
# [8] failed to reach lower right corner
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | Python solution with explaination | avs-abhishek123 | 0 | 14 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,219 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/2758829/python3-bfs | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
m, n = len(grid), len(grid[0])
if m == 1 and n ==1: return 0
queue = [(0,0,0)]
step = 1
visited = {(0,0):0}
while queue:
length = len(queue)
new_queue = []
for y,x,count in queue:
for dy, dx in [(-1,0),(1,0),(0,-1),(0,1)]:
tmp = count
if 0<=x+dx<n and 0<=y+dy<m and ((y+dy,x+dx) not in visited or visited[(y+dy,x+dx)] > tmp):
if grid[y+dy][x+dx] == 1: tmp += 1
if tmp > k: continue
if ((y+dy,x+dx,tmp)) not in new_queue: new_queue.append((y+dy,x+dx,tmp))
if (y+dy,x+dx) not in visited: visited[(y+dy,x+dx)] = 0
visited[(y+dy,x+dx)] = tmp
if (y+dy) == (m-1) and (x+dx) == (n-1): return step
queue = new_queue
step += 1
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | python3, bfs | pjy953 | 0 | 10 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,220 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/2758812/Python-BFS | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
m, n = len(grid), len(grid[0])
if m == 1 and n == 1:
return 0
pos = [(1, 0), (-1, 0), (0, 1), (0, -1)]
maxK = [[-1 for _ in range(n)] for _ in range(m)]
queue = [(0, 0, k, 0)]
maxK[0][0] = k
while len(queue) != 0:
(r, c, kp, d) = queue.pop(0)
for (p0, p1) in pos:
r0, c1 = r + p0, c + p1
if (0 <= r0 < m) and (0 <= c1 < n):
newK = kp - grid[r0][c1]
if newK > maxK[r0][c1]:
if (r0 == m - 1) and (c1 == n - 1):
return d + 1
queue.append((r0, c1, newK, d + 1))
maxK[r0][c1] = newK
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | [Python] BFS | mingyang-tu | 0 | 12 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,221 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/2758697/Python3-or-Dijkstra | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
heap = [(0, 0, 0, 0)]
seen = set()
n, m = len(grid), len(grid[0])
def checkInBound(x, y):
return 0 <= x < n and 0 <= y < m
while heap:
d, kt, i, j = heapq.heappop(heap)
if kt > k or (kt, i, j) in seen:
continue
if i == n-1 and j == m-1:
return d
seen.add((kt, i, j))
for di, dj in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
xi, xj = i + di, j + dj
if checkInBound(xi, xj):
heapq.heappush(heap, (d + 1, kt + grid[i][j], xi, xj))
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | Python3 | Dijkstra | vikinam97 | 0 | 17 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,222 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/2758649/BFS-Python-Solution | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
m = len(grid)
n = len(grid[0])
queue = deque()
seen = set()
queue.append(((0, 0), 0))
seen.add((0, 0, 0))
moves = [(0, 1), (0, -1), (-1, 0), (1, 0)]
steps = 0
target = (m - 1, n - 1)
while queue:
count = len(queue)
for _ in range(count):
cell, obstacles = queue.popleft()
if cell == target:
return steps
for move in moves:
x = cell[0] + move[0]
y = cell[1] + move[1]
if x < 0 or x >= m:
continue
if y < 0 or y >= n:
continue
if (x, y, obstacles) in seen:
continue
if grid[x][y] == 1 and obstacles == k:
continue
queue.append(((x, y), obstacles + grid[x][y]))
seen.add((x, y, obstacles))
steps += 1
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | BFS Python Solution | mansoorafzal | 0 | 12 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,223 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/2758351/Python3-BFS-but-using-heap | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
mx, nx = len(grid), len(grid[0])
h = [(0, 0, 0, 0)]
visited = set()
while h:
s, n, i, j = heappop(h)
if i<0 or i>=mx or j<0 or j>=nx or (i, j, n) in visited:
continue
n += grid[i][j]
if n > k:
continue
visited.add((i,j, n+1))
visited.add((i,j, n))
if i == mx-1 and j==nx-1:
return s
heappush(h, (s + 1, n, i+1, j))
heappush(h, (s + 1, n, i-1, j))
heappush(h, (s + 1, n, i, j+1))
heappush(h, (s + 1, n, i, j-1))
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | Python3 BFS, but using heap | godshiva | 0 | 15 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,224 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/2603134/Python-BFS-Simple-ans-Easy | class Solution:
# Simple BFS Solution in Python
def shortestPath(self, grid: List[List[int]], k: int) -> int:
m, n = len(grid), len(grid[0])
directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
state = (0, 0, k)
queue = deque([(0, state)])
seen = set([state])
while queue:
steps, (ri, cj, kk) = queue.popleft()
if (ri, cj) == (m - 1, n - 1): return steps # Reaching the end the first time within k steps will be the shortest path
for i, j in directions:
nr, nc = ri + i, cj + j
if 0 <= nr < m and 0 <= nc < n: #isValid
new_state = (nr, nc, kk - grid[nr][nc])
if new_state[2] >= 0 and new_state not in seen: # Valid new step can be added to queue for BFS traversal
seen.add(new_state)
queue.append((steps + 1, new_state))
return -1 # All paths exhausted none can reach target within k steps | shortest-path-in-a-grid-with-obstacles-elimination | Python BFS Simple ans Easy | shiv-codes | 0 | 111 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,225 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/2536537/Python-or-BFS | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
def bfs(grid, k):
q = collections.deque()
q.append((0, 0, k, 0))
visited = set()
ROWS = len(grid)
COLS = len(grid[0])
if ROWS == 1 and COLS == 1:
return 0
visited.add((0, 0, k))
while q:
r, c, k, pathLen = q.popleft()
for row, col in [r+1, c], [r-1, c], [r, c+1], [r, c-1]:
if 0 <= row < ROWS and 0 <= col < COLS and (row, col, k) not in visited and (k > 0 or grid[row][col] == 0):
visited.add((row, col, k))
if row == ROWS - 1 and col == COLS - 1:
return pathLen+1
if grid[row][col] == 1:
q.append((row, col, k-1, pathLen+1))
else:
q.append((row, col, k, pathLen+1))
return -1
return bfs(grid, k) | shortest-path-in-a-grid-with-obstacles-elimination | Python | BFS | Mark5013 | 0 | 173 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,226 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/2340692/Python-BFS-solution | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
moves = [[-1, 0], [1, 0], [0, -1], [0, 1]]
M, N = len(grid), len(grid[0])
if M == 1 and N == 1:
return 0
q = deque()
q.append((0, 0, 0))
visited = set()
visited.add((0, 0, 0))
total_steps = 0
while q:
q_size = len(q)
for _ in range(q_size):
x, y, obstackles_elimionated = q.popleft()
if x == M-1 and y == N-1:
return total_steps
for mx, my in moves:
nx = x + mx
ny = y + my
if 0<=nx<M and 0<=ny<N:
if grid[nx][ny] == 1 and (nx, ny, obstackles_elimionated+1) not in visited:
if obstackles_elimionated + 1 <= k:
visited.add((nx, ny, obstackles_elimionated+1))
q.append((nx, ny, obstackles_elimionated + 1))
elif grid[nx][ny] == 0 and (nx, ny, obstackles_elimionated) not in visited:
visited.add((nx, ny, obstackles_elimionated))
q.append((nx, ny, obstackles_elimionated))
total_steps += 1
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | Python BFS solution | pivovar3al | 0 | 115 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,227 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/1922331/Python-easy-to-read-and-understand-or-BFS | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
m, n = len(grid), len(grid[0])
visit = set()
visit.add((0, 0, 0))
q = [[0, 0, 0, 0]]
while q:
x, y, obstacle, path = q.pop(0)
if x == m-1 and y == n-1:
return path
if x > 0:
if grid[x-1][y] == 1 and obstacle < k and (x-1, y, obstacle+1) not in visit:
visit.add((x-1, y, obstacle+1))
q.append([x-1, y, obstacle+1, path+1])
elif grid[x-1][y] == 0 and (x-1, y, obstacle) not in visit:
visit.add((x-1, y, obstacle))
q.append([x-1, y, obstacle, path+1])
if y > 0:
if grid[x][y-1] == 1 and obstacle < k and (x, y-1, obstacle+1) not in visit:
visit.add((x, y-1, obstacle+1))
q.append([x, y-1, obstacle+1, path+1])
elif grid[x][y-1] == 0 and (x, y-1, obstacle) not in visit:
visit.add((x, y-1, obstacle))
q.append([x, y-1, obstacle, path+1])
if x < m-1:
if grid[x+1][y] == 1 and obstacle < k and (x+1, y, obstacle+1) not in visit:
visit.add((x+1, y, obstacle+1))
q.append([x+1, y, obstacle+1, path+1])
elif grid[x+1][y] == 0 and (x+1, y, obstacle) not in visit:
visit.add((x+1, y, obstacle))
q.append([x+1, y, obstacle, path+1])
if y < n-1:
if grid[x][y+1] == 1 and obstacle < k and (x, y+1, obstacle+1) not in visit:
visit.add((x, y+1, obstacle+1))
q.append([x, y+1, obstacle+1, path+1])
elif grid[x][y+1] == 0 and (x, y+1, obstacle) not in visit:
visit.add((x, y+1, obstacle))
q.append([x, y+1, obstacle, path+1])
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | Python easy to read and understand | BFS | sanial2001 | 0 | 100 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,228 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/1911319/Python-BFS-and-A*-Search-with-explanation-or-Beats-95 | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
m, n = len(grid), len(grid[0])
# find neighbours of node
def neighbour(node):
i,j = node
moves = ((1,0),(0,1),(-1,0),(0,-1)) # up, down, left, or right
return [ (i+di,j+dj) for di,dj in moves if -1<i+di<m and -1<j+dj<n ]
# dfs
nodes = deque( [ [ (0,0), 0 ] ] ) # last node and obst eliminated so far
visited = dict() # holds visited node and min obst eliminated to reach
ret = -1 # current distance traveled
while nodes:
len_ = len(nodes)
ret +=1
for _ in range(len_):
node, obst = nodes.pop()
# cont if more than k obstacle eliminated or node is visited with less obst eliminated
if obst > k or (node in visited and obst >= visited[node]):
continue
# return if lowest right corner
if node == (m-1,n-1):
return ret
# update min obst eliminated to reach
visited[node] = obst
# if we can eliminated obstacle on path where we only go down and right
# and have not reroute yet due to constraint
if sum(node) == ret and k-obst >= m+n-3 - ret:
return m+n-2
# add new possible routes with obstacle eliminated
for nxt_i,nxt_j in neighbour(node):
nxt_node = (nxt_i,nxt_j)
if grid[nxt_i][nxt_j]:
nodes.appendleft([ nxt_node, obst+1 ])
else:
nodes.appendleft([ nxt_node, obst ])
# not possible to find such walk
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | [Python] BFS and A* Search with explanation | Beats 95% | haydarevren | 0 | 110 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,229 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/1911319/Python-BFS-and-A*-Search-with-explanation-or-Beats-95 | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
m, n = len(grid), len(grid[0])
# find neighbours of node
def neighbour(node):
i,j = node
moves = ((1,0),(0,1),(-1,0),(0,-1)) # up, down, left, or right
return [ (i+di,j+dj) for di,dj in moves if -1<i+di<m and -1<j+dj<n ]
def priority(i,j,d):
return m-i+n-j+d
# priority, distance, obst eliminated, node
hq = [ ( priority(0,0,0), 0, 0, (0,0) ) ]
visited = dict() # holds visited node and min obst eliminated to reach
while hq:
p, d, obst, node = heapq.heappop(hq)
# cont if more than k obstacle eliminated or node is visited with less obst eliminated
if obst > k or (node in visited and obst >= visited[node]):
continue
# return if lowest right corner
if node == (m-1,n-1):
return d
# update min obst eliminated to reach
visited[node] = obst
# if we can eliminated obstacle on path where we only go down and right
# and have not reroute yet due to constraint
if sum(node) == d and k-obst >= m+n-3 - d:
return m+n-2
for nxt_i,nxt_j in neighbour(node):
nxt_node = (nxt_i,nxt_j)
if grid[nxt_i][nxt_j]:
heapq.heappush(hq, ( priority(*nxt_node,d), d+1, obst+1, nxt_node ) )
else:
heapq.heappush(hq, ( priority(*nxt_node,d), d+1, obst, nxt_node ) )
# not possible to find such walk
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | [Python] BFS and A* Search with explanation | Beats 95% | haydarevren | 0 | 110 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,230 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/1719750/Python-BFS-easy-to-follow-solution | class Solution:
def findAdjacentPositions(self, i, j, distance, k, grid, seen):
adjacentPositions = []
if i > 0 :
adjacentPositions.append((i-1, j, k, distance + 1))
if i < len(grid)-1:
adjacentPositions.append((i+1, j, k, distance + 1))
if j > 0:
adjacentPositions.append((i, j-1, k, distance + 1))
if j < len(grid[0])-1:
adjacentPositions.append((i, j+1, k, distance + 1))
return adjacentPositions
def bfs(self, grid, k, seen):
output = float("inf")
endrow, endcol = len(grid) - 1, len(grid[0]) - 1
queue = []
starting = (0, 0, k, 0)
queue.append(starting)
while (len(queue) > 0):
row, col, remainingElimination, distance = queue.pop(0)
if (remainingElimination <= seen[row][col]):
continue
seen[row][col] = remainingElimination
if ((row == endrow and col == endcol)):
return distance
if (grid[row][col] == 1):
if remainingElimination == 0:
continue
else:
remainingElimination -= 1
adjacentPositions = self.findAdjacentPositions(row, col, distance, remainingElimination, grid, seen)
for pos in adjacentPositions:
queue.append(pos)
return output
def shortestPath(self, grid: List[List[int]], k: int) -> int:
seen = [[-1]*len(grid[0]) for _ in range(len(grid))]
shortestPathDist = self.bfs(grid, k, seen)
if shortestPathDist == float("inf"):
return -1
else:
return shortestPathDist | shortest-path-in-a-grid-with-obstacles-elimination | Python BFS easy to follow solution | user7857pf | 0 | 237 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,231 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/1424448/Python%3A-BFS | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
M,N=len(grid),len(grid[0])
steps=0
q,seen=[(0,0,0)],set()
while q:
for _ in range(len(q)):
r,c,used=q.pop(0)
if (r,c)==(M-1,N-1):
return steps
for x,y in [(r-1,c),(r,c-1),(r,c+1),(r+1,c)]:
if 0<=x<M and 0<=y<N and (x,y,used) not in seen:
if grid[x][y]==0:
q.append((x,y,used))
seen.add((x,y,used))
elif grid[x][y]==1 and used<k:
seen.add((x,y,used))
q.append((x,y,used+1))
steps+=1
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | Python: BFS | SeraphNiu | 0 | 115 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,232 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/453721/Python3-breadth-first-search | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
m, n = len(grid), len(grid[0]) #dimension
if k >= m+n-2: return m+n-2 #key for speed 668ms -> 52ms
level = 0
queue = [(0, 0, 0)]
visited = set(queue)
#bfs at most k obstacles
while queue:
temp = []
for i, j, z in queue:
if i == m-1 and j == n-1: return level #arriving at right corner
for ii, jj in ((i,j+1), (i,j-1), (i-1,j), (i+1,j)):
if 0 <= ii < m and 0 <= jj < n:
kk = z + grid[ii][jj] #update obstacles
if kk <= k and (ii, jj, kk) not in visited: #at most k obstacles
temp.append((ii, jj, kk))
visited.add((ii, jj, kk))
level += 1
queue = temp
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | [Python3] breadth-first search | ye15 | 0 | 100 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,233 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/1485320/Python3-BFS-%2B-Note-on-DFS | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
visited, m, n = set(), len(grid), len(grid[0])
@cache
def dfs(i, j, k):
key = (i, j)
if (k < 0 or i >= m or i < 0 or j >= n or j < 0 or key in visited):
return math.inf
if (i == m - 1 and j == n - 1):
return 0
k -= grid[i][j]
visited.add(key)
minSteps = min(dfs(i + 1, j, k), dfs(i - 1, j, k), dfs(i, j + 1, k), dfs(i, j - 1 , k))
visited.remove(key)
return 1 + minSteps
ans = dfs(0, 0, k)
return -1 if ans == math.inf else ans | shortest-path-in-a-grid-with-obstacles-elimination | Python3 - BFS + Note on DFS ✅ | Bruception | -1 | 310 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,234 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/1485320/Python3-BFS-%2B-Note-on-DFS | class Solution:
def shortestPath(self, grid: List[List[int]], k: int) -> int:
m, n, steps = len(grid), len(grid[0]), 0
seen, queue, dirs = set([(0, 0, k)]), deque([(0, 0, k)]), [(1, 0), (-1, 0), (0, 1), (0, -1)]
while (queue):
for _ in range(len(queue)):
i, j, k = queue.popleft()
if (i == m - 1 and j == n - 1):
return steps
for di, dj in dirs:
di, dj = di + i, dj + j
if (di >= m or di < 0 or dj >= n or dj < 0):
continue
dk = k - grid[di][dj]
child = (di, dj, dk)
if (dk >= 0 and child not in seen):
seen.add(child)
queue.append(child)
steps += 1
return -1 | shortest-path-in-a-grid-with-obstacles-elimination | Python3 - BFS + Note on DFS ✅ | Bruception | -1 | 310 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,235 |
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/452144/Python-3-(beats-100)-(40-ms)-(eleven-lines)-(BFS) | class Solution:
def shortestPath(self, G: List[List[int]], k: int) -> int:
M, N, P, Q, D, L = len(G)-1, len(G[0])-1, [(0,0,0)], [], {}, 0
if k >= M+N: return M+N
while P:
for (x,y,s) in P:
if (x,y) == (M,N): return L
for i,j in (x-1,y),(x,y+1),(x+1,y),(x,y-1):
if 0<=i<=M and 0<=j<=N:
t = s + G[i][j]
if t <= k and D.get((i,j),math.inf) > t: D[(i,j)], _ = t, Q.append((i,j,t))
P, Q, L = Q, [], L + 1
return -1
- Junaid Mansuri
- Chicago, IL | shortest-path-in-a-grid-with-obstacles-elimination | Python 3 (beats 100%) (40 ms) (eleven lines) (BFS) | junaidmansuri | -4 | 503 | shortest path in a grid with obstacles elimination | 1,293 | 0.456 | Hard | 19,236 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/468107/Python-3-lightning-fast-one-line-solution | class Solution:
def findNumbers(self, nums: List[int]) -> int:
return len([x for x in nums if len(str(x)) % 2 == 0]) | find-numbers-with-even-number-of-digits | Python 3 lightning fast one line solution | denisrasulev | 31 | 7,300 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,237 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/616315/Several-python-sol-sharing-w-Reference | class Solution:
def findNumbers(self, nums: List[int]) -> int:
counter = 0
for number in nums:
if len( str(number) ) % 2 == 0:
counter += 1
return counter | find-numbers-with-even-number-of-digits | Several python sol sharing [w/ Reference] | brianchiang_tw | 8 | 719 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,238 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/616315/Several-python-sol-sharing-w-Reference | class Solution:
def findNumbers(self, nums: List[int]) -> int:
# output by generator expression
return sum( (1 for number in nums if len(str(number))%2 == 0), 0 ) | find-numbers-with-even-number-of-digits | Several python sol sharing [w/ Reference] | brianchiang_tw | 8 | 719 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,239 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/616315/Several-python-sol-sharing-w-Reference | class Solution:
def findNumbers(self, nums: List[int]) -> int:
even_digit_width = lambda number: ( len( str(number) ) % 2 == 0 )
return sum( map(even_digit_width, nums) , 0 ) | find-numbers-with-even-number-of-digits | Several python sol sharing [w/ Reference] | brianchiang_tw | 8 | 719 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,240 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/457649/Python-3-(one-line)-(beats-100) | class Solution:
def findNumbers(self, N: List[int]) -> int:
return sum(len(str(n)) % 2 == 0 for n in N)
- Junaid Mansuri
- Chicago, IL | find-numbers-with-even-number-of-digits | Python 3 (one line) (beats 100%) | junaidmansuri | 3 | 790 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,241 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/1067611/Python-simple-solution(Faster-than-91.41-and-very-EASY-to-understand) | class Solution:
def findNumbers(self, nums: List[int]) -> int:
count = 0
for i in nums:
i = str(i)
if len(i) % 2 == 0:
count += 1
return count
``` | find-numbers-with-even-number-of-digits | Python simple solution(Faster than 91.41% and very EASY to understand) | Sissi0409 | 2 | 271 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,242 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2773355/1-Liner-using-map | class Solution:
def findNumbers(self, nums: List[int]) -> int:
return sum(not n&1 for n in map(len, map(str, nums))) | find-numbers-with-even-number-of-digits | 1 Liner using map | Mencibi | 1 | 50 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,243 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2514057/Simple-python-sol | class Solution:
def findNumbers(self, nums: List[int]) -> int:
count = 0
for num in nums:
if len(str(num)) % 2 == 0:
count += 1
return count | find-numbers-with-even-number-of-digits | Simple python sol | aruj900 | 1 | 50 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,244 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2086379/Python3-brute-force-to-optimal-solution | class Solution:
def findNumbers(self, nums: List[int]) -> int:
# return self.solOne(nums)
# return self.solTwo(nums)
return self.solThree(nums)
# O(N) || O(1) 105ms 12.77%
# brute force
def solOne(self, numArray):
if not numArray:
return 0
counter = 0
for x in numArray:
counter += 1 if len(str(x)) % 2 == 0 else 0
return counter
# O(n) || O(1) 80ms 38.54%
# optimal solution
def solTwo(self, numArray):
if not numArray:
return 0
counter = 0
for num in numArray:
counter += 1 if (int(log10(num) + 1)) % 2 == 0 else 0
return counter
# O(n) || O(1) should it be O(n^2) ?
# 93ms 22.69%
def solThree(self, numArray):
if not numArray:
return 0
counter = 0
for num in numArray:
if self.helper(num):
counter += 1
return counter
def helper(self, num):
count = 0
while num > 0:
num //= 10
count += 1
return count % 2 == 0 | find-numbers-with-even-number-of-digits | Python3 brute force to optimal solution | arshergon | 1 | 74 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,245 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/1587238/Python3-or-Check-number-length-as-a-string | class Solution:
def findNumbers(self, nums: List[int]) -> int:
evenCount = 0
for num in nums:
if len(str(num)) % 2 == 0:
evenCount += 1
return evenCount | find-numbers-with-even-number-of-digits | Python3 | Check number length as a string | JM_Pranav | 1 | 77 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,246 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/1450724/Python-One-Liner | class Solution:
def findNumbers(self, nums: List[int]) -> int:
return [len(str(num)) % 2 for num in nums ].count(0) | find-numbers-with-even-number-of-digits | Python One Liner | vatsea | 1 | 111 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,247 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/1105917/Python3-simple-one-liner-faster-than-95 | class Solution:
def findNumbers(self, nums: List[int]) -> int:
return([len(str(i))%2 for i in nums].count(0)) | find-numbers-with-even-number-of-digits | Python3 simple one liner faster than 95% | suhasmr2911 | 1 | 188 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,248 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/942874/Easy-Python-Solution | class Solution:
def findNumbers(self, nums: List[int]) -> int:
return sum(len(str(i))%2==0 for i in nums) | find-numbers-with-even-number-of-digits | Easy Python Solution | lokeshsenthilkumar | 1 | 261 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,249 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/781518/Python-1-liner | class Solution:
def findNumbers(self, nums: List[int]) -> int:
return sum([len(str(i))%2==0 for i in nums]) | find-numbers-with-even-number-of-digits | Python 1-liner | lokeshsenthilkumar | 1 | 200 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,250 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/749193/Python-solution-WITHOUT-using-str()-and-len() | class Solution:
def findNumbers(self, nums: List[int]) -> int:
total_count = 0
for i in nums:
count = 0
while i > 0:
i = i // 10
count += 1
if count % 2 == 0:
total_count += 1
return total_count | find-numbers-with-even-number-of-digits | Python solution WITHOUT using str() and len() | CzechAssassin | 1 | 121 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,251 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/693880/PythonC-Find-Numbers-with-Even-Number-of-Digits | class Solution:
def findNumbers(self, nums: List[int]) -> int:
count = 0
for i in nums:
if len(str(i))%2 == 0:
count += 1
return count | find-numbers-with-even-number-of-digits | [Python/C] Find Numbers with Even Number of Digits | abhijeetmallick29 | 1 | 173 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,252 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/683309/Python-Very-Easy-One-Liner. | class Solution:
def findNumbers(self, nums: List[int]) -> int:
return len([x for x in nums if len(str(x)) % 2 == 0]) | find-numbers-with-even-number-of-digits | Python, Very Easy One-Liner. | Cavalier_Poet | 1 | 143 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,253 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/669185/Python3-easy-one-line-solution | class Solution:
def findNumbers(self, nums: List[int]) -> int:
return [len(str(num))%2==0 for num in nums].count(True) | find-numbers-with-even-number-of-digits | Python3 easy one line solution | aj_to_rescue | 1 | 81 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,254 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/589748/Python3-one-line-solution | class Solution:
def findNumbers(self, nums: List[int]) -> int:
return len(list(filter(lambda x: len(str(x))%2==0, nums))) | find-numbers-with-even-number-of-digits | Python3 one line solution | 2736618 | 1 | 236 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,255 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/545439/easy-python-3-solution | class Solution:
def findNumbers(self, nums: List[int]) -> int:
if len(nums)<1 and len(nums)>500:
return 0
count1=0 # to count number of even digits
for i in range(0,(len(nums))):
count = 0 # to count digits in a number
while nums[i]: # loop that counts digits in a number
nums[i] = nums[i] // 10
count += 1
if count % 2 == 0:
count1+=1
return count1 | find-numbers-with-even-number-of-digits | easy python 3 solution | syednabi932 | 1 | 95 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,256 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/533943/Python3%3A-99-runtime-Time-O(n)-Space-O(1)-with-inline-analysis | class Solution:
def findNumbers(self, nums: List[int]) -> int:
# Space O(1)
output = 0
# Time O(n)
for digit in nums:
# Convert int to str then calculate length and use modulus to check if even
if len(str(digit)) % 2 == 0:
output += 1
return output
# Big O: Time: O(n) Space: O(s) | find-numbers-with-even-number-of-digits | Python3: 99% runtime, Time O(n) Space O(1) with inline analysis | dentedghost | 1 | 124 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,257 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2846973/Python-multiple-solutions | class Solution:
def findNumbers(self, nums: List[int]) -> int:
output = 0
for integers in nums:
even = 0
while integers != 0:
integers //= 10
even += 1
if even % 2 == 0:
output += 1
return output | find-numbers-with-even-number-of-digits | Python multiple solutions | yijiun | 0 | 1 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,258 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2846973/Python-multiple-solutions | class Solution:
def findNumbers(self, nums: List[int]) -> int:
output = 0
for integers in nums:
if len(str(integers)) % 2 == 0:
output += 1
return output | find-numbers-with-even-number-of-digits | Python multiple solutions | yijiun | 0 | 1 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,259 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2846973/Python-multiple-solutions | class Solution:
def findNumbers(self, nums: List[int]) -> int:
return len([integers for integers in nums if len(str(integers)) % 2 == 0]) | find-numbers-with-even-number-of-digits | Python multiple solutions | yijiun | 0 | 1 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,260 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2838572/Python-one-line-using-Filter | class Solution:
def findNumbers(self, nums: List[int]) -> int:
return len(list(filter(lambda x: len(str(x)) % 2 == 0, nums))) | find-numbers-with-even-number-of-digits | Python one line using Filter | th4tkh13m | 0 | 1 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,261 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2819040/One-Liner-Python-Solution | class Solution:
def findNumbers(self, nums: List[int]) -> int:
return len([True for num in nums if len(str(num)) % 2 == 0]) | find-numbers-with-even-number-of-digits | One-Liner Python Solution | PranavBhatt | 0 | 2 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,262 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2809948/Python-or-One-liner | class Solution:
def findNumbers(self, nums: List[int]) -> int:
return sum(1 for num in nums if len(str(num))%2 == 0) | find-numbers-with-even-number-of-digits | Python | One liner | pawangupta | 0 | 3 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,263 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2806674/Python3-solution | class Solution:
def findNumbers(self, nums: List[int]) -> int:
count = 0
for num in nums:
if (len(str(num)) % 2 == 0):
count += 1
return count | find-numbers-with-even-number-of-digits | Python3 solution | SupriyaArali | 0 | 5 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,264 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2800390/python3-brute-force | class Solution:
def findNumbers(self, nums: List[int]) -> int:
result = 0
for x in nums:
count = 0
while x != 0:
x = x//10
count += 1
#print('count',count)
if count % 2 == 0:
result += 1
#print('result',result)
return result | find-numbers-with-even-number-of-digits | python3 brute force | BhavyaBusireddy | 0 | 2 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,265 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2754812/Python3-Solution-oror-85-Faster-oror-Easy | class Solution:
def findNumbers(self, nums: List[int]) -> int:
count = 0
for i in nums:
if len(str(i)) % 2 == 0:
count += 1
return count | find-numbers-with-even-number-of-digits | Python3 Solution || 85% Faster || Easy | shashank_shashi | 0 | 2 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,266 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2739915/Python-3-Solution | class Solution:
def findNumbers(self, nums: List[int]) -> int:
arr = [len(str(x))%2 for x in nums]
return len(arr) - sum(arr) | find-numbers-with-even-number-of-digits | Python 3 Solution | mati44 | 0 | 3 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,267 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2731477/Python-solution-O(1)-space | class Solution:
def findNumbers(self, nums: List[int]) -> int:
for i in range(len(nums)):
nums[i] = len(str(nums[i])) % 2 == 0
return sum(nums) | find-numbers-with-even-number-of-digits | Python solution O(1) space | manufesto | 0 | 3 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,268 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2711771/Python3-99-Straightforward-using-strings | class Solution:
def findNumbers(self, nums: List[int]) -> int:
output = 0
for n in nums:
if len(str(n)) % 2 == 0:
output += 1
return output | find-numbers-with-even-number-of-digits | [Python3] 99% Straightforward using strings | connorthecrowe | 0 | 2 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,269 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2689783/Python-(traditional-approach) | class Solution:
def findNumbers(self, nums: List[int]) -> int:
k=0
nums=map(str,nums)
for x in nums:
if len(x)%2==0:
k=k+1
return k | find-numbers-with-even-number-of-digits | Python (traditional approach) | Leox2022 | 0 | 3 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,270 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2674718/Python-without-convert-int-to-str | class Solution:
def findNumbers(self, nums: List[int]) -> int:
count_even = 0
for num in nums:
count = 0
while(num > 0):
num //= 10
count += 1
if count % 2 == 0:
count_even += 1
return count_even | find-numbers-with-even-number-of-digits | ✔️ Python without convert int to str | QuiShimo | 0 | 16 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,271 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2673910/Python-Simple-one-Line-code | class Solution:
def findNumbers(self, nums: List[int]) -> int:
cnt=0
cnt = len([cnt for i in nums if len(str(i))%2 == 0])
return cnt | find-numbers-with-even-number-of-digits | Python Simple one Line code | shubhamshinde245 | 0 | 4 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,272 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2657812/Python-oror-Easily-Understood-oror-Faster-than-96-oror-Fast | class Solution:
def findNumbers(self, nums: List[int]) -> int:
ans = 0
for i in nums:
if len(str(i))%2==0:
ans+=1
return ans | find-numbers-with-even-number-of-digits | 🔥 Python || Easily Understood ✅ || Faster than 96% || Fast | rajukommula | 0 | 29 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,273 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2652520/O(n)-Easy-Python-single-line-solution-using-%22map%22-and-%22lambda-function%22 | class Solution:
def findNumbers(self, nums: List[int]) -> int:
return sum(map(lambda x : x%2==0, map(len, map(str, nums)))) | find-numbers-with-even-number-of-digits | O(n) Easy Python single line solution using "map" and "lambda function" | RoyaLotfi | 0 | 1 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,274 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2455245/Simple-oror-Python3-oror-Beats-97 | class Solution:
def findNumbers(self, nums: List[int]) -> int:
nums = list(map(str,nums))
res = 0
for i in nums:
if len(i) % 2 == 0:
res += 1
return res | find-numbers-with-even-number-of-digits | Simple || Python3 || Beats 97 % | irapandey | 0 | 58 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,275 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2449840/Simple-and-Easy-solution-or-Python-or-Easy-understanding | class Solution:
def findNumbers(self, nums: List[int]) -> int:
count = 0
for ele in nums:
if len(str(ele))%2 == 0:
count+=1
return count | find-numbers-with-even-number-of-digits | Simple & Easy solution | Python | Easy-understanding | PratyayMondal | 0 | 24 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,276 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2431626/Python-solution-using-math.log10() | class Solution:
def findNumbers(self, nums: List[int]) -> int:
count = 0
for i in nums:
digits_after_log = math.log10(i)
floor_log_num = math.floor(digits_after_log)
if floor_log_num > 0 and floor_log_num % 2 != 0:
count += 1
return count | find-numbers-with-even-number-of-digits | Python solution using math.log10() | samanehghafouri | 0 | 19 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,277 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2400966/Python3-Easy-One-Liner | class Solution:
def findNumbers(self, nums: List[int]) -> int:
return sum([len(str(num)) % 2 == 0 for num in nums]) | find-numbers-with-even-number-of-digits | [Python3] Easy One-Liner | ivnvalex | 0 | 33 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,278 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2361933/Python-Solution-Without-Converting-to-String | class Solution:
def hasEvenDigits(self, num) -> int:
if num < pow(10, 1):
return False
elif num < pow(10,2):
return True
elif num < pow(10,3):
return False
elif num < pow(10,4):
return True
elif num < pow(10,5):
return False
elif num < pow(10,6):
return True
else:
return False
def findNumbers(self, nums: List[int]) -> int:
total = 0
for num in nums:
if self.hasEvenDigits(num):
total += 1
return total | find-numbers-with-even-number-of-digits | Python Solution Without Converting to String | APet99 | 0 | 34 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,279 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2311339/Easy-to-understand-Python-solution | class Solution:
def findNumbers(self, nums: List[int]) -> int:
count_even = 0
for num in nums:
if len(str(num)) % 2 == 0:
count_even += 1
return count_even | find-numbers-with-even-number-of-digits | Easy to understand Python solution | Balance-Coffee | 0 | 54 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,280 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2290335/Python-One-Liner-72-ms-code | class Solution:
def findNumbers(self, nums: List[int]) -> int:
return len([x for x in nums if len(str(x))%2 == 0]) | find-numbers-with-even-number-of-digits | Python One Liner 72 ms code | Yodawgz0 | 0 | 51 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,281 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2169134/Simple-python3-solution-using-int-to-string-conversion | class Solution:
def findNumbers(self, nums: List[int]) -> int:
l = []
for i in nums:
if (len(str(i)))%2==0:
l.append(i)
return (len(l)) | find-numbers-with-even-number-of-digits | Simple python3 solution using int to string conversion | psnakhwa | 0 | 31 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,282 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2092106/PYTHON-or-Super-simple-python-solution | class Solution:
def findNumbers(self, nums: List[int]) -> int:
res = 0
for i in range(len(nums)):
if len(str(nums[i])) % 2 == 0:
res += 1
return res | find-numbers-with-even-number-of-digits | PYTHON | Super simple python solution | shreeruparel | 0 | 54 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,283 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/2028129/Pythonic-clean-solution | class Solution:
def findNumbers(self, nums: List[int]) -> int:
return len([x for x in nums if len(str(x))%2==0]) | find-numbers-with-even-number-of-digits | Pythonic clean solution | StikS32 | 0 | 59 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,284 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/1927863/easy-python-code | class Solution:
def findNumbers(self, nums: List[int]) -> int:
count = 0
for i in nums:
if len(str(i))%2 == 0:
count += 1
return count | find-numbers-with-even-number-of-digits | easy python code | dakash682 | 0 | 58 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,285 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/1918253/Python-Math-approach-%2B-String-conversion-or-Clean-and-Simple-or-One-Liner | class Solution:
def findNumbers(self, nums):
def getNumOfDigits(x): return len(str(x))
def isEven(x): return x % 2 == 0
return sum(isEven(getNumOfDigits(x)) for x in nums) | find-numbers-with-even-number-of-digits | Python - Math approach + String conversion | Clean and Simple | One-Liner | domthedeveloper | 0 | 67 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,286 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/1918253/Python-Math-approach-%2B-String-conversion-or-Clean-and-Simple-or-One-Liner | class Solution:
def findNumbers(self, nums):
return sum(len(str(x))%2==0 for x in nums) | find-numbers-with-even-number-of-digits | Python - Math approach + String conversion | Clean and Simple | One-Liner | domthedeveloper | 0 | 67 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,287 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/1918253/Python-Math-approach-%2B-String-conversion-or-Clean-and-Simple-or-One-Liner | class Solution:
def findNumbers(self, nums):
def getNumOfDigits(x): return floor(log10(x))+1
def isEven(x): return x % 2 == 0
return sum(isEven(getNumOfDigits(x)) for x in nums) | find-numbers-with-even-number-of-digits | Python - Math approach + String conversion | Clean and Simple | One-Liner | domthedeveloper | 0 | 67 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,288 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/1918253/Python-Math-approach-%2B-String-conversion-or-Clean-and-Simple-or-One-Liner | class Solution:
def findNumbers(self, nums):
return sum((floor(log10(x))+1)%2==0 for x in nums) | find-numbers-with-even-number-of-digits | Python - Math approach + String conversion | Clean and Simple | One-Liner | domthedeveloper | 0 | 67 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,289 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/1884262/Python-solution-by-converting-to-string | class Solution:
def findNumbers(self, nums: List[int]) -> int:
count = 0
for i in nums:
if len(str(i)) % 2 == 0:
count += 1
return count | find-numbers-with-even-number-of-digits | Python solution by converting to string | alishak1999 | 0 | 42 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,290 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/1852961/1-Line-Python-Solution-oror-87-Faster-oror-Memory-less-than-72 | class Solution:
def findNumbers(self, nums: List[int]) -> int:
return sum([1 for num in nums if len(str(num))%2==0]) | find-numbers-with-even-number-of-digits | 1-Line Python Solution || 87% Faster || Memory less than 72% | Taha-C | 0 | 76 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,291 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/1802187/Python3-easy-to-read-beats-97%2B | class Solution:
def findNumbers(self, nums: List[int]) -> int:
nums = list(map(str,nums))
count = 0
for num in nums:
if len(num)%2 == 0:
count += 1
return count | find-numbers-with-even-number-of-digits | Python3 easy-to-read beats 97+% | eating | 0 | 69 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,292 |
https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/1669938/Time-consuming-python-solution | class Solution(object):
def findNumbers(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#iniializing the counter
counter = 0
for i in nums:
#counting the digits in the number
count = 0
while (i > 0):
i = i//10
count = count + 1
#checking wether the count is even or odd
if count % 2 == 0:
counter +=1
return counter | find-numbers-with-even-number-of-digits | Time consuming python solution | ebrahim007 | 0 | 44 | find numbers with even number of digits | 1,295 | 0.77 | Easy | 19,293 |
https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/discuss/785364/O(N-log(N))-time-and-O(N)-space-Python3-using-Hashmap-and-lists | class Solution:
def isPossibleDivide(self, nums: List[int], k: int) -> bool:
hand = nums
W = k
if not hand and W > 0:
return False
if W > len(hand):
return False
if W == 0 or W == 1:
return True
expectation_map = {}
# self.count keep track of the numbers of cards that have been successfully counted as a straight,
# when self.count == len(hand) => All cards are part of a valid straight
self.count = 0
handLength = len(hand)
#Sort the hand.
sortedHand = sorted(hand)
"""
This method updates the expectation map in the following way:
a) If the len(l) == W
=> We've completed a straight of length W, add it towards the final count
b) if the next expected number (num+1) is already in the map
=> add the list to a queue of hands waiting to make a straight
c) if expected number (num+1) not in the map
=> Add a new expectation key with value as a new queue with this list
"""
def update_expectation_with_list(expectation_map, num, l, W):
# If we have W consecutive numbers, we're done with this set, count towards final count
if len(l) == W:
self.count += W
# we need more numbers to make this straight, add back with next expected num
else:
exp = num + 1
# Some other list is already expecting this number, add to the queue
if exp in expectation_map:
expectation_map[exp].append(l)
# New expected number, create new key and set [l] as value
else:
expectation_map[exp] = [l]
"""
Very similar to update_expectation_with_list. The difference here is we have the first card of the straight and thus we need to handle it correctly (set the value as a list of lists)
"""
def update_expectation_with_integer(expectation_map, num):
exp = num + 1
# Some other list is already expecting this number, add to the queue
if exp in expectation_map:
expectation_map[exp].append([num])
# New expected number, create new key and set [num] as value
else:
expectation_map[exp] = [[num]]
for idx,num in enumerate(sortedHand):
# A possible straight can be formed with this number
if num in expectation_map:
# there are multiple hands waiting for this number
if len(expectation_map[num]) > 1:
# pop the first hand
l = expectation_map[num].pop(0)
# add num to this hand
l.append(num)
# Update the expectation map
update_expectation_with_list(expectation_map, num, l, W)
# there's only one hand expecting this number
else:
# pop the first hand
l = expectation_map[num].pop(0)
l.append(num)
# Important : del the key! There's no other hand expecting this number
expectation_map.pop(num)
update_expectation_with_list(expectation_map, num, l, W)
# Nothing is expecting this number, add new expectation to the map
else:
update_expectation_with_integer(expectation_map, num)
return self.count == handLength | divide-array-in-sets-of-k-consecutive-numbers | O(N log(N)) time and O(N) space- Python3 using Hashmap and lists | prajwalpv | 1 | 169 | divide array in sets of k consecutive numbers | 1,296 | 0.566 | Medium | 19,294 |
https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/discuss/2837249/python-super-easy-greedy-using-hash-map | class Solution:
def isPossibleDivide(self, nums: List[int], k: int) -> bool:
if len(nums) % k != 0:
return False
count = collections.Counter(nums)
count = dict(sorted(count.items()))
print(count)
while count:
start_key = list(count.keys())[0]
count[start_key] -=1
if count[start_key] == 0:
count.pop(start_key)
for i in range(1, k):
if start_key + i not in count:
return False
count[start_key+i] -=1
if count[start_key+i] == 0:
count.pop(start_key+i)
return True | divide-array-in-sets-of-k-consecutive-numbers | python super easy greedy using hash map | harrychen1995 | 0 | 3 | divide array in sets of k consecutive numbers | 1,296 | 0.566 | Medium | 19,295 |
https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/discuss/2523049/Python-easy-to-read-and-understand-or-hashmap | class Solution:
def isPossibleDivide(self, nums: List[int], k: int) -> bool:
n = len(nums)
if n%k != 0:
return False
d = {}
for num in nums:
d[num] = d.get(num, 0) + 1
while d:
mn = min(d.keys())
for i in range(k):
if (mn+i) in d:
if d[(mn+i)] == 1:
del d[(mn+i)]
else:
d[(mn+i)] -= 1
else:
return False
return True | divide-array-in-sets-of-k-consecutive-numbers | Python easy to read and understand | hashmap | sanial2001 | 0 | 71 | divide array in sets of k consecutive numbers | 1,296 | 0.566 | Medium | 19,296 |
https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/discuss/462636/Python3-Hash-function-and-DFS-solution-with-explanation | class Solution:
def isPossibleDivide(self, nums: List[int], k: int) -> bool:
def dfs_util(num_counts, val, left):
if left == 0:
return True
if val not in num_counts:
return False
else:
num_counts[val] -= 1
if num_counts[val] == 0:
del(num_counts[val])
return dfs_util(num_counts, val+1, left-1)
if (len(nums) % k != 0):
return False
rounds = len(nums) // k
num_counts = collections.Counter(nums)
for _ in range(rounds):
start = min(num_counts.keys())
#print("start: ", start)
if not dfs_util(num_counts, start, k):
#print("failing", start, num_counts)
return False
return True | divide-array-in-sets-of-k-consecutive-numbers | Python3 Hash function and DFS solution with explanation | geekcoder1989 | 0 | 75 | divide array in sets of k consecutive numbers | 1,296 | 0.566 | Medium | 19,297 |
https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/discuss/457638/Python-3-(seven-lines) | class Solution:
def isPossibleDivide(self, N: List[int], k: int) -> bool:
L, C = len(N), collections.Counter(N)
for i in range(L//k):
m = min(C.keys())
for j in range(m,m+k):
if C[j] > 1: C[j] -= 1
else: del C[j]
return not (C or L % k)
- Junaid Mansuri
- Chicago, IL | divide-array-in-sets-of-k-consecutive-numbers | Python 3 (seven lines) | junaidmansuri | 0 | 352 | divide array in sets of k consecutive numbers | 1,296 | 0.566 | Medium | 19,298 |
https://leetcode.com/problems/maximum-number-of-occurrences-of-a-substring/discuss/1905801/python-easy-approach | class Solution:
def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:
s1 = []
count ={}
while minSize <= maxSize:
for i in range(0,len(s)):
if (i+ minSize) <=len(s) and len(set(s[i: i+ minSize])) <= maxLetters:
s1.append(s[i: i+ minSize])
minSize += 1
for i in s1:
count[i] = count[i] + 1 if i in count else 1
return max(count.values()) if count else 0 | maximum-number-of-occurrences-of-a-substring | python easy approach | hari07 | 4 | 286 | maximum number of occurrences of a substring | 1,297 | 0.52 | Medium | 19,299 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.