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/unique-paths-iii/discuss/1061049/Python-or-Backtracking-with-comments | class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
global result
result = 0
def backtrack(i, j, squares):
global result
# all the code below here is pretty much termination conditions from above bullet points...
if not (0 <= i < len(grid)): return
if not (0 <= j < len(grid[0])): return
if grid[i][j] == -1: return # ignore obstacles
if grid[i][j] == 2: # return
if squares == 0:
result += 1 # only add result if we've reached all squares
return
if grid[i][j] == 0:
squares -= 1 # one less square to touch
# backtracking code to avoid walking in circles
# ....
grid[i][j] = -1
for x, y in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]:
backtrack(x, y, squares)
grid[i][j] = 0
# Figure out how many zeros we need?
num_zeros = 0
for i in grid:
num_zeros += collections.Counter(i)[0]
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
backtrack(i, j, num_zeros)
return result | unique-paths-iii | Python | Backtracking with comments | dev-josh | 2 | 109 | unique paths iii | 980 | 0.797 | Hard | 15,900 |
https://leetcode.com/problems/unique-paths-iii/discuss/1061049/Python-or-Backtracking-with-comments | class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
global result
result = 0
def backtrack(i, j, squares):
global result
if not (0 <= i < len(grid)): return
if not (0 <= j < len(grid[0])): return
if grid[i][j] == -1: return
if grid[i][j] == 0: squares -= 1
if grid[i][j] == 2:
if squares == 0: result += 1
return
grid[i][j] = -1
for x, y in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]:
backtrack(x, y, squares)
grid[i][j] = 0
num_zeros = 0
for i in grid:
num_zeros += collections.Counter(i)[0]
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
backtrack(i, j, num_zeros)
return result | unique-paths-iii | Python | Backtracking with comments | dev-josh | 2 | 109 | unique paths iii | 980 | 0.797 | Hard | 15,901 |
https://leetcode.com/problems/unique-paths-iii/discuss/1534269/WEEB-DOES-PYTHON-BFS | class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
row, col = len(grid), len(grid[0])
queue = deque([])
numSquare = 1 # include starting point
visited = set()
for x in range(row):
for y in range(col):
if grid[x][y] == 1:
visited.add((x,y))
queue.append((x, y, visited))
if grid[x][y] == 0:
numSquare += 1
return self.bfs(queue, grid, row, col, numSquare)
def bfs(self, queue, grid, row, col ,numSquare):
result = 0
while queue:
x, y, visited = queue.popleft()
for nx, ny in [[x+1,y], [x-1,y], [x,y+1], [x,y-1]]:
if 0<=nx<row and 0<=ny<col and (nx,ny) not in visited:
if grid[nx][ny] == 0:
queue.append((nx, ny, visited | {(nx,ny)}))
if grid[nx][ny] == 2:
if len(visited) == numSquare:
result += 1
return result | unique-paths-iii | WEEB DOES PYTHON BFS | Skywalker5423 | 1 | 118 | unique paths iii | 980 | 0.797 | Hard | 15,902 |
https://leetcode.com/problems/unique-paths-iii/discuss/1195823/Python-Iterative-dfs | class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
nonObstacle = 0
for i in range(rows):
for j in range(cols):
if grid[i][j] == 1:
start = [i,j]
if grid[i][j] == 2:
end = [i,j]
if grid[i][j]==0:
nonObstacle+=1
count = 0
directions = [[0,-1],[-1,0],[1,0],[0,1]]
stack = []
nonObsCount = 0
stack.append((start, [start],nonObsCount ))
grid[start[0]][start[1]] = -1 # mark start node as visited
while stack:
[r,c], path,nonObsCount = stack.pop()
for d in directions:
ni,nj = r+d[0],c+d[1]
#traverse only for non obstacle nodes
if 0<=ni<rows and 0<=nj<cols and grid[ni][nj]!=-1:
if grid[ni][nj] == 2:
#if you've reached the end node, check if you've visited all non obstacle nodes
if nonObsCount==nonObstacle:
#print('One of the paths',path)
count += 1
continue
elif grid[ni][nj] == 1:
continue
else:
#if [ni,nj] not in path, it's not visited yet, add it to the path
if [ni,nj] not in path:
stack.append(([ni,nj],path+[[ni,nj]], nonObsCount+1))
else:
#check if [ni,nj] already in path, if so continue as its visited already
continue
return count | unique-paths-iii | Python - Iterative dfs | anusharp | 1 | 72 | unique paths iii | 980 | 0.797 | Hard | 15,903 |
https://leetcode.com/problems/unique-paths-iii/discuss/1172665/easy-python-solution-with-comments-(44ms) | class Solution:
def uniquePathsIII(self, A: List[List[int]]) -> int:
m, n = len(A), len(A[0])
start = end = p = 0
# Flatten the array for better performance
A = reduce(operator.add, A)
for key, val in enumerate(A):
if val >= 0:
p += 1 # Count the number of none obstacle square
if val == 1: start = key # get start and end index
if val == 2: end = key
l = m*n
def dfs(i, p):
if i == end and not p:
return 1
if A[i] < 0 or i == end: return 0
A[i], res= -1, 0 # place an obstacle on the square when passing by
# check every legal action
if i >= n: res += dfs(i - n, p - 1)
if i < l - n: res += dfs(i + n, p - 1)
if i % n: res += dfs(i - 1, p - 1)
if (i - n + 1) % n: res += dfs(i + 1, p - 1)
A[i] = 0 # backtrack, remove obstacle
return res
return dfs(start, p-1) | unique-paths-iii | easy python solution with comments (44ms) | TimSYQQX | 1 | 167 | unique paths iii | 980 | 0.797 | Hard | 15,904 |
https://leetcode.com/problems/unique-paths-iii/discuss/1172665/easy-python-solution-with-comments-(44ms) | class Solution:
def uniquePathsIII(self, A: List[List[int]]) -> int:
m, n = len(A) + 2, len(A[0]) + 2
start = end = p = 0
# Flatten the array for better performance
# and padd the array to avoid boundary condition
A = [-1] * n + reduce(operator.add, map(lambda x: [-1] + x + [-1], A)) + [-1] * n
l = m*n
for key, val in enumerate(A):
if val >= 0:
p += 1 # Count the number of none obstacle square
if val == 1: start = key # get start and end index
if val == 2: end = key
def dfs(i, p):
if i == end and not p: return 1
if A[i] < 0 or i == end: return 0
A[i] = -1 # block the square after passing
res = sum(dfs(i + k, p - 1) for k in [-n, n, -1, 1])
A[i] = 0 # restore the square (backtrack)
return res
return dfs(start, p-1) | unique-paths-iii | easy python solution with comments (44ms) | TimSYQQX | 1 | 167 | unique paths iii | 980 | 0.797 | Hard | 15,905 |
https://leetcode.com/problems/unique-paths-iii/discuss/462896/Python-3-(DFS)-(14-lines)-O(1)-space-(beats-~93)-(52-ms) | class Solution:
def uniquePathsIII(self, G: List[List[int]]) -> int:
M, N, t, z = len(G), len(G[0]), [0], 0
for i,j in itertools.product(range(M),range(N)):
if G[i][j] == 0: z += 1
if G[i][j] == 1: a,b = i,j
if G[i][j] == 2: e,f = i,j
G[a][b] = 0
def dfs(i,j,c):
if (i,j) == (e,f): t[0] += (c == z+1)
if G[i][j]: return
G[i][j] = -1
for x,y in (i-1,j),(i,j+1),(i+1,j),(i,j-1): 0<=x<M and 0<=y<N and dfs(x,y,c+1)
G[i][j] = 0
dfs(a,b,0)
return t[0]
- Junaid Mansuri
- Chicago, IL | unique-paths-iii | Python 3 (DFS) (14 lines) O(1) space (beats ~93%) (52 ms) | junaidmansuri | 1 | 420 | unique paths iii | 980 | 0.797 | Hard | 15,906 |
https://leetcode.com/problems/unique-paths-iii/discuss/2775551/Python-or-Easy-Solution-or-DFS-and-Backtracking | class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
start_row,start_col,end_row,end_col = 0,0,0,0
empty_cells = 0
# Traversing the grid to find the start and end index
for i in range(0,rows):
for j in range(0,cols):
if (grid[i][j] == 1):
start_row,start_col = i,j
elif (grid[i][j] == 2):
end_row,end_col = i,j
elif (grid[i][j] == 0):
empty_cells += 1
self.output = 0
visited = set()
def dfs(r,c,visited,walk):
if (r == end_row and c == end_col):
if (walk == empty_cells+1):
self.output += 1 # Path found
return
if (0<= r < rows and 0<= c < cols and grid[r][c] != -1 and (r,c) not in visited):
visited.add((r,c))
for i,j in [(0,-1),(0,1),(1,0),(-1,0)]:
dfs(r+i,c+j,visited,walk+1)
visited.remove((r,c))
dfs(start_row,start_col,visited,0)
return self.output | unique-paths-iii | [Python] | Easy Solution | DFS & Backtracking ✅ | tharunbalaji31 | 0 | 6 | unique paths iii | 980 | 0.797 | Hard | 15,907 |
https://leetcode.com/problems/unique-paths-iii/discuss/2692734/Straightforward-Python-DFS-solution. | class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
directions = [-1, 0, 1, 0, -1]
m, n = len(grid), len(grid[0])
def helper(ans, start, target, cur_count, M, visited, grid):
if start == target:
if cur_count == M:
return ans + 1
else:
return ans
x, y = start
for i in range(4):
next_x, next_y = x + directions[i], y + directions[i + 1]
if 0 <= next_x < m and 0 <= next_y < n and not visited[next_x][next_y] and grid[next_x][next_y] != -1:
visited[next_x][next_y] = True
ans = helper(ans, (next_x, next_y), target, cur_count + 1, M, visited, grid)
visited[next_x][next_y] = False
return ans
start, target = None, None
M = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
start = (i, j)
elif grid[i][j] == 2:
target = (i, j)
elif grid[i][j] == -1:
M += 1
M = m * n - M
visited = [[False for _ in range(n)] for _ in range(m)]
visited[start[0]][start[1]] = True
return helper(0, start, target, 1, M, visited, grid) | unique-paths-iii | Straightforward Python DFS solution. | yiming999 | 0 | 5 | unique paths iii | 980 | 0.797 | Hard | 15,908 |
https://leetcode.com/problems/unique-paths-iii/discuss/2558677/Intuitive-Python-DFS-Solution | class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
ROWS, COLS = len(grid), len(grid[0])
ROBOT = TARGET = ()
zeros = 0
# Locate robot and target positions and count number of zeros.
for r in range(ROWS):
for c in range(COLS):
if grid[r][c] == 0:
zeros += 1
if grid[r][c] == 1:
ROBOT = (r, c)
if grid[r][c] == 2:
TARGET = (r, c)
visited = set()
def dfs(r, c):
nb_paths = 0
# Bounds check
if r < 0 or r == ROWS or\
c < 0 or c == COLS or\
(r, c) in visited or\
grid[r][c] == -1:
return 0
if (r, c) == TARGET:
if len(visited) == zeros + 1:
return 1
return 0
visited.add((r, c))
# Move in all 4 directions
directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
for dr, dc in directions:
nb_paths += dfs(r+dr, c+dc)
visited.remove((r, c))
return nb_paths
return dfs(*ROBOT) | unique-paths-iii | Intuitive Python DFS Solution | Nibba2018 | 0 | 48 | unique paths iii | 980 | 0.797 | Hard | 15,909 |
https://leetcode.com/problems/unique-paths-iii/discuss/2318256/Python3-Clean-Iterative-DFS | class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
def dfs(start, empty):
res = 0
stack = [(start, set([start]), empty - 1)]
while stack:
(i, j), seen, empty_left = stack.pop()
res += grid[i][j] == 2 and not empty_left
for u, v in (i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1):
if 0 <= u < m and 0 <= v < n and grid[u][v] != -1 and (u, v) not in seen:
stack.append(((u, v), seen.copy() | {(u, v)}, empty_left - 1))
return res
empty = 1
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
start = (i, j)
elif grid[i][j] != -1:
empty += 1
return dfs(start, empty) | unique-paths-iii | [Python3] Clean Iterative DFS | 0xRoxas | 0 | 35 | unique paths iii | 980 | 0.797 | Hard | 15,910 |
https://leetcode.com/problems/unique-paths-iii/discuss/2309001/Recursive-Tryout-with-Simple-Stop-Condition | class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
M=len(grid) # row"
N=len(grid[0]) #col
obstacles=[]
for m in range(M):
for n in range(N):
if grid[m][n]==1:
s=(m,n)
if grid[m][n]==2:
f=(m,n)
if grid[m][n]==-1:
obstacles.append((m,n))
total_remain=M*N-1-len(obstacles)
self.paths=0
go=dict(
l=lambda loc: (loc[0],loc[1]-1),
r=lambda loc: (loc[0],loc[1]+1),
u=lambda loc: (loc[0]-1,loc[1]),
d=lambda loc: (loc[0]+1,loc[1])
)
def tryout(cur,bag_of_steps,remain):
# Check Status
if cur==f:
if remain==0:
self.paths+=1
return
# Next Move
for key,move in go.items():
if (cur[0]==0) & (key=="u"):
continue
if (cur[0]==M-1) & (key=="d"):
continue
if (cur[1]==0) & (key=="l"):
continue
if (cur[1]==N-1) & (key=="r"):
continue
nxt=move(cur)
if nxt in bag_of_steps+obstacles:
continue
_=tryout(nxt,bag_of_steps+[cur],remain-1)
_=tryout(s,[],total_remain)
return self.paths | unique-paths-iii | Recursive Tryout with Simple Stop Condition | syhaung | 0 | 10 | unique paths iii | 980 | 0.797 | Hard | 15,911 |
https://leetcode.com/problems/unique-paths-iii/discuss/2270783/Easy-Understanding-soln | class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
# 1 -> starting
# 2 -> ending
# 0 -> empty spaces ( can walk over)
# -1 -> obstacles( can't walk over)
m, n = len(grid), len(grid[0])
zeros = 0
startingX, startingY = 0, 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
startingX = i
startingY = j
if grid[i][j] == 0:
zeros += 1
return self.rec(grid, startingX, startingY, zeros)
def rec(self, grid, i, j, zeros):
m, n = len(grid), len(grid[0])
if i < 0 or j < 0 or i >= m or j >= n or grid[i][j] == -1:
return 0
if grid[i][j] == 2:
if zeros == -1:
return 1
else:
return 0
zeros -= 1
grid[i][j] = -1
totalPaths = self.rec(grid, i+1, j, zeros) + self.rec(grid, i-1, j, zeros) + self.rec(grid, i, j+1, zeros) + self.rec(grid, i, j-1, zeros)
zeros += 1
grid[i][j] = 0
return totalPaths | unique-paths-iii | Easy Understanding soln | logeshsrinivasans | 0 | 38 | unique paths iii | 980 | 0.797 | Hard | 15,912 |
https://leetcode.com/problems/unique-paths-iii/discuss/1983553/PYTHON-SOL-oror-FASTER-THAN-95-oror-BACKTRACKING-oror-WELL-EXPLAINED-oror-COMMENTED-oror | class Solution:
def backtracking(self,row,col,count):
# reach the end
if row == self.endrow and col == self.endcol:
if count == self.counts: self.ans += 1
return
# mark block as visited
self.vis[row][col] = True
# now we will try all adjacent blocks
adj = ((row+1,col),(row-1,col),(row,col-1),(row,col+1))
for x,y in adj:
if 0<=x<self.rows and 0<=y<self.cols and self.vis[x][y] == False and self.grid[x][y] != -1:
self.backtracking(x,y,count+1)
# mark block as unvisited
self.vis[row][col] = False
return
def uniquePathsIII(self, grid: List[List[int]]) -> int:
# 1 represents start
# 2 represents end
# 0 represents we can walk over
# -1 represents we cannot walk over
startrow,startcol,self.endrow,self.endcol = None,None,None,None
self.rows = len(grid)
self.cols = len(grid[0])
self.counts = 0
for i in range(self.rows):
for j in range(self.cols):
if grid[i][j] == 1:startrow,startcol = i,j
elif grid[i][j] == 2: self.endrow,self.endcol = i,j
if grid[i][j] != -1: self.counts += 1
self.grid = grid
self.ans = 0
self.vis = [[False for i in range(self.cols)] for j in range(self.rows)]
self.backtracking(startrow,startcol,1)
return self.ans | unique-paths-iii | PYTHON SOL || FASTER THAN 95% || BACKTRACKING || WELL EXPLAINED || COMMENTED || | reaper_27 | 0 | 116 | unique paths iii | 980 | 0.797 | Hard | 15,913 |
https://leetcode.com/problems/unique-paths-iii/discuss/1780324/Bitmask-python | class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
start = si = sj = 0
endgame = 0
for i in range(m):
for j in range(n):
idx = i * n + j
if grid[i][j] != -1:
endgame |= (1 << idx)
if grid[i][j] == 1:
start = 1 << idx
si, sj = i, j
count= 0
def backtracking(i, j, state):
nonlocal count
# went into the target, path terminate, increase count if met ending criteria.
if grid[i][j] == 2:
if state == endgame:
count += 1
return
for di, dj in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
ii, jj = i+ di, j + dj
if (0 <= ii < m and 0 <= jj < n) and ((1 << (ii * n + jj)) & state ==0) and grid[ii][jj] != -1:
backtracking(ii, jj, state | (1 << (ii * n + jj)))
backtracking(si, sj, start)
return count | unique-paths-iii | Bitmask python | yshawn | 0 | 37 | unique paths iii | 980 | 0.797 | Hard | 15,914 |
https://leetcode.com/problems/unique-paths-iii/discuss/1555492/Python3-or-Easy-or-DFS-Explained | class Solution:
def _dfs(self, i,j, grid, _visited, non_blocker_nodes, m,n):
_visited.add((i,j))
if grid[i][j] == 2 and len(_visited) == non_blocker_nodes:
_visited.remove((i,j))
return 1
_steps = [(0,1),(0,-1),(1,0),(-1,0)]
_ans = 0
for k in _steps:
_n_i = i + k[0]
_n_j = j + k[1]
_curr = (_n_i, _n_j)
if (0<=_n_i<=m) and (0<=_n_j<=n) and grid[_n_i][_n_j] != -1 and (_curr not in _visited):
_ans += self._dfs(_n_i,_n_j,grid,_visited,non_blocker_nodes,m,n)
_visited.remove((i,j))
return _ans
def uniquePathsIII(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
_non_blocker_nodes = 0
_start = None
for i in range(m):
for j in range(n):
if grid[i][j]==1:
_start = (i,j)
if grid[i][j] != -1:
_non_blocker_nodes+=1
_ans = self._dfs(_start[0],_start[1],grid, set(), _non_blocker_nodes, m-1, n-1)
return _ans | unique-paths-iii | Python3 | Easy | DFS Explained | tg68 | 0 | 26 | unique paths iii | 980 | 0.797 | Hard | 15,915 |
https://leetcode.com/problems/unique-paths-iii/discuss/1555259/Using-sets-for-walked-paths-96-speed | class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
zeros = set()
start, end = (0, 0), (0, 0)
for r, row in enumerate(grid):
for c, v in enumerate(row):
if v == 1:
start = (r, c)
elif v == 2:
end = (r, c)
elif v == 0:
zeros.add((r, c))
n_zeros1 = len(zeros) + 1
paths = [[start, {start}]]
valid_paths = 0
while paths:
new_paths = []
for (r, c), set_path in paths:
for tpl in [(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)]:
if tpl == end and len(set_path) == n_zeros1:
valid_paths += 1
elif tpl in zeros and tpl not in set_path:
new_path = set_path.copy()
new_path.add(tpl)
new_paths.append([tpl, new_path])
paths = new_paths
return valid_paths | unique-paths-iii | Using sets for walked paths, 96% speed | EvgenySH | 0 | 61 | unique paths iii | 980 | 0.797 | Hard | 15,916 |
https://leetcode.com/problems/unique-paths-iii/discuss/1554249/Python3-Fast-and-Memory-efficient | class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
self.ans = 0
m = len(grid)
n = len(grid[0])
target_sum = 5 - m*n # start: 1, end: 2
start_i, start_j = None, None
for i, row in enumerate(grid):
for j, col in enumerate(row):
if col == 1:
start_i, start_j = i, j
break
if start_i:
break
def dfs(i, j) -> None:
if i < 0 or j < 0 or i >= m or j >= n:
return
if grid[i][j] == 2:
if sum(sum(grid, [])) == target_sum:
self.ans += 1
elif grid[i][j] == 0:
grid[i][j] = -1
dfs(i+1, j)
dfs(i, j+1)
dfs(i-1, j)
dfs(i, j-1)
grid[i][j] = 0
dfs(start_i + 1, start_j)
dfs(start_i, start_j + 1)
dfs(start_i - 1, start_j)
dfs(start_i, start_j - 1)
return self.ans | unique-paths-iii | Python3 Fast and Memory-efficient | ynnekuw | 0 | 17 | unique paths iii | 980 | 0.797 | Hard | 15,917 |
https://leetcode.com/problems/unique-paths-iii/discuss/1462752/Simple-Python-O(3n)-brute-force-dfs-solution | class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
def dfs(cur_i, cur_j):
if (cur_i, cur_j) == end or not empties:
if not empties:
self.ret += 1
return
for d_i, d_j in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
new_i, new_j = cur_i+d_i, cur_j+d_j
if 0 <= new_i < m and 0 <= new_j < n and (new_i, new_j) in empties:
empties.remove((new_i, new_j))
dfs(new_i, new_j)
empties.add((new_i, new_j))
m, n = len(grid), len(grid[0])
start = end = None
empties = set()
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
start = (i, j)
elif grid[i][j] == 2:
end = (i, j)
empties.add((i, j))
elif grid[i][j] == 0:
empties.add((i, j))
self.ret = 0
dfs(start[0], start[1])
return self.ret | unique-paths-iii | Simple Python O(3^n) brute force dfs solution | Charlesl0129 | 0 | 87 | unique paths iii | 980 | 0.797 | Hard | 15,918 |
https://leetcode.com/problems/unique-paths-iii/discuss/1458196/PyPy3-Solution-using-DFS-w-comments | class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
# Init
count = 0
m = len(grid)
n = len(grid[0])
# Assign start, end, obstacles and calculate total no. of
# nodes which can be visited before reaching the
# destination
start = (0,0)
end = (m-1,n-1)
obstacles = set()
total = m*n - 1
for row in range(m):
for col in range(n):
if grid[row][col] == -1:
total -= 1
obstacles.add((row,col))
if grid[row][col] == 1:
start = (row,col)
if grid[row][col] == 2:
end = (row,col)
# DFS in disguise
def dfs(node: Tuple, isVisited: Set = set()):
nonlocal count # global variable
# Node is not none
if node:
# Extact x and y co-ordinates of the node
x, y = node
if (node not in isVisited and # If not Visited
(0 <= x < m) and (0 <= y < n) and # Within Boundaries
node not in obstacles): # Not an obstacle
# if destination reached and all nodes are visited
# increment counter
if node == end and len(isVisited) == total:
count += 1
else:
# Add to isVisited Set
isVisited.add((x,y))
# Traverse from next neighbour
for r,c in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]:
if (r,c) not in isVisited:
dfs((r,c), isVisited)
# Back Track
isVisited.remove((x,y))
return
# begin dfs from start position
dfs(start)
return count # return count | unique-paths-iii | [Py/Py3] Solution using DFS w/ comments | ssshukla26 | 0 | 74 | unique paths iii | 980 | 0.797 | Hard | 15,919 |
https://leetcode.com/problems/unique-paths-iii/discuss/1409924/Fastest-Python-solution-(Backtrackingdfs)-with-better-understanding | class Solution:
def dfs(self, grid: List[List[int]], visitContext: List[List[bool]], x: int, y: int, remaining: int) -> int:
direction, output = [(0,1), (0,-1), (1,0), (-1,0)], 0
visitContext[x][y] = False
for i,j in direction:
dx, dy = x+i, y+j
if dx<0 or dx>len(grid)-1 or dy<0 or dy>len(grid[0])-1: continue
elif visitContext[dx][dy] and grid[dx][dy] == 0:
output += self.dfs(grid, visitContext, dx, dy, remaining-1)
elif visitContext[dx][dy] and grid[dx][dy] == 2 and remaining == 0:
output += 1
visitContext[x][y] = True
return output
def uniquePathsIII(self, grid: List[List[int]]) -> int:
visitContext, nonObstacleCount = [[True for i in range(len(grid[0]))] for i in range(len(grid))], 0
x=y=0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]==0:
nonObstacleCount +=1
elif grid[i][j]==1:
x, y = i, j
return self.dfs(grid, visitContext, x, y, nonObstacleCount) | unique-paths-iii | Fastest Python solution (Backtracking/dfs) with better understanding | abrarjahin | 0 | 76 | unique paths iii | 980 | 0.797 | Hard | 15,920 |
https://leetcode.com/problems/unique-paths-iii/discuss/1376595/python3-or-48ms-Backtracking | class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
self.noc=0 #no of non-obstacle cell
self.ans=0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]==0:
self.noc+=1 #counting no of non-obstacle cell
visited=[[False for i in range(len(grid[0]))] for j in range(len(grid))]
cell_cnt=0 #for counting how many cells we travelled
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]==1:
self.solve(i,j,grid,visited,cell_cnt) #function call
break #there is only one starting point so we break after one-call
return self.ans
def solve(self,row,col,grid,visited,cell_cnt):
if grid[row][col]==2: #if we reach destination cell
if cell_cnt-1==self.noc: #compare no of travelled cells V/S no of cells we have to travel (minus because we are including 1 also in non-obstacle cells)
self.ans+=1 #incrementing answer by 1 as we got one path
return
if self.isvalid(row,col,grid,visited):
visited[row][col]=True #marked as visited
cell_cnt+=1 #increment travelled cell by 1
if row-1>=0 and visited[row-1][col]==False: #upper cell check
self.solve(row-1,col,grid,visited,cell_cnt)
visited[row-1][col]=False #marking previous cell as unvisited so we can visit in next path also (same for next 4 checks)
if row+1<len(grid) and visited[row+1][col]==False: #lower cell check
self.solve(row+1,col,grid,visited,cell_cnt)
visited[row+1][col]=False
if col-1>=0 and visited[row][col-1]==False: #left cell check
self.solve(row,col-1,grid,visited,cell_cnt)
visited[row][col-1]=False
if col+1<len(grid[0]) and visited[row][col+1]==False: #right cell check
self.solve(row,col+1,grid,visited,cell_cnt)
visited[row][col+1]=False
visited[row][col]=False #marking current cell unvisited so we can visit in next path also
return
def isvalid(self,row,col,grid,visited): #checking cell Validity
if grid[row][col]!=-1 and visited[row][col]==False:
return True
else:
return False | unique-paths-iii | python3 | 48ms Backtracking | swapnilsingh421 | 0 | 57 | unique paths iii | 980 | 0.797 | Hard | 15,921 |
https://leetcode.com/problems/unique-paths-iii/discuss/903602/Python-Clean-and-Simple | class Solution:
directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
def uniquePathsIII(self, grid: List[List[int]]) -> int:
row, col = len(grid), len(grid[0])
result, empty = [0], 1
sX, sY = 0, 0
for x, y in product(range(row), range(col)):
if grid[x][y] == 1:
sX, sY = x, y
if grid[x][y] == 0:
empty += 1
def dfs(x, y, empty):
if not (0 <= x < row and 0 <= y < col and grid[x][y] >= 0):
return
if grid[x][y] == 2:
result[0] += 1 if empty == 0 else 0
return
grid[x][y] = -2
for dx, dy in self.directions:
dfs(x + dx, y + dy, empty - 1)
grid[x][y] = 0
dfs(sX, sY, empty)
return result[0] | unique-paths-iii | [Python] Clean & Simple | yo1995 | 0 | 66 | unique paths iii | 980 | 0.797 | Hard | 15,922 |
https://leetcode.com/problems/unique-paths-iii/discuss/856993/Python3-or-Simple-or-DFS-or-Explained-or-Annotated | class Solution:
def uniquePathsIII(self, grid):
self.ans = 0
n = len(grid)
m = len(grid[0])
def dfs(point, remain):
x = point[0]
y = point[1]
if grid[x][y] == -1:
return
if grid[x][y] == 2 and not remain:
self.ans += 1
return
for (dx, dy) in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
save = grid[x][y]
grid[x][y] = -1
if 0<=dx+x<=n-1 and 0<=dy+y<=m-1:
dfs((dx+x, dy+y), remain-1)
grid[x][y] = save
valid = 0
start = (0, 0)
for i in range(n):
for j in range(m):
if grid[i][j] == 1:
start = (i, j)
if grid[i][j] != -1:
valid += 1
dfs(start, valid-1)
return self.ans | unique-paths-iii | [Python3] | Simple | DFS | Explained | Annotated | TanishqChaudhary | 0 | 35 | unique paths iii | 980 | 0.797 | Hard | 15,923 |
https://leetcode.com/problems/unique-paths-iii/discuss/804132/Python%3A-Easy!-Simple-DFS-Solution-oror-97-Faster | class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
moves = ((1, 0), (-1, 0), (0, 1), (0, -1))
ans = 0
# ----------------------------------------------
def dfs(grid, r, c, vertexSet):
nonlocal ans, moves
vertexSet.remove((r, c))
if grid[r][c] == 2:
if len(vertexSet) == 0:
ans += 1
return
for x, y in moves:
x, y = r + x, c + y
if (x, y) in vertexSet:
dfs(grid, x, y, vertexSet.copy())
# -----------------------------------------------
vertexSet = set()
r1, r2 = 0, 0
for r in range(len(grid)): # Add (row, col) in set if it is not onstacle
for c in range(len(grid[0])):
if grid[r][c] != -1:
if grid[r][c] == 1:
r1, c1 = r, c
vertexSet.add((r, c))
dfs(grid, r1, c1, vertexSet) # Start DFS from start - (row, col)
return ans | unique-paths-iii | Python: Easy! Simple DFS Solution || 97% Faster | sameerkhurd | 0 | 130 | unique paths iii | 980 | 0.797 | Hard | 15,924 |
https://leetcode.com/problems/triples-with-bitwise-and-equal-to-zero/discuss/1257470/Python3-hash-table | class Solution:
def countTriplets(self, nums: List[int]) -> int:
freq = defaultdict(int)
for x in nums:
for y in nums:
freq[x&y] += 1
ans = 0
for x in nums:
mask = x = x ^ 0xffff
while x:
ans += freq[x]
x = mask & (x-1)
ans += freq[0]
return ans | triples-with-bitwise-and-equal-to-zero | [Python3] hash table | ye15 | 4 | 222 | triples with bitwise and equal to zero | 982 | 0.577 | Hard | 15,925 |
https://leetcode.com/problems/triples-with-bitwise-and-equal-to-zero/discuss/2667308/Python-Easy-Solution-beats-69.73 | class Solution:
def countTriplets(self, nums: List[int]) -> int:
freq = defaultdict(int)
for x in nums:
for y in nums:
freq[x&y] += 1
ans = 0
for x in nums:
mask = x = x ^ 0xffff
while x:
ans += freq[x]
x = mask & (x-1)
ans += freq[0]
return ans | triples-with-bitwise-and-equal-to-zero | Python Easy Solution beats 69.73% | mritunjayyy | 0 | 8 | triples with bitwise and equal to zero | 982 | 0.577 | Hard | 15,926 |
https://leetcode.com/problems/triples-with-bitwise-and-equal-to-zero/discuss/2483331/This-is-my-Python3-solution-oror-Easy-to-understand | class Solution:
def countTriplets(self, nums: List[int]) -> int:
ans = 0
mem = [0] * (1 << 16)
size = len(nums)
for i in range(size):
for j in range(i, size):
mem[nums[i]&nums[j]] += 2 if i != j else 1
for ij in range(1 << 16):
if mem[ij] > 0:
for k in nums:
if k & ij == 0:
ans += mem[ij]
return ans | triples-with-bitwise-and-equal-to-zero | ✔️ This is my Python3 solution || Easy to understand | explusar | 0 | 33 | triples with bitwise and equal to zero | 982 | 0.577 | Hard | 15,927 |
https://leetcode.com/problems/minimum-cost-for-tickets/discuss/1219272/Python-O(N)-Runtime-O(N)-with-explanation | class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
#create the total costs for the days
costForDays = [0 for _ in range(days[-1] + 1) ]
#since days are sorted in ascending order, we only need the index of the days we haven't visited yet
curIdx = 0
for d in range(1, len(costForDays)):
#if we do not need to travel that day
#we don't need to add extra costs
if d < days[curIdx]:
costForDays[d] = costForDays[d - 1]
continue
#else this means we need to travel this day
#find the cost if we were to buy a 1-day pass, 7-day pass and 30-day pass
costs_extra_1 = costForDays[d - 1] + costs[0]
costs_extra_7 = costForDays[max(0, d - 7)] + costs[1]
costs_extra_30 = costForDays[max(0, d - 30)] + costs[2]
#get the minimum value
costForDays[d] = min(costs_extra_1, costs_extra_7, costs_extra_30)
#update the index to the next day we need to travel
curIdx += 1
return costForDays[-1] | minimum-cost-for-tickets | Python O(N) Runtime O(N) with explanation | sherlockieee | 3 | 244 | minimum cost for tickets | 983 | 0.644 | Medium | 15,928 |
https://leetcode.com/problems/minimum-cost-for-tickets/discuss/1877186/Python3oror-O(n)-time-oror-O(max(days))-space | class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
dp = [0] * (days[-1]+1)
date = 0
for idx in range(1,len(dp)):
if idx == days[date]:
one_day = dp[idx-1] + costs[0]
seven_day = dp[idx-7] + costs[1] if idx - 7 >= 0 else costs[1]
thirty_day = dp[idx-30] + costs[2] if idx - 30 >= 0 else costs[2]
dp[idx] = min(one_day,seven_day,thirty_day)
date += 1
else:
dp[idx] = dp[idx-1]
return dp[-1] | minimum-cost-for-tickets | Python3|| O(n) time || O(max(days)) space | s_m_d_29 | 2 | 79 | minimum cost for tickets | 983 | 0.644 | Medium | 15,929 |
https://leetcode.com/problems/minimum-cost-for-tickets/discuss/1674020/Simple-DP-solution-in-Python | class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
# map the number of days per ticket to the cost
cost_map = {
1: costs[0],
7: costs[1],
30: costs[2],
}
travelling_days = set(days) # set of active travel days
dp_costs = [0 for x in range(days[-1] + 1)] # tracks the min cost day
for i in range(days[-1] + 1):
# store most recent lowest sum in arr to use later
if i not in travelling_days:
dp_costs[i] = dp_costs[i - 1]
continue
possible_costs = []
for ticket,cost in cost_map.items():
day_diff = i - ticket
if day_diff <= 0:
# this ticket will cover the total cost
possible_costs.append(cost)
else:
# ticket was bought day_diff ago
# sum lowest cost on day_diff with new ticket cost
possible_costs.append(cost + dp_costs[day_diff])
# find min of all ticket options on this day
dp_costs[i] = min(possible_costs)
return dp_costs[-1] | minimum-cost-for-tickets | Simple DP solution in Python | nat_5t34 | 1 | 84 | minimum cost for tickets | 983 | 0.644 | Medium | 15,930 |
https://leetcode.com/problems/minimum-cost-for-tickets/discuss/1199803/Python-Basic-Recursion | class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
days = set(days)
graph = {0 : 1, 1 : 7, 2: 30}
@functools.lru_cache(None)
def recurse(day, end):
if day > end:
return 0
if day not in days:
return recurse(day+1, end)
return min([
c + recurse(day+graph[i], end)
for i,c in enumerate(costs)
])
return recurse(1, max(days)) | minimum-cost-for-tickets | Python Basic Recursion | dev-josh | 1 | 159 | minimum cost for tickets | 983 | 0.644 | Medium | 15,931 |
https://leetcode.com/problems/minimum-cost-for-tickets/discuss/811167/Python3-dp-and-binary-search | class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
@lru_cache(None)
def fn(i):
"""Return minimum cost of traveling on days[i:]"""
if i == len(days): return 0 # boundary condition (no more travel)
ans = inf
for cost, d in zip(costs, (1, 7, 30)):
ii = bisect_left(days, days[i]+d)
ans = min(ans, cost + fn(ii))
return ans
return fn(0) | minimum-cost-for-tickets | [Python3] dp & binary search | ye15 | 1 | 81 | minimum cost for tickets | 983 | 0.644 | Medium | 15,932 |
https://leetcode.com/problems/minimum-cost-for-tickets/discuss/347934/DP-python3-99 | class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
cost_of_day = [0] * 366
for index, day in enumerate(days):
if index == 0:
cost_of_day[day] = min(costs)
continue
for i in range(days[index-1]+1, day):
cost_of_day[i] = cost_of_day[i-1]
cost_of_day[day] = min([cost_of_day[days[index-1]]+costs[0], \
cost_of_day[max([day-7, 0])]+costs[1],\
cost_of_day[max([0, day-30])]+costs[2]])
return cost_of_day[days[-1]] | minimum-cost-for-tickets | DP python3 99% | pingruchou1125tw | 1 | 107 | minimum cost for tickets | 983 | 0.644 | Medium | 15,933 |
https://leetcode.com/problems/minimum-cost-for-tickets/discuss/2656214/Easy-Python-DP-with-comments | class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
days = sorted(days)
res = [0] * (days[-1] + 1) # represent each day.
start = days[0]
res[start] = min(costs) # in case day 7 pass is cheaper than day 1
days = set(days)
for d in range(start+1, len(res)):
if d not in days: # only consider the day in the days set.
res[d] = res[d-1]
else:
# case 1: buy day 1 pass for today (d)
case_1 = costs[0] + res[d-1]
# case 2: buy day 7 pass for today (d)
if d - 7 >= start:
case_2 = res[d-7] + costs[1]
else:
case_2 = costs[1]
# case 3: buy day 30 pass for today (d)
if d - 30 >= start:
case_3 = res[d-30] + costs[-1]
else:
case_3 = costs[-1]
res[d] = min(case_1, case_2, case_3)
return res[-1] | minimum-cost-for-tickets | Easy Python DP with comments | xiangyupeng1994 | 0 | 6 | minimum cost for tickets | 983 | 0.644 | Medium | 15,934 |
https://leetcode.com/problems/minimum-cost-for-tickets/discuss/2636741/Clean-Fast-Python3-or-Bottom-Up-DP-or-9-Lines | class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
travel = [False] * (days[-1]) + [True] * 31
for day in days: travel[day] = True
dp = [0] * (days[-1] + 31)
for i in range(days[-1], -1, -1):
if travel[i]:
dp[i] = min(costs[0] + dp[i + 1], costs[1] + dp[i + 7], costs[2] + dp[i + 30])
else:
dp[i] = dp[i + 1]
return dp[0] | minimum-cost-for-tickets | Clean, Fast Python3 | Bottom Up DP | 9 Lines | ryangrayson | 0 | 7 | minimum cost for tickets | 983 | 0.644 | Medium | 15,935 |
https://leetcode.com/problems/minimum-cost-for-tickets/discuss/2495967/Python3-solution%3A-faster-than-most-submissions-oror-Very-simple | class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
min_cost = float('inf')
que = deque()
# enqueue the possible state of day 1
que.append((days[0], costs[0]))
que.append((days[0]+7-1, costs[1]))
que.append((days[0]+30-1, costs[2]))
last_day = days[-1]
for i in range(1, len(days)):
for _ in range(len(que)):
node = que.popleft()
if node[0] < days[i]:
# try taking all the three pass on that day and enqueue
que.append((days[i], node[1]+costs[0]))
if days[i] + 7 - 1 >= last_day:
min_cost = min(min_cost, node[1] + costs[1])
else:
que.append((days[i]+7-1, node[1]+costs[1]))
if days[i] + 30 - 1 >= last_day:
min_cost = min(min_cost, node[1] + costs[2])
else:
que.append((days[i]+30-1, node[1]+costs[2]))
else:
que.append(node)
for _ in range(len(que)):
node = que.popleft()
min_cost = min(min_cost, node[1])
return min_cost | minimum-cost-for-tickets | ✔️ Python3 solution: faster than most submissions || Very simple | explusar | 0 | 57 | minimum cost for tickets | 983 | 0.644 | Medium | 15,936 |
https://leetcode.com/problems/minimum-cost-for-tickets/discuss/2318046/Python-Memoized-Solution | class Solution(object):
def mincostTickets(self,days, costs):
dp = {}
def index_finder(i,days,arr):
key = arr[i]
while i<len(arr) and arr[i]< key+days:
i+=1
return i
def solve(days,i,costs):
if i>=len(days):
return 0
if days[i] in dp:
return dp[days[i]]
# cost 1
j = index_finder(i,1,days)
v1 = solve(days,j,costs)+costs[0]
# cost 2
j = index_finder(i,7,days)
v2 = solve(days,j,costs)+costs[1]
# cost3
j = index_finder(i,30,days)
v3 = solve(days,j,costs)+costs[2]
dp[days[i]] = min(v1,v2,v3)
return dp[days[i]]
return solve(days,0,costs) | minimum-cost-for-tickets | Python Memoized Solution | Abhi_009 | 0 | 34 | minimum cost for tickets | 983 | 0.644 | Medium | 15,937 |
https://leetcode.com/problems/minimum-cost-for-tickets/discuss/2156588/Python-clean-DP | class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
dp = [0] * (366 + 30)
days = set(days)
for day in range(365, 0, -1):
if day in days:
dp[day] = min(dp[day+1] + costs[0], dp[day+7] + costs[1], dp[day+30] + costs[2])
else:
dp[day] = dp[day+1]
return dp[1] | minimum-cost-for-tickets | Python, clean DP | blue_sky5 | 0 | 35 | minimum cost for tickets | 983 | 0.644 | Medium | 15,938 |
https://leetcode.com/problems/minimum-cost-for-tickets/discuss/1984076/PYTHON-SOL-oror-DP-oror-TABULAR-METHOR-oror-LINEAR-SOLUTION-oror-WELL-EXPLAINED-oror | class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
dp = [0]*366
d = {x:True for x in days}
for i in range(366):
if i in d:
tmp1 = dp[i-1] if i>=1 else 0
tmp2 = dp[i-7] if i>=7 else 0
tmp3 = dp[i-30] if i>=30 else 0
mini = min(costs[0]+tmp1,costs[1]+tmp2,costs[2]+tmp3)
dp[i] = mini
else:
dp[i] = dp[i-1]
return dp[days[-1]] | minimum-cost-for-tickets | PYTHON SOL || DP || TABULAR METHOR || LINEAR SOLUTION || WELL EXPLAINED || | reaper_27 | 0 | 61 | minimum cost for tickets | 983 | 0.644 | Medium | 15,939 |
https://leetcode.com/problems/minimum-cost-for-tickets/discuss/1817389/Python-easy-to-read-and-understand-or-DP | class Solution:
def find(self, days, i, target):
while i < len(days) and days[i] <= target:
i = i+1
return i
def solve(self, days, costs, i):
if i >= len(days):
return 0
x1 = self.solve(days, costs, i+1) + costs[0]
index = self.find(days, i, days[i]+6)
x2 = self.solve(days, costs, index) + costs[1]
index = self.find(days, i, days[i]+29)
x3 = self.solve(days, costs, index) + costs[2]
return min(x1, x2, x3)
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
return self.solve(days, costs, 0) | minimum-cost-for-tickets | Python easy to read and understand | DP | sanial2001 | 0 | 137 | minimum cost for tickets | 983 | 0.644 | Medium | 15,940 |
https://leetcode.com/problems/minimum-cost-for-tickets/discuss/1817389/Python-easy-to-read-and-understand-or-DP | class Solution:
def find(self, days, i, target):
while i < len(days) and days[i] <= target:
i = i+1
return i
def solve(self, days, costs, i, d):
if i >= len(days):
return 0
if i in d:
return d[i]
x1 = self.solve(days, costs, i+1, d) + costs[0]
index = self.find(days, i, days[i]+6)
x2 = self.solve(days, costs, index, d) + costs[1]
index = self.find(days, i, days[i]+29)
x3 = self.solve(days, costs, index, d) + costs[2]
d[i] = min(x1, x2, x3)
return d[i]
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
return self.solve(days, costs, 0, {}) | minimum-cost-for-tickets | Python easy to read and understand | DP | sanial2001 | 0 | 137 | minimum cost for tickets | 983 | 0.644 | Medium | 15,941 |
https://leetcode.com/problems/minimum-cost-for-tickets/discuss/1782976/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up) | class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
@lru_cache(None)
def dp(day: int) -> int:
if day > days[-1]:
return 0
if day == days[-1]:
return min(costs)
else:
i = 0
while i < len(days) and days[i] < day:
i += 1
if i == len(days):
return 0
day = days[i]
return min(costs[0]+dp(day+1), costs[1]+dp(day+7), costs[2]+dp(day+30))
return dp(days[0]) | minimum-cost-for-tickets | ✅ [Java / Python3] Simple DP Solution (Top-Down & Bottom-Up) | JawadNoor | 0 | 56 | minimum cost for tickets | 983 | 0.644 | Medium | 15,942 |
https://leetcode.com/problems/minimum-cost-for-tickets/discuss/1782976/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up) | class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
dp = [0]*(days[-1]+1)
for i in range(len(dp)):
if i in days:
dp[i] = min(dp[max(0, i-1)]+costs[0],
dp[max(0, i-7)]+costs[1], dp[max(0, i-30)]+costs[2])
else:
dp[i] = dp[i-1]
return dp[-1] | minimum-cost-for-tickets | ✅ [Java / Python3] Simple DP Solution (Top-Down & Bottom-Up) | JawadNoor | 0 | 56 | minimum cost for tickets | 983 | 0.644 | Medium | 15,943 |
https://leetcode.com/problems/string-without-aaa-or-bbb/discuss/1729883/Python-beats-91 | class Solution:
def strWithout3a3b(self, a: int, b: int) -> str:
res = []
while a + b > 0:
if len(res) >= 2 and res[-2:] == ['a', 'a']:
res.append('b')
b-=1
elif len(res) >= 2 and res[-2:] == ['b', 'b']:
res.append('a')
a-=1
elif a > b:
res.append('a')
a-=1
else:
res.append('b')
b-=1
return ''.join(res) | string-without-aaa-or-bbb | Python beats 91% | leopardcoderd | 1 | 104 | string without aaa or bbb | 984 | 0.43 | Medium | 15,944 |
https://leetcode.com/problems/string-without-aaa-or-bbb/discuss/984024/Python3-greedy-O(N) | class Solution:
def strWithout3a3b(self, a: int, b: int) -> str:
ans = []
while a and b:
if ans[-2:] == ["b"]*2 or 2*b < a:
ans.append("a")
a -= 1
else:
ans.append("b")
b -= 1
ans.extend(a*["a"] + b*["b"])
return "".join(ans) | string-without-aaa-or-bbb | [Python3] greedy O(N) | ye15 | 1 | 63 | string without aaa or bbb | 984 | 0.43 | Medium | 15,945 |
https://leetcode.com/problems/string-without-aaa-or-bbb/discuss/1984137/PYTHON-SOL-oror-VERY-EASY-AND-INTUATIVE-oror-WELL-EXPLAINED-oror-GREEDY-oror | class Solution:
def strWithout3a3b(self, a: int, b: int) -> str:
n = a + b
fill = 'a' if a >= b else 'b'
ma = a if a >= b else b
mi = a if a < b else b
string = [None]*n
index = 0
while ma > 0 :
string[index] = fill
index += 3
if index >= n: index = 1
ma -= 1
fill ='a' if a < b else 'b'
ans = ""
for i in string:
if i == None: ans += fill
else: ans += i
return ans | string-without-aaa-or-bbb | PYTHON SOL || VERY EASY AND INTUATIVE || WELL EXPLAINED || GREEDY || | reaper_27 | 0 | 80 | string without aaa or bbb | 984 | 0.43 | Medium | 15,946 |
https://leetcode.com/problems/string-without-aaa-or-bbb/discuss/1856391/Python-Solution-Heap | class Solution:
def strWithout3a3b(self, a: int, b: int) -> str:
heap = []
if a > 0:
heapq.heappush(heap, (-a, 'a'))
if b > 0:
heapq.heappush(heap, (-b, 'b'))
s = ''
while heap:
try:
curr_char_remain, current_char = heapq.heappop(heap)
except IndexError:
break
curr_char_remain = abs(curr_char_remain)
if s[-2:] != 2 * current_char:
if curr_char_remain >= 2:
s += 2 * current_char
curr_char_remain -= 2
if curr_char_remain > 0:
heapq.heappush(heap, (-1 * curr_char_remain, current_char))
else:
s += current_char
else:
try:
n_curr_char_remain, n_current_char = heapq.heappop(heap)
except IndexError:
break
n_curr_char_remain = abs(n_curr_char_remain)
s += n_current_char
n_curr_char_remain -= 1
if n_curr_char_remain != 0:
heapq.heappush(heap, (-1 * n_curr_char_remain, n_current_char))
heapq.heappush(heap, (-1 * curr_char_remain, current_char))
return s | string-without-aaa-or-bbb | Python Solution Heap | DietCoke777 | 0 | 19 | string without aaa or bbb | 984 | 0.43 | Medium | 15,947 |
https://leetcode.com/problems/string-without-aaa-or-bbb/discuss/1625750/Python-3-O(n)-solution | class Solution:
def strWithout3a3b(self, a: int, b: int) -> str:
# n = current # of consecutive chracters in res that are the same
# positive if it's consecutive as, negative if it's bs
n = 0
res = ''
while a and b:
if n == -2 or (n != 2 and a >= b):
res += 'a'
a -= 1
n = max(1, n + 1)
else:
res += 'b'
b -= 1
n = min(-1, n - 1)
return res + (a * 'a') + (b * 'b') | string-without-aaa-or-bbb | Python 3 O(n) solution | dereky4 | 0 | 116 | string without aaa or bbb | 984 | 0.43 | Medium | 15,948 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2603372/LeetCode-The-Hard-Way-Explained-Line-By-Line | class Solution:
# the idea is we don't calculate the even sum from scratch for each query
# instead, we calculate it at the beginning
# since each query only updates one value,
# so we can adjust the even sum base on the original value and new value
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
# calculate the sum of all even numbers
evenSum = sum(x for x in nums if x % 2 == 0)
ans = []
for val, idx in queries:
# if original nums[idx] is even, then we deduct it from evenSum
if nums[idx] % 2 == 0: evenSum -= nums[idx]
# in-place update nums
nums[idx] += val
# check if we need to update evenSum for the new value
if nums[idx] % 2 == 0: evenSum += nums[idx]
# then we have evenSum after this query, push it to ans
ans.append(evenSum)
return ans | sum-of-even-numbers-after-queries | 🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line | wingkwong | 58 | 3,200 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,949 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2603332/Easy-python-solution | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
sm=0
for i in range(len(nums)):
if nums[i]%2==0:
sm+=nums[i]
lst=[]
for i in range(len(queries)):
prev=nums[queries[i][1]]
nums[queries[i][1]]+=queries[i][0]
curr=nums[queries[i][1]]
if prev%2==0:
if curr%2==0:
sm+=(curr-prev)
else:
sm-=prev
else:
if curr%2==0:
sm+=curr
lst.append(sm)
return lst | sum-of-even-numbers-after-queries | Easy python solution | shubham_1307 | 5 | 575 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,950 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2603228/Python-Segment-Tree-Approach-%2B-Query-Traversal-Approach | class Solution:
# Simple query traversal approach
# Check if previously the nums element was even or odd
# If it was even we just need to remove it or update the ressum based on the new result being even or odd
# If it was odd we need to add to the ressum only if the new value becomes even
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
ressum = sum([num for num in nums if not num & 1])
res = []
for val, i in queries:
if nums[i] & 1:
if not nums[i] + val & 1:
ressum += nums[i] + val
else:
if not nums[i] + val & 1:ressum += val
else: ressum -= nums[i]
res.append(ressum)
nums[i] += val
return res | sum-of-even-numbers-after-queries | Python Segment Tree Approach + Query Traversal Approach | shiv-codes | 2 | 80 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,951 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2169359/Python3-Runtime%3A-583ms-72.40-oror-memory%3A-20.5mb-37.69 | class Solution:
# O(n) || O(1)
# Runtime: 583ms 72.40% || memory: 20.5mb 37.69%
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
totalEvenNumSum = sum([num for num in nums if num % 2 == 0])
result = []
for val, idx in queries:
oldVal = nums[idx]
nums[idx] += val
if oldVal % 2 == 0:
totalEvenNumSum -= oldVal
if nums[idx] % 2 == 0:
totalEvenNumSum += nums[idx]
result.append(totalEvenNumSum)
return result | sum-of-even-numbers-after-queries | Python3 Runtime: 583ms 72.40% || memory: 20.5mb 37.69% | arshergon | 2 | 101 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,952 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2606821/python3-pretty-short-solution | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
res=[]
cur_sum=sum([i for i in nums if not i%2])
for q in queries:
if not nums[q[1]]%2:
cur_sum-=nums[q[1]]
nums[q[1]]+=q[0]
if not nums[q[1]]%2:
cur_sum+=nums[q[1]]
res.append(cur_sum)
return res | sum-of-even-numbers-after-queries | python3 pretty short solution | benon | 1 | 38 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,953 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2605677/SIMPLEST-PYTHON-SOLUTION(Memory-Usage%3A-20.4-MB-less-than-75.51-of-Python3) | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
ans=list()
asum=0
for i in nums:
if i%2==0:
asum+=i
else: continue
subans=asum
for j in queries:
if nums[j[1]]%2==0:
subans-=nums[j[1]]
# print(nums)
nums[j[1]]+=j[0]
if nums[j[1]]%2==0:
subans+=nums[j[1]]
# print(nums)
ans.append(subans)
return ans | sum-of-even-numbers-after-queries | SIMPLEST PYTHON SOLUTION(Memory Usage: 20.4 MB, less than 75.51% of Python3) | DG-Problemsolver | 1 | 39 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,954 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2605548/Python-Easy-Solution-~-Brute-force | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
res = []
total = sum(list(filter(lambda x: (x%2==0),nums)))
for i in range(len(queries)):
val = queries[i][0]
index = queries[i][1]
num = nums[index]
if num%2 == 0:
total -= num
nums[index] += val
if nums[index]%2 == 0:
total += nums[index]
res += [total]
return res | sum-of-even-numbers-after-queries | Python Easy Solution ~ Brute force | Shivam_Raj_Sharma | 1 | 18 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,955 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2603527/Python-O(n) | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
se = 0
ans = []
for i in nums:
if(i%2==0):
se += i
for i in queries:
if(nums[i[1]]%2 and i[0]%2):
se+= nums[i[1]] + i[0]
nums[i[1]] += i[0]
elif(nums[i[1]]%2==0 and i[0]%2):
se -= nums[i[1]]
nums[i[1]] += i[0]
elif(nums[i[1]]%2 and i[0]%2==0):
nums[i[1]] += i[0]
else:
se += i[0]
nums[i[1]] += i[0]
ans.append(se)
return ans | sum-of-even-numbers-after-queries | Python O(n) | Pradyumankannan | 1 | 47 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,956 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2603266/python3-or-easy-or-array-or-even-sum | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
res, s = [], 0
for i, e in enumerate(nums):
if e%2==0: s += e
for val, index in queries:
if nums[index] % 2 == 0: s -= nums[index]
nums[index] += val
if nums[index]%2==0: s += nums[index]
res.append(s)
return res | sum-of-even-numbers-after-queries | python3 | easy | array | even sum | H-R-S | 1 | 49 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,957 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/1033838/Same-Idea-As-the-Solution-(though-slightly-complex)-With-Clear-Comments! | class Solution:
def sumEvenAfterQueries(self, A: List[int], queries: List[List[int]]) -> List[int]:
# time limit exceeded
# outSum = []
# for query in queries:
# A[query[1]] += query[0]
# outSum.append(sum([i for i in A if i%2 == 0 ]))
# return outSum
outSum = []
# memorize the evenSum
evenSumSoFar = sum([i for i in A if i%2 == 0 ])
for x,k in queries:
if x % 2 == 0 and A[k] %2 == 0: # even + even = even -- from even to even
evenSumSoFar += x
if x % 2 != 0 and A[k] % 2 == 0: # odd + even = odd -- from even to odd
evenSumSoFar -= A[k]
if x % 2 != 0 and A[k] % 2 != 0: # odd + odd = even -- from odd to even
evenSumSoFar += x + A[k]
# if x % 2 == 0 and A[k] % 2 != 0: # even + odd = odd -- from odd to odd
# do nothing
A[k] += x
outSum.append(evenSumSoFar)
return outSum | sum-of-even-numbers-after-queries | Same Idea As the Solution (though slightly complex) With Clear Comments! | Yan_Air | 1 | 168 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,958 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/805245/simple-of-simple | class Solution:
def sumEvenAfterQueries(self, A: List[int], queries: List[List[int]]) -> List[int]:
answer = []
s = 0
for i in A:
if i % 2 == 0:
s += i
for q in queries:
t = A[q[1]]
if t % 2 == 0:
s -= t
A[q[1]] += q[0]
t = A[q[1]]
if t % 2 == 0:
s += t
answer.append(s)
return answer | sum-of-even-numbers-after-queries | simple of simple | seunggabi | 1 | 101 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,959 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2803265/Python-or-Simple-or-Short | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
s = 0
ans = []
# storing sum of all even elements in s
for ele in nums:
if ele % 2 == 0:
s += ele
# iterating queries
for q in queries:
# if the element that we will modify is already even, subtract it from s, we will add it later
if nums[q[1]]%2==0:
s -= nums[q[1]]
# adding val to the required element
nums[q[1]] += q[0]
# if the element is even after modification, we will add it to s
if nums[q[1]] % 2 == 0:
s += nums[q[1]]
# we will insert s in ans in every iteration
ans.append(s)
return ans | sum-of-even-numbers-after-queries | Python | Simple | Short | imkprakash | 0 | 1 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,960 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2607559/Java-or-Python3-or-JavaScript-Solution-simple-few-lines.-O(N-%2B-M)-time-O(1)-space. | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
sum = 0
res = []
for num in nums:
if num%2 == 0:
sum += num
for query in queries:
if nums[query[1]]%2 == 0:
sum -= nums[query[1]]
nums[query[1]] += query[0]
if nums[query[1]]%2 == 0:
sum += nums[query[1]]
res.append(sum)
return res | sum-of-even-numbers-after-queries | Java | Python3 | JavaScript Solution simple, few lines. O(N + M) time O(1) space. | Angelus_ | 0 | 13 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,961 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2607011/Python3-or-CPP-or-O(N)-or-Simple | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
ans = []
even_nums = [num for num in nums if not num % 2 ]
sm = sum(even_nums)
for val, index in queries:
num = nums[index]
tmp = num + val
if not num % 2 and not tmp % 2:
sm += val
elif not num % 2:
sm -= num
elif not tmp % 2:
sm += tmp
nums[index] += val
ans.append(sm)
return ans | sum-of-even-numbers-after-queries | Python3 | CPP | O(N) | Simple | joshua_mur | 0 | 9 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,962 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2606987/Python-Straight-forward | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
# even + even = add value to tot
# odd + odd = add both
# even + odd = subtract nums[i]
# odd + even = no changes
tot = sum(i for i in nums if i%2==0)
res = []
for v,i in queries:
if nums[i]%2==0 and v%2==0:
tot += v
if nums[i]%2 and v%2:
tot += nums[i] + v
if nums[i]%2==0 and v%2:
tot -= nums[i]
nums[i] += v
res.append(tot)
return res | sum-of-even-numbers-after-queries | Python - Straight forward | lokeshsenthilkumar | 0 | 8 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,963 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2606333/Python-or-Simple-or-SOLUTION-or-FASTER-than-93.37 | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
res=[]
s=0
for i in nums:
if i%2==0:
s+=i
for v,i in queries:
if nums[i]%2==0:
s=s-nums[i]
t=nums[i]+v
if t%2==0:
s+=t
nums[i]=t
res.append(s)
return res | sum-of-even-numbers-after-queries | Python | Simple | SOLUTION | FASTER than 93.37% | manav023 | 0 | 13 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,964 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2606175/Intuitive-solution-in-Python-3-with-inline-comments | class Solution:
def sumEvenAfterQueries(self, N: List[int], Q: List[List[int]]) -> List[int]:
def gen():
s = sum(n for n in N if not n & 1)
for v, index in Q:
# prev is the value before N[index] gets queried
prev, N[index] = N[index], N[index] + v
# if N[index] is changed from odd to even,
# from the aspect of sum of even numbers, s simply increases by N[index]
if prev & 1 and not N[index] & 1:
s += N[index]
# if N[index] is changed from even to odd,
# s actullay loses prev hence we subtract by prev
elif not prev & 1 and N[index] & 1:
s -= prev
# if N[index] remains even, we shall update s by the difference between prev and N[index]
elif not prev & 1 and not N[index] & 1:
s += (N[index] - prev)
yield s
return list(gen()) | sum-of-even-numbers-after-queries | Intuitive solution in Python 3 with inline comments | mousun224 | 0 | 3 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,965 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2605568/Python-Simple-Python-Solution | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
result = []
even_sum = 0
for num in nums:
if num % 2 == 0:
even_sum = even_sum + num
for query in queries:
value, index = query
current_value = nums[index]
updated_value = nums[index] + value
if current_value % 2 == 0 and updated_value % 2 == 0:
result.append(even_sum + value)
elif current_value % 2 != 0 and updated_value % 2 != 0:
result.append(even_sum)
elif current_value % 2 == 0 and updated_value % 2 != 0:
result.append(even_sum - current_value)
elif current_value % 2 != 0 and updated_value % 2 == 0:
result.append(even_sum + updated_value)
nums[index] = updated_value
even_sum = result[-1]
return result | sum-of-even-numbers-after-queries | [ Python ] ✅✅ Simple Python Solution 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 26 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,966 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2605391/Python-or-Easy-understanding-or-based-on-just-even-odd | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
even_sum=0
for i in nums:
if i%2==0:
even_sum+=i
res=[]
for i in range(0,len(queries)):
x,y=queries[i]
if nums[y]%2==0:
even_sum-=nums[y]
nums[y]+=x
else:
nums[y]+=x
if nums[y]%2==0:
even_sum+=nums[y]
res.append(even_sum)
return res | sum-of-even-numbers-after-queries | Python | Easy understanding | based on just even odd | Mom94 | 0 | 3 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,967 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2605261/python3-or-easy-or-O(N) | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
s = 0
ans = []
for i in nums:
if i %2 == 0:
s += i
for v,i in queries:
if nums[i] % 2 != 0:
nums[i] += v
if nums[i] % 2 != 0:
ans.append(s)
else:
s += nums[i]
ans.append(s)
else:
s -= nums[i]
nums[i] += v
if nums[i] % 2 != 0:
ans.append(s)
else:
s += nums[i]
ans.append(s)
return ans | sum-of-even-numbers-after-queries | python3 | easy | O(N) | jayeshmaheshwari555 | 0 | 5 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,968 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2605039/python-code | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
answer=[]
currsum=0
#find sum of all even numbers in nums and store in a variable
for i in nums:
if i%2==0:
currsum+=i
for i in queries:
temp=nums[i[1]]
#subtract the value from stored sum if it is even
if temp%2==0:
currsum-=temp
nums[i[1]]+=i[0]
#add the new value to the stored sum if it is even
if nums[i[1]]%2==0:
currsum+=nums[i[1]]
answer.append(currsum)
return answer | sum-of-even-numbers-after-queries | python code | ayushigupta2409 | 0 | 13 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,969 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2605008/Python3-oror-99-Fasteroror-O(N%2BQ)-Time | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
evesum = 0
for num in nums:
if not num%2: evesum += num
res = []
for val, ind in queries:
if not nums[ind] % 2:
evesum -= nums[ind]
nums[ind] += val
if not nums[ind] % 2:
evesum += nums[ind]
res.append(evesum)
return res | sum-of-even-numbers-after-queries | Python3 || 99% Faster🚀|| O(N+Q) Time | Dewang_Patil | 0 | 6 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,970 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2604826/Python-Simple-Solution-or-O(n)-or-99-faster | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
running_even_sum = sum(i for i in nums if i % 2 == 0)
res = []
for val, idx in queries:
# Check if the initial value / final value at the particular index are even or not & based on that information manipulate the running even value sum.
init_even, init_val = (nums[idx] % 2 == 0), nums[idx]
nums[idx] += val
final_even = nums[idx] % 2 == 0
if init_even and final_even:
running_even_sum -= init_val
running_even_sum += nums[idx]
elif init_even:
running_even_sum -= init_val
elif final_even:
running_even_sum += nums[idx]
res.append(running_even_sum)
return res | sum-of-even-numbers-after-queries | ✅ Python Simple Solution | O(n) | 99% faster | Nk0311 | 0 | 9 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,971 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2604819/Python-easy-solution | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
answer = []
sum_even = sum([num for num in nums if num%2 == 0]) # sum of even numbers at first
for val, index in queries:
if nums[index] % 2 == 0: # subtract the current num from sum if it is even
sum_even -= nums[index]
nums[index] += val # add the val
if nums[index] % 2 == 0: # update sum if new value is even
sum_even += nums[index]
answer.append(sum_even) # apped the sum to answer
return answer | sum-of-even-numbers-after-queries | Python easy solution | remenraj | 0 | 5 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,972 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2604762/Simple-%22python%22-Solution | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
evnesum = sum(i for i in nums if i % 2 == 0)
for i in range(len(queries)):
val, id = queries[i]
if nums[id] % 2 == 0: evnesum -= nums[id]
nums[id] += val
if nums[id] % 2 == 0: evnesum += nums[id]
queries[i] = evnesum
return queries | sum-of-even-numbers-after-queries | Simple "python" Solution | anandchauhan8791 | 0 | 8 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,973 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2604652/Ezy-to-understand-python3-solution | class Solution:
# O(n+q) time, q --> len(queries), n --> len(nums)
# O(q) space,
# Approach: simulation,
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
even_sum = 0
ans = []
for num in nums:
if num % 2 == 0:
even_sum += num
for query in queries:
val, index = query
result = nums[index] + val
if nums[index] % 2 == 0:
even_sum -=nums[index]
if result % 2 == 0:
even_sum += result
nums[index] = result
ans.append(even_sum)
return ans | sum-of-even-numbers-after-queries | Ezy to understand python3 solution | destifo | 0 | 3 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,974 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2604610/Python3-Straightforward-Solution | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
res = []
sumEven = sum(n for n in nums if not n%2)
for q,i in queries:
if nums[i]%2 and q%2:
sumEven += nums[i]+q
elif not nums[i]%2 and q%2:
sumEven -= nums[i]
elif not nums[i]%2 and not q%2:
sumEven += q
res.append(sumEven)
nums[i] += q
return res | sum-of-even-numbers-after-queries | [Python3] Straightforward Solution | ruosengao | 0 | 5 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,975 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2604514/Python3-Runtime%3A-497-ms-faster-than-100.00-of-Python3-online-submissions | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
ret = []
evenSum = 0
for _ in nums:
if not _ & 1:
evenSum += _
for val, idx in queries:
num = nums[idx]
evenSum = evenSum - num if not num & 1 else evenSum
num += val
nums[idx] = num
evenSum = evenSum + num if not num & 1 else evenSum
ret.append(evenSum)
return ret | sum-of-even-numbers-after-queries | [Python3] Runtime: 497 ms, faster than 100.00% of Python3 online submissions | geka32 | 0 | 8 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,976 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2604472/Easy-Python-Solution-with-comments-oror-O(n)-Time-complexity | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
# Calculating the initial even_sum
even_sum = 0
for num in nums:
if(num % 2 == 0):
even_sum += num
ans = []
# Loop in each query
for val, idx in queries:
previous_val = nums[idx]
new_val = nums[idx] + val
nums[idx] = new_val
# If value before query was even then it should be subtracted from even_sum
if(previous_val % 2 == 0):
even_sum -= previous_val
# If value after query is even then it should be added to even_sum
if(new_val % 2 == 0):
even_sum += new_val
ans.append(even_sum)
return ans | sum-of-even-numbers-after-queries | Easy Python Solution with comments || O(n) Time complexity | vanshika_2507 | 0 | 6 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,977 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2604242/Easy-Python-Solution-or-Basic-intuition | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
ans = []
res = 0
for j in nums:
if j&1==0:
res += j
for i in queries:
temp = nums[i[1]]
nums[i[1]] = nums[i[1]] + i[0]
if temp&1:
if nums[i[1]]&1 == 0:
res += nums[i[1]]
else:
if nums[i[1]]&1 == 0:
res += i[0]
else:
res -= temp
ans.append(res)
return ans
``` | sum-of-even-numbers-after-queries | Easy Python Solution | Basic intuition | RajatGanguly | 0 | 5 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,978 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2604214/Python3-or-Easy-solutionor-Faster-97 | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
res, even = [], sum(num for num in nums if not num % 2)
for v, i in queries:
if not nums[i] % 2: even -= nums[i]
nums[i] += v
if not nums[i] % 2: even += nums[i]
res.append(even)
return res | sum-of-even-numbers-after-queries | ✅ Python3 | Easy solution| Faster 97% ✅ | abdoohossamm | 0 | 7 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,979 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2604083/Python3-or-O(n)-Easy-Solution | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
es = 0
arr = []
for i in nums:
if i%2 == 0:
es += i
for i in queries:
if((nums[i[1]]+i[0])%2 == 0 and nums[i[1]]%2 == 0):
es -= nums[i[1]]
es += nums[i[1]]+i[0]
elif (nums[i[1]]+i[0])%2 != 0 and nums[i[1]]%2 == 0:
es -= nums[i[1]]
elif (nums[i[1]]+i[0])%2 == 0 and nums[i[1]]%2 != 0:
es += nums[i[1]]+i[0]
nums[i[1]] = nums[i[1]]+i[0]
arr.append(es)
return arr | sum-of-even-numbers-after-queries | Python3 | O(n) Easy Solution | urmil_kalaria | 0 | 4 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,980 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2604064/GolangPython-O(N%2BQ)-time-or-O(Q)-space | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
evens_sum = 0
for item in nums:
if item % 2 == 0:
evens_sum+=item
answer = []
for add,i in queries:
if nums[i] % 2 == 0:
evens_sum-=nums[i]
nums[i]+=add
if nums[i] % 2 == 0:
evens_sum+=nums[i]
answer.append(evens_sum)
return answer | sum-of-even-numbers-after-queries | Golang/Python O(N+Q) time | O(Q) space | vtalantsev | 0 | 6 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,981 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2603905/Python-Simple-O(n)-Solution-or-Beats-90-time | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
res = []
total_sum = 0
for i in range(len(nums)):
if nums[i] % 2 == 0:
total_sum += nums[i]
for v, i in queries:
prev = nums[i]
nums[i] += v
if prev % 2 == 0:
if nums[i] % 2 == 0:
total_sum += (nums[i] - prev)
else:
total_sum -= prev
else:
if nums[i] % 2 == 0:
total_sum += nums[i]
res.append(total_sum)
return res | sum-of-even-numbers-after-queries | Python Simple O(n) Solution | Beats 90% time | dos_77 | 0 | 5 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,982 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2603749/SIMPLE-PYTHON3-SOLUTION-faster-and-easy-to-understand | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
even_sum = sum(v for v in nums if v % 2 == 0)
res: list[int] = []
for val, idx in queries:
if nums[idx] % 2 == 0:
even_sum -= nums[idx]
nums[idx] += val
if nums[idx] % 2 == 0:
even_sum += nums[idx]
res.append(even_sum)
return res | sum-of-even-numbers-after-queries | ✅✔ SIMPLE PYTHON3 SOLUTION ✅✔ faster and easy to understand | rajukommula | 0 | 6 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,983 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2603692/Python-Solution-or-Simulation-or-Brute-Force | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
ans=[]
evenSum=0
for num in nums:
if num%2==0:
evenSum+=num
for query in queries:
val=query[0]
index=query[1]
if nums[index]%2==0:
if (nums[index]+val)%2==0:
evenSum+=val
else:
evenSum-=nums[index]
else:
if (nums[index]+val)%2==0:
evenSum+=val+nums[index]
nums[index]+=val
# temp=0
# for num in nums:
# if num%2==0:
# temp+=num
ans.append(evenSum)
return ans | sum-of-even-numbers-after-queries | Python Solution | Simulation | Brute Force | Siddharth_singh | 0 | 7 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,984 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2603603/Sum-of-Even-Numbers-After-Queries-Python-or-Java | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
sm=0
for i in range(len(nums)):
if nums[i]%2==0:
sm+=nums[i]
lst=[]
for i in range(len(queries)):
prev=nums[queries[i][1]]
nums[queries[i][1]]+=queries[i][0]
curr=nums[queries[i][1]]
if prev%2==0:
if curr%2==0:
sm+=(curr-prev)
else:
sm-=prev
else:
if curr%2==0:
sm+=curr
lst.append(sm)
return lst | sum-of-even-numbers-after-queries | Sum of Even Numbers After Queries [ Python | Java ] | klu_2100031497 | 0 | 11 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,985 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2603574/Easy-Python-Accepted | class Solution:
def sumEvenAfterQueries(self, A: List[int], queries: List[List[int]]) -> List[int]:
S, Q = sum([i for i in A if i % 2 == 0]), []
for [v,i] in queries:
a = A[i]
A[i] += v
if a % 2 == 0:
if v % 2 == 0: S += v
else: S -= a
elif v % 2 == 1: S += A[i]
Q.append(S)
return Q | sum-of-even-numbers-after-queries | Easy Python Accepted ✅ | Khacker | 0 | 11 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,986 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2603562/Python3-Runtime%3A-510-ms-faster-than-99.12-or-Memory%3A-20.3-MB-less-than-97.08 | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
even_sum = 0
for n in nums:
if n & 1 == 0:
even_sum += n
ans = []
for val, idx in queries:
new_val = nums[idx] + val
if nums[idx] & 1 == 0:
even_sum -= nums[idx]
if new_val & 1 == 0:
even_sum += new_val
nums[idx] = new_val
ans.append(even_sum)
return ans | sum-of-even-numbers-after-queries | [Python3] Runtime: 510 ms, faster than 99.12% | Memory: 20.3 MB, less than 97.08% | anubhabishere | 0 | 6 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,987 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2603391/Python-or-Hash(dict)-or-Straight-solution-or | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
ans = []
h = {}
for i in range(len(nums)):
if nums[i]%2==0:
h[i] = nums[i]
s = sum(h.values())
for val,idx in queries:
nums[idx] = nums[idx]+val
if nums[idx]%2==0:
if idx in h:
s+=val
h[idx]+=val
else:
h[idx] = nums[idx]
s+=h[idx]
else:
if idx in h:
s-=h[idx]
del h[idx]
ans.append(s)
return ans | sum-of-even-numbers-after-queries | Python | Hash(dict) | Straight solution | | Brillianttyagi | 0 | 8 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,988 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2603337/Python-or-O(n)-or-Easy-and-simple-solution-explained | class Solution(object):
def sumEvenAfterQueries(self, nums, queries):
"""
:type nums: List[int]
:type queries: List[List[int]]
:rtype: List[int]
"""
current_sum = 0
res = []
#Summing all the even numbers in num
for num in nums:
if num % 2 == 0:
current_sum += num
for query in queries:
val, index = query
#changing the sum of even numbers only if nums[index] and val are
#even + even = even or odd + odd = even, we increase the sum with val or nums[index] + val
#even + odd = odd, we decrease the sum with nums[index] no longer even
if nums[index] % 2 == 0 and val % 2 == 0:
current_sum += val
elif nums[index] % 2 == 1 and val % 2 == 1:
current_sum += nums[index] + val
elif nums[index] % 2 == 0:
current_sum -= nums[index]
#appending the updated sum
res.append(current_sum)
#updating the nums[index] with val as required per query
nums[index] += val
return res | sum-of-even-numbers-after-queries | Python | O(n) | Easy and simple solution explained | iLikeBreathing | 0 | 13 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,989 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2144005/python-3-oror-simple-O(n)-solution | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
evenSum = sum(num for num in nums if not num % 2)
answer = []
for val, i in queries:
if not nums[i] % 2:
if not val % 2:
evenSum += val
else:
evenSum -= nums[i]
elif val % 2:
evenSum += nums[i] + val
answer.append(evenSum)
nums[i] += val
return answer | sum-of-even-numbers-after-queries | python 3 || simple O(n) solution | dereky4 | 0 | 58 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,990 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/1993750/Python-Solution-or-Over-90-Faster-or-Conditional-Arithmetic-Based-or-Clean-Code | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
total = sum(n for n in nums if not (n & 1))
store = []
for val,idx in queries:
ogVal = nums[idx]
nums[idx] += val
if not (ogVal & 1):
total -= ogVal
if not (nums[idx] & 1):
total += nums[idx]
store.append(total)
return store | sum-of-even-numbers-after-queries | Python Solution | Over 90% Faster | Conditional Arithmetic Based | Clean Code | Gautam_ProMax | 0 | 39 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,991 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/1986072/PYTHON-SOL-oror-EXPLAINED-oror-LINEAR-SOL-oror-COMMENTED-oror-EASY-oror | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
# queries[i] = [val,index]
# for each query i
# nums[index] = nums[index] + bal
# print the sum of the even values of nums
# nums = [1,2,3,4] , queries = [[1,0],[-3,1],[-4,0],[2,3]]
# output = [8,6,2,4]
# add 1 to index 0 -> arr = [2,2,3,4]
# add -3 to index 1 -> arr = [2,-1,3,4]
# add -4 to index 0 -> arr = [-2,-1,3,4]
# add 2 to index 3 -> arr = [-2,-1,3,6]
# first calc even sums = 6
# now check for only the index
ans = []
summ = 0
for i in nums :
if i % 2 == 0: summ += i
for val,index in queries:
if nums[index] %2 == 0: summ -= nums[index]
nums[index] += val
if nums[index] %2 == 0: summ += nums[index]
ans.append(summ)
return ans | sum-of-even-numbers-after-queries | PYTHON SOL || EXPLAINED || LINEAR SOL || COMMENTED || EASY || | reaper_27 | 0 | 38 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,992 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/1445985/python-or-better-than-99 | class Solution:
def sumEvenAfterQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:
es=0
for i in arr:
if i%2==0:
es+=i
ans=[]
print(es)
for i,j in queries:
if (arr[j]%2==0 and i%2==0):
es+=i
arr[j]+=i
elif (arr[j]%2!=0 and i%2!=0):
arr[j]+=i
es+=arr[j]
elif (arr[j]%2==0):
es-=arr[j]
arr[j]+=i
else:
arr[j]+=i
ans.append(es)
return ans | sum-of-even-numbers-after-queries | python | better than 99% | heisenbarg | 0 | 136 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,993 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/1415519/Detailed-Explanation-Keep-track-of-even_sum-at-all-times-%3A) | class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
even_sum = sum(x for x in nums if x % 2 == 0)
answer = []
for val, idx in queries:
if nums[idx] % 2 == 0:
# his old value was a part of even_sum!
# now his value will change so remove him!
even_sum -= nums[idx]
nums[idx] += val
if nums[idx] % 2 == 0:
# his new value is part of even_sum!
even_sum += nums[idx]
answer.append(even_sum)
return answer | sum-of-even-numbers-after-queries | Detailed Explanation Keep track of even_sum at all times :) | yozaam | 0 | 51 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,994 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/924715/Python%3A-O(N)-Time-%2B-Space-(No-CounterZip) | class Solution:
def sumEvenAfterQueries(self, A: List[int], queries: List[List[int]]) -> List[int]:
output = []
even_sum = sum(filter(lambda x: x%2==0, A))
# Linear Scan
# the even_sum changes depending on the parity of the element before
# and after the new value is added
for i in range(len(queries)):
val = queries[i][0]
index = queries[i][1]
before = A[index]
after = A[index] + val
if before%2==0 and after%2==0:
even_sum += val
elif before%2==0 and after%2!=0:
even_sum -= before
elif before%2!=0 and after%2==0:
even_sum += after
elif before%2!=0 and after%2!=0:
pass
A[index] = after
output.append(even_sum)
return output | sum-of-even-numbers-after-queries | Python: O(N) Time + Space (No Counter/Zip) | JuanTheDoggo | 0 | 120 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,995 |
https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/751235/Fast-and-easy-python-solution | class Solution:
def sumEvenAfterQueries(self, A: List[int], queries: List[List[int]]) -> List[int]:
s=0
a=[0]*len(queries)
for i in A:
if i%2==0:
s+=i
for i in range(len(queries)):
indx=queries[i][1]
val=queries[i][0]
if val%2==0:
if A[indx]%2==0:
s+=val
else:
if A[indx]%2==0:
s-=A[indx]
else:
s+=A[indx]+val
A[indx]+=val
a[i]=s
return a | sum-of-even-numbers-after-queries | Fast and easy python solution | NvsYashwanth | 0 | 107 | sum of even numbers after queries | 985 | 0.682 | Medium | 15,996 |
https://leetcode.com/problems/interval-list-intersections/discuss/646939/Python-O(m%2Bn)-by-two-pointers.w-Graph | class Solution:
def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
idx_a, idx_b = 0, 0
size_a, size_b = len(A), len(B)
intersection = []
# Scan each possible interval pair
while idx_a < size_a and idx_b < size_b :
# Get start-time as well as end-time
start_a, end_a = A[idx_a]
start_b, end_b = B[idx_b]
# Compute common start time and end time for current interval pair
common_start = max( start_a, start_b )
common_end = min( end_a, end_b )
if common_start <= common_end:
# Find one common overlapped interval
intersection.append( [common_start, common_end] )
if end_a <= end_b:
# Try next interval of A
idx_a += 1
else:
# Try next interval of B
idx_b += 1
return intersection | interval-list-intersections | Python O(m+n) by two-pointers.[w/ Graph] | brianchiang_tw | 3 | 264 | interval list intersections | 986 | 0.714 | Medium | 15,997 |
https://leetcode.com/problems/interval-list-intersections/discuss/2215014/Python-or-Using-two-pointers-or-99-faster-submissions-with-comments | class Solution:
def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:
res = []
s,e = 0,1
i,j = 0,0
while i < len(firstList) and j < len(secondList):
a = firstList[i] # fetching the interval
b = secondList[j] # fetching the interval
# checking for the overlapping
if b[s] <= a[e] and b[e] >= a[s]:
# fetching the intersection point
intersectionPoint = [max(a[s],b[s]),min(a[e],b[e])]
res.append(intersectionPoint) # appending intersectionPoint into result list
if a[e] > b[e]:
j += 1
else:
i += 1
return res | interval-list-intersections | Python | Using two pointers | 99% faster submissions with comments | __Asrar | 2 | 82 | interval list intersections | 986 | 0.714 | Medium | 15,998 |
https://leetcode.com/problems/interval-list-intersections/discuss/1854925/Python-easy-to-read-and-understand-or-two-pointers | class Solution:
def intervalIntersection(self, a: List[List[int]], b: List[List[int]]) -> List[List[int]]:
ans = []
i, j = 0, 0
while i < len(a) and j < len(b):
ai, aj = a[i]
bi, bj = b[j]
if bj >= ai and aj >= bi:
ans.append([max(ai, bi), min(aj, bj)])
if bj >= aj:
i += 1
else:
j += 1
return ans | interval-list-intersections | Python easy to read and understand | two pointers | sanial2001 | 2 | 84 | interval list intersections | 986 | 0.714 | Medium | 15,999 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.