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/rotting-oranges/discuss/2771844/Chinese-Explanation-%2B-Python | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
# bfs
# 1. 定位rotten orange的坐标,并且save in visited and queue
# 2. start bfs
m,n = len(grid), len(grid[0])
queue = collections.deque()
# locate rotten orange
for i in range(m):
for j in range(n):
if grid[i][j] == 2:
queue.append([i,j])
def addNums(grid, i, j):
# empty cell, so nothing to do at this cell
# rotten cell, nothing to do
if i<0 or j<0 or i>=m or j>=n or grid[i][j] == 2 or grid[i][j] == 0:
return
if grid[i][j] == 1:
# 转换fresh orange into rotten orange
grid[i][j] = 2
queue.append([i,j])
# use bfs to change fresh orange near rotten orange into rotten orange
# layer by layer
# 进入以下while loop,会将初始的rotten orange当作第一步
# 但是我们是从第0步开始计算,所以steps初始值为-1
steps = -1
while queue:
for i in range(len(queue)):
r,c = queue.popleft()
addNums(grid, r+1, c)
addNums(grid, r-1, c)
addNums(grid, r, c+1)
addNums(grid, r, c-1)
steps += 1
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
return -1
if steps == -1: return 0
return steps | rotting-oranges | Chinese Explanation + Python | Michael_Songru | 0 | 2 | rotting oranges | 994 | 0.525 | Medium | 16,200 |
https://leetcode.com/problems/rotting-oranges/discuss/2749731/Efficient-Python-BFS-with-comments | class Solution:
'''
BFS approach
'''
def orangesRotting(self, grid: List[List[int]]) -> int:
queue = deque()
minutes, fresh = 0, 0
# Populate the initial queue with coordinates of 2's
# Count 1's as fresh
for i, row in enumerate(grid):
for j, val in enumerate(row):
if val == 2:
queue.append((i, j))
elif val == 1:
fresh += 1
# Change all 1's to 2, or exhaust the queue while trying
while fresh and queue:
# Process the CURRENT contents of the queue (not any nodes added during this minute)
for _ in range(len(queue)):
i, j = queue.popleft()
# We do the four directions inline to minimize boundary checking
i -= 1 # above
if i >= 0 and grid[i][j] == 1:
grid[i][j] = 2
queue.append((i, j))
fresh -= 1
i += 2 # below
if i < len(grid) and grid[i][j] == 1:
grid[i][j] = 2
queue.append((i, j))
fresh -= 1
i -= 1 # original
j -= 1 # left
if j >= 0 and grid[i][j] == 1:
grid[i][j] = 2
queue.append((i, j))
fresh -= 1
j += 2 # right
if j < len(grid[0]) and grid[i][j] == 1:
grid[i][j] = 2
queue.append((i, j))
fresh -= 1
minutes += 1
return -1 if fresh else minutes | rotting-oranges | Efficient Python BFS with comments | decsery | 0 | 12 | rotting oranges | 994 | 0.525 | Medium | 16,201 |
https://leetcode.com/problems/rotting-oranges/discuss/2735774/Python-Easy-Solution-Time%3A-O(n)-Space%3A-O(n) | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
# record rotten and fresh oranges
rottens = []
freshs = []
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] == 1:
freshs.append((r,c))
elif grid[r][c] == 2:
rottens.append((r,c))
# check the edge cases
# (1)(2)()
if freshs and not rottens:
return -1
elif rottens and not freshs:
return 0
elif not rottens and not freshs:
return 0
total_orange = len(rottens) + len(freshs)
mom = 0
# rotting oranges
new_rottens = []
total_rottens = rottens.copy()
while len(total_rottens) != total_orange:
mom += 1
# BFS
for r, c in rottens:
# up
if r-1>=0:
if grid[r-1][c] == 1:
grid[r-1][c] = 2
new_rottens.append((r-1,c))
# right
if c+1<=len(grid[0])-1:
if grid[r][c+1] == 1:
grid[r][c+1] = 2
new_rottens.append((r,c+1))
# down
if r+1<=len(grid)-1:
if grid[r+1][c] == 1:
grid[r+1][c] = 2
new_rottens.append((r+1,c))
# left
if c-1>=0:
if grid[r][c-1] == 1:
grid[r][c-1] = 2
new_rottens.append((r,c-1))
# check if there is no change in this round, means it's not possible
if not new_rottens:
return -1
total_rottens += new_rottens
rottens = new_rottens.copy()
new_rottens = []
return mom | rotting-oranges | Python Easy Solution Time: O(n) Space: O(n) | chienhsiang-hung | 0 | 9 | rotting oranges | 994 | 0.525 | Medium | 16,202 |
https://leetcode.com/problems/rotting-oranges/discuss/2707117/Simple-python-oror-beats-99-memory | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
mins=0 # store result
dirs = [(0,1),(1,0),(-1,0), (0,-1)] # movement directions
rotten_set = set()
total_r = 0 # total rotten in any minute
total_o = 0 # total oranges
m = len(grid)
n = len(grid[0])
for i in range(m):
for j in range(n):
if grid[i][j] == 2:
rotten_set.add((i, j))
total_r+=1
if grid[i][j] != 0:
total_o+=1
while mins <= m*n:
if total_r == total_o:
return mins
temp_set = set()
for o in rotten_set:
for item in dirs:
x = o[0]+item[0]
y = o[1]+item[1]
if x >= 0 and x < m and y >=0 and y < n and grid[x][y] == 1:
grid[x][y] = 2
temp_set.add((x,y))
total_r+=len(temp_set) # add newly rotten to total rotten
rotten_set = temp_set # next rotten_set to search
mins+=1
return -1 | rotting-oranges | Simple python || beats 99% memory | user1090g | 0 | 6 | rotting oranges | 994 | 0.525 | Medium | 16,203 |
https://leetcode.com/problems/rotting-oranges/discuss/2687990/Simple-DFS-like-Solution-with-explanation | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
def Rotting(i, j): # function to make oranges rotten
if i >= 0 and i < len(grid) and j >= 0 and j < len(grid[0]) and grid[i][j] == 1:
grid[i][j] = 2
count = 0
prev = copy.deepcopy(grid) # use deepcopy here to prevent prev from changing when modifying grid
while self.iffresh(grid): # if there's fresh orange in grid then start process of rotting
for n in range(len(grid)):
for m in range(len(grid[0])):
if prev[n][m] == 2: # when current orange is rotten, make its neighbor rotting
for (a,b) in [(1,0),(0,1),(-1,0),(0,-1)]:
Rotting(n+a,m+b)
count += 1 # when the whole grid get rotten, we count for 1 time
# if there is fresh orange in grid(which is be detected by the while line)
# but the grid isn't different from prev, mean there are unrottable oranges, return -1
if prev == grid:
return -1
else:
prev = copy.deepcopy(grid) # memory current grid for next round comparison
return count
def iffresh(self, grid): # function to detect if there's any fresh orange in grid
for row in grid:
for n in row:
if n == 1: return True
return False | rotting-oranges | Simple DFS-like Solution with explanation | AustinHuang823 | 0 | 30 | rotting oranges | 994 | 0.525 | Medium | 16,204 |
https://leetcode.com/problems/rotting-oranges/discuss/2673232/python-! | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
q = deque()
m,n = len(grid), len(grid[0])
oranges = set()
for i in range(m):
for j in range(n):
if grid[i][j]==2:
q.append((i,j,0))
elif grid[i][j]==1:
oranges.add((i,j))
time = 0
visited = set()
dirs = [(0,1),(1,0),(-1,0),(0,-1)]
while q:
i,j, time = q.popleft()
visited.add((i,j))
for dx,dy in dirs:
x,y = i+dx, j+dy
if 0<=x<m and 0<=y<n and (x,y) not in visited and grid[x][y]==1:
grid[x][y]=2
if (x,y) in oranges:
oranges.remove((x,y))
q.append((x,y, time+1))
return -1 if len(oranges)>0 else time | rotting-oranges | python ! | sanjeevpathak | 0 | 6 | rotting oranges | 994 | 0.525 | Medium | 16,205 |
https://leetcode.com/problems/rotting-oranges/discuss/2666239/python-BFS-with-readable-explanation | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
minutes = 0
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
rotten = set()
fresh_count = 0
infected = set()
# go thru each cell to find the position of 2s, count the 1s
for row in range(rows):
for col in range(cols):
if grid[row][col] == 1:
fresh_count += 1
if grid[row][col] == 2:
rotten.add((row, col))
# infect the fresh ones using a bfs function, count the loop
def bfs(batch: List[tuple]):
queue = collections.deque()
queue.append(batch)
nonlocal minutes
while queue:
batch = queue.popleft()
next_batch = set()
infected.update(batch)
for row, col in batch:
for dr, dc in directions:
r, c = row + dr, col + dc
if r in range(rows) and c in range(cols) and grid[r][c] == 1 and (r, c) not in infected:
infected.add((r, c))
next_batch.add((r, c))
if next_batch:
queue.append(next_batch)
minutes += 1
bfs(rotten)
# check if all fresh ones were infected
return minutes if len(infected - rotten) == fresh_count else -1 | rotting-oranges | python BFS with readable explanation | deezeey | 0 | 15 | rotting oranges | 994 | 0.525 | Medium | 16,206 |
https://leetcode.com/problems/rotting-oranges/discuss/2622386/python3-oror-easy-oror-bfs-solution | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
visited=[[0]*len(grid[0]) for i in range(len(grid))]
rowSize=len(grid)
colSize=len(grid[0])
q=collections.deque()
for r in range(rowSize):
for c in range(colSize):
if grid[r][c]==2:
q.append((r,c,0))
visited[r][c]=2
else:
visited[r][c]=0
tm=0
while q:
r,c,t=q.popleft()
tm=max(tm,t)
for i,j in [[-1,0],[1,0],[0,-1],[0,1]]:
nrow=r+i
ncol=c+j
if nrow>=0 and nrow<rowSize and ncol>=0 and ncol<colSize and visited[nrow][ncol]==0 and grid[nrow][ncol]==1:
q.append((nrow,ncol,t+1))
visited[nrow][ncol]=2
for i in range(rowSize):
for j in range(colSize):
if visited[i][j]!=2 and grid[i][j]==1:
return -1
return tm | rotting-oranges | python3 || easy || bfs solution | _soninirav | 0 | 11 | rotting oranges | 994 | 0.525 | Medium | 16,207 |
https://leetcode.com/problems/rotting-oranges/discuss/2610530/Simple-Python-solution-(faster-than-90)-with-detailed-explanation.-easy-to-understand. | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
M = len(grid) # num rows
N = len(grid[0]) # num cols
q = [] # queue
visited = [ [0]*N for _ in range(M)] #2D list
n_fresh = [0] # global variable (pointer)
def update(i,j):
if visited[i][j] == 0 and grid[i][j] == 1:
q.append((i,j))
visited[i][j] = 1
grid[i][j] = 2
n_fresh[0] -= 1
def expand4(i,j):
if i>0: update(i-1,j)
if j>0: update(i,j-1)
if i+1<M: update(i+1,j)
if j+1<N: update(i,j+1)
for i in range(M):
for j in range(N):
if grid[i][j] == 2:
q.append((i,j))
visited[i][j] = 1
elif grid[i][j] == 1:
n_fresh[0] +=1
step = 0
if n_fresh[0] == 0: return 0
while q:
for _ in range(len(q)):
i,j = q.pop(0)
expand4(i,j)
step+= 1
if n_fresh[0] == 0: return(step)
return -1 | rotting-oranges | Simple Python solution (faster than 90%) with detailed explanation. easy to understand. | alexion1 | 0 | 37 | rotting oranges | 994 | 0.525 | Medium | 16,208 |
https://leetcode.com/problems/rotting-oranges/discuss/2600535/BREADTH-FIRST-SEARCH-APPROACH | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
"""
Each cell can have one of 3 values
0 - empty cell
1 - fresh orange
2 - rotten orange
output - time to turn all fresh oranges to rotten if possible
else return -1
# use a queue data structure which will be a level order traversal or
a breadth first search approach
1. Get the position of all rotten oranges time 0
2. Check the neighbors of these rotten oranges and commute them to rotten
3 We have to also get the number of fresh oranges which will help us to know if
all oranges are rotten or not,
"""
rows, cols = len(grid), len(grid[0])
#1. GET ALL THE FRESH ORANGES
fresh = 0
for m in range(len(grid)):
for n in range(len(grid[0])):
if grid[m][n] == 1:
fresh += 1
#2. GET THE POSITION OF ALL ROTTEN ORANGES
queue = collections.deque()
for m in range(len(grid)):
for n in range(len(grid[0])):
if grid[m][n] == 2:
queue.append((m, n))
directions = [(0, 1), (0, -1), (-1, 0), (1, 0)]
time = 0
while queue and fresh > 0:
queueLength = len(queue)
for _ in range(queueLength):
row, col = queue.popleft()
for dr, dc in directions:
if (0<=row+dr<rows and 0<=col+dc<cols and grid[row+dr][col+dc] == 1):
grid[row+dr][col+dc] = 2
queue.append((row+dr, col+dc))
fresh -= 1
time += 1
return time if fresh == 0 else -1 | rotting-oranges | BREADTH FIRST SEARCH APPROACH | leomensah | 0 | 42 | rotting oranges | 994 | 0.525 | Medium | 16,209 |
https://leetcode.com/problems/rotting-oranges/discuss/2541032/Python3-Solution-or-BFS | class Solution:
def orangesRotting(self, grid):
n, m = len(grid), len(grid[0])
q, ans = collections.deque(), -1
count = sum(row.count(1) for row in grid)
for i in range(n):
for j in range(m):
if grid[i][j] == 2:
q.append((i, j))
while q:
k = len(q)
for i in range(k):
row, col = q.popleft()
for r, c in ((0,1),(0,-1),(1,0),(-1,0)):
if 0 <= row + r < n and 0 <= col + c < m and grid[row + r][col + c] == 1:
grid[row + r][col + c] = 2
q.append((row + r, col + c))
count -= 1
ans += 1
return max(0, ans) if count == 0 else -1 | rotting-oranges | ✔ Python3 Solution | BFS | satyam2001 | 0 | 44 | rotting oranges | 994 | 0.525 | Medium | 16,210 |
https://leetcode.com/problems/rotting-oranges/discuss/2537000/Python-oror-BFS-oror-Queue-oror-97-fast | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
q = []
m = len(grid)
n = len(grid[0])
seen = set()
def makerot(i,j,q):
if (i,j) in seen:
return
seen.add((i,j))
if i+1 < m and (i+1,j) not in seen:
if grid[i+1][j] == 1:
grid[i+1][j] = 2
q.append((i+1,j))
if i-1 >= 0 and (i-1,j) not in seen:
if grid[i-1][j] == 1:
grid[i-1][j] = 2
q.append((i-1,j))
if j+1 < n and (i,j+1) not in seen:
if grid[i][j+1] == 1:
grid[i][j+1] = 2
q.append((i,j+1))
if j-1 >= 0 and (i,j-1) not in seen:
if grid[i][j-1] == 1:
grid[i][j-1] = 2
q.append((i,j-1))
return
one = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 2:
q.append((i,j))
if grid[i][j] == 1:
one +=1
if not q and one:
return -1
if not q:
return 0
count = -1
while q:
size = len(q)
for _ in range(size):
i,j = q.pop(0)
if grid[i][j] == 2:
makerot(i,j,q)
# print(grid,q,seen)
count += 1
# print(grid)
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
return -1
return count | rotting-oranges | Python || BFS || Queue || 97% fast | 1md3nd | 0 | 70 | rotting oranges | 994 | 0.525 | Medium | 16,211 |
https://leetcode.com/problems/rotting-oranges/discuss/2470825/Clean-Fast-Python3-or-BFS | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
# for each fresh orange, bfs to nearest rotten one. Take max of these distances
rows, cols = len(grid), len(grid[0])
dirs = [(0, -1), (-1, 0), (0, 1), (1, 0)]
def bfs(start_row, start_col):
nonlocal rows, cols, dirs
q, seen = deque([[(start_row, start_col), 0]]), set([(start_row, start_col)])
while q:
(row, col), mins = q.pop()
for r, c in dirs:
nei_row, nei_col = row + r, col + c
if -1 < nei_row < rows and -1 < nei_col < cols:
if grid[nei_row][nei_col] == 2:
return mins + 1
if grid[nei_row][nei_col] == 1 and (nei_row, nei_col) not in seen:
seen.add((nei_row, nei_col))
q.appendleft([(nei_row, nei_col), mins + 1])
return -1
minutes = 0
for row in range(rows):
for col in range(cols):
if grid[row][col] == 1:
mins_to_rotten = bfs(row, col)
if mins_to_rotten == -1:
return -1
minutes = max(minutes, mins_to_rotten)
return minutes | rotting-oranges | Clean, Fast Python3 | BFS | ryangrayson | 0 | 47 | rotting oranges | 994 | 0.525 | Medium | 16,212 |
https://leetcode.com/problems/rotting-oranges/discuss/2417509/Python3-9792-Simple-Solution-w-Explanation | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
changing = True
infected = 1
# Loop through mxn changing grid entries until no entries are changed on a loop
while changing:
infected += 1
changing = False
# Loop through the whole grid
for i in range(m):
for j in range(n):
# If an entry is infected:
# -> check the surrounding squares. If they are unrotten:
# -> Set them to infected + 1, and note that something has changed this iteration (minute)
# - > This prevents them being recognized as rotten until the next loop through
# Otherwise, they would spread rot before they should be able to
if grid[i][j] == infected:
if i > 0:
if grid[i-1][j] == 1:
grid[i-1][j] = infected + 1
changing = True
if j > 0:
if grid[i][j-1] == 1:
grid[i][j-1] = infected +1
changing = True
if i < m-1:
if grid[i+1][j] == 1:
grid[i+1][j] = infected + 1
changing = True
if j < n-1:
if grid[i][j+1] == 1:
grid[i][j+1] = infected + 1
changing = True
# Once no changes have been made, check to see if there are unrotten oranges anywhere
# that couldn't have been reached. If there are, return -1
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
return -1
# If all oranges were infected, return the infected iterable minus two (since it started there)
return infected - 2 | rotting-oranges | [Python3] 97%/92% Simple Solution w Explanation | connorthecrowe | 0 | 56 | rotting oranges | 994 | 0.525 | Medium | 16,213 |
https://leetcode.com/problems/rotting-oranges/discuss/2337831/Python3-knapsack-solution-with-mega-comprehension | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
rotten = frozenset((x, y) for y, row in enumerate(grid) for x, cell in enumerate(row) if cell == 2)
length = len(grid)
width = len(grid[0])
minutes = 0
while True:
neighbors = (cell for x, y in rotten for cell in ((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)))
rotten = frozenset((x, y) for x, y in neighbors if 0 <= x < width and 0 <= y < length and grid[y][x] == 1)
for x, y in rotten:
grid[y][x] = 2
if not rotten:
break
minutes += 1
return -1 if any(cell == 1 for row in grid for cell in row) else minutes | rotting-oranges | Python3 knapsack solution with mega comprehension | SkookumChoocher | 0 | 38 | rotting oranges | 994 | 0.525 | Medium | 16,214 |
https://leetcode.com/problems/rotting-oranges/discuss/2255567/Python-Readable-and-easy-to-understand-solution-with-explanation-using-only-a-queue | class Solution:
EMPTY = 0
FRESH = 1
ROTTEN = 2
ADJACENT_DIRECTIONS = [(-1, 0), (+1, 0), (0, -1), (0, +1)]
def orangesRotting(self, grid: List[List[int]]) -> int:
self.grid = grid
self.rows, self.columns = len(grid), len(grid[0])
rotten_coordinates_queue = self._get_rotten_oranges_coordinates_queue()
minute = -1
while len(rotten_coordinates_queue) > 0:
minute, row_i, column_i = rotten_coordinates_queue.popleft()
for adj_row_i, adj_col_i in self._get_adjacent_cells(row_i, column_i):
if self.grid[adj_row_i][adj_col_i] == Solution.FRESH:
self.grid[adj_row_i][adj_col_i] = Solution.ROTTEN
rotten_coordinates_queue.append((minute+1, adj_row_i, adj_col_i))
no_fresh_left = all(all(orange != Solution.FRESH for orange in row) for row in self.grid)
if not no_fresh_left:
return -1
return minute if minute >= 0 else 0
def _get_rotten_oranges_coordinates_queue(self):
rotten_oranges_coordinates = collections.deque()
for row_i in range(self.rows):
for column_i in range(self.columns):
if self.grid[row_i][column_i] == Solution.ROTTEN:
rotten_oranges_coordinates.append((0, row_i, column_i))
return rotten_oranges_coordinates
def _get_adjacent_cells(self, row_i, column_i) -> List[Tuple[int, int]]:
return [
(row_i + dir[0], column_i + dir[1])
for dir in Solution.ADJACENT_DIRECTIONS
if 0 <= row_i + dir[0] < self.rows and 0 <= column_i + dir[1] < self.columns
] | rotting-oranges | [Python] Readable and easy to understand solution with explanation, using only a queue | julenn | 0 | 67 | rotting oranges | 994 | 0.525 | Medium | 16,215 |
https://leetcode.com/problems/rotting-oranges/discuss/2254223/Python-Basic-BFS-91-Less-Memory | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
def searchFreshAndRotten(grid):
freshes = 0
rots = []
for row in range(len(grid)):
for col in range(len(grid[row])):
if grid[row][col] == 1:
freshes += 1
elif grid[row][col] == 2:
rots.append((row, col))
return freshes, rots
freshes, nexts = searchFreshAndRotten(grid)
len_r, len_c = len(grid), len(grid[0])
minute = 0
while freshes > 0 and len(nexts) > 0:
rots = []
for row, col in nexts:
for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
x, y = row + dx, col + dy
if x < 0 or x == len_r or y < 0 or y == len_c:
continue
if grid[x][y] == 1:
grid[x][y] = 2
rots.append((x, y))
freshes -= 1
nexts = rots
minute += 1
if freshes <= 0:
return minute
else:
return -1 | rotting-oranges | Python Basic BFS 91% Less Memory | codeee5141 | 0 | 54 | rotting oranges | 994 | 0.525 | Medium | 16,216 |
https://leetcode.com/problems/rotting-oranges/discuss/2116219/BFS-Solution-Python-(Time-87-Space-99) | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
# Breadth-first search
m, n = len(grid), len(grid[0])
minute = 0
qRotten, freshCount = [], 0
for i in range(m):
for j in range(n):
# We store rotten orange positions
if grid[i][j] == 2:
qRotten.append([i,j])
# We store the count of fresh oranges
elif grid[i][j] == 1:
freshCount += 1
if freshCount == 0:
return 0
# Define all directions (up, down, left, and right) 东西南北
direction = [[0, 1], [0, -1], [1, 0], [-1, 0]]
while len(qRotten) != 0:
minute += 1
for _ in range(len(qRotten)):
# Fill in the body here
rottenOrange = qRotten.pop(0)
# Search in all four directions to look for fresh oranges
for i in range(4):
neighborOrange = [rottenOrange[0] + direction[i][0], rottenOrange[1] + direction[i][1]]
# If not an edge
if neighborOrange[0] >= 0 and neighborOrange[0] < m and neighborOrange[1] >= 0 and neighborOrange[1] < n:
# If the orange is fresh
if grid[neighborOrange[0]][neighborOrange[1]] == 1:
# Turn the fresh orange into a rotten orange
grid[neighborOrange[0]][neighborOrange[1]] = 2
# Remove it from the count of fresh oranges
freshCount -= 1
# Add it to the queue of rotten oranges
qRotten.append(neighborOrange)
if freshCount == 0:
return minute
return -1 | rotting-oranges | BFS Solution - Python (Time 87%, Space 99%) | tylerpruitt | 0 | 92 | rotting oranges | 994 | 0.525 | Medium | 16,217 |
https://leetcode.com/problems/rotting-oranges/discuss/1988876/ororPYTHON-SOL-oror-VERY-EASY-oror-WELL-EXPLAINED-oror-JUST-AS-QUESTION-DEMANDS-oror-BFS-oror | class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
# 0 = means empty
# 1 = fresh orange
# 2 = rotten orange
# every minute any every rotten orange infects its adjacent fresh orange
# min no of minutes to make all rotten else -1
fresh_oranges = 0
rotten_oranges = []
rows = len(grid)
cols = len(grid[0])
steps = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == 1:
fresh_oranges += 1
elif grid[r][c] == 2:
rotten_oranges.append((r,c))
if fresh_oranges == 0: return 0
while rotten_oranges:
tmp = []
while rotten_oranges:
r,c = rotten_oranges.pop(0)
paths = ((r+1,c),(r-1,c),(r,c+1),(r,c-1))
for x,y in paths:
if 0<=x<rows and 0<=y<cols and grid[x][y] == 1:
grid[x][y] = 2
fresh_oranges -=1
if fresh_oranges == 0: return steps + 1
tmp.append((x,y))
steps += 1
rotten_oranges = tmp
return -1 | rotting-oranges | ||PYTHON SOL || VERY EASY || WELL EXPLAINED || JUST AS QUESTION DEMANDS || BFS || | reaper_27 | 0 | 77 | rotting oranges | 994 | 0.525 | Medium | 16,218 |
https://leetcode.com/problems/minimum-number-of-k-consecutive-bit-flips/discuss/2122927/Python-O(N)-S(N)-Queue-solution | class Solution:
def minKBitFlips(self, nums: List[int], k: int) -> int:
ans = 0
q = []
for i in range(len(nums)):
if len(q) % 2 == 0:
if nums[i] == 0:
if i+k-1 <= len(nums)-1:
ans += 1
q.append(i+k-1)
else:
return -1
else:
if nums[i] == 1:
if i+k-1 <= len(nums)-1:
ans += 1
q.append(i+k-1)
else:
return -1
if q:
if q[0] == i:
q.pop(0)
return ans | minimum-number-of-k-consecutive-bit-flips | Python O(N) S(N) Queue solution | DietCoke777 | 0 | 64 | minimum number of k consecutive bit flips | 995 | 0.512 | Hard | 16,219 |
https://leetcode.com/problems/minimum-number-of-k-consecutive-bit-flips/discuss/1266069/Python3-greedy | class Solution:
def minKBitFlips(self, nums: List[int], k: int) -> int:
ans = flip = 0
queue = deque()
for i, x in enumerate(nums):
if queue and i == queue[0]:
flip ^= 1
queue.popleft()
if x == flip:
if len(nums) - i < k: return -1
ans += 1
flip ^= 1
queue.append(i+k)
return ans | minimum-number-of-k-consecutive-bit-flips | [Python3] greedy | ye15 | 0 | 186 | minimum number of k consecutive bit flips | 995 | 0.512 | Hard | 16,220 |
https://leetcode.com/problems/number-of-squareful-arrays/discuss/1375586/python-simple-backtracking.-20ms | class Solution(object):
def numSquarefulPerms(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def dfs(temp,num,count = 0):
if len(num)==0:
return count+1
for i in xrange(len(num)):
if (i>0 and num[i]==num[i-1]) or (len(temp) > 0 and math.sqrt(num[i] + temp[-1]) % 1 != 0):
continue
count = dfs(temp+[num[i]],num[:i]+num[i+1:],count)
return count
nums.sort()
res = dfs([],nums)
return res | number-of-squareful-arrays | python simple backtracking. 20ms | leah123 | 1 | 305 | number of squareful arrays | 996 | 0.492 | Hard | 16,221 |
https://leetcode.com/problems/number-of-squareful-arrays/discuss/1314226/Python3-TSP | class Solution:
def numSquarefulPerms(self, nums: List[int]) -> int:
@cache
def fn(v, mask):
"""Return squareful arrays given prev value and mask."""
if not mask: return 1
ans = 0
seen = set()
for i, x in enumerate(nums):
if x not in seen and (mask == (1 << len(nums)) - 1 or mask & (1 << i) and int(sqrt(x+v))**2 == x+v):
seen.add(x)
ans += fn(x, mask ^ (1 << i))
return ans
return fn(-1, (1 << len(nums)) - 1) | number-of-squareful-arrays | [Python3] TSP | ye15 | 1 | 152 | number of squareful arrays | 996 | 0.492 | Hard | 16,222 |
https://leetcode.com/problems/number-of-squareful-arrays/discuss/2674701/Python | class Solution:
def numSquarefulPerms(self, nums: List[int]) -> int:
n = len(nums)
nums.sort()
def dfs(prev,rem):
if not rem:
return 1
ans = 0
for i,a in enumerate(rem):
if (i > 0 and a == rem[i-1]) or (prev != -1 and math.sqrt(prev+a)%1 != 0):
continue
ans += dfs(a,rem[:i]+rem[i+1:])
return ans
return dfs(-1,nums) | number-of-squareful-arrays | Python | Akhil_krish_na | 0 | 4 | number of squareful arrays | 996 | 0.492 | Hard | 16,223 |
https://leetcode.com/problems/number-of-squareful-arrays/discuss/2447950/Python-3-Backtrack | class Solution:
def numSquarefulPerms(self, nums: List[int]) -> int:
def is_perfect(v):
k=int(math.sqrt(v))
return k*k==v
nums.sort()
def perm(A,prev):
if len(A)==0:
self.res+=1
return
for j in range(len(A)):
if j>0 and A[j]==A[j-1]:continue
if prev is None:
perm(A[:j]+A[j+1:],A[j])
elif is_perfect(prev+A[j]):
perm(A[:j]+A[j+1:],A[j])
self.res=0
perm(nums,None)
return self.res | number-of-squareful-arrays | [Python 3] Backtrack | gabhay | 0 | 40 | number of squareful arrays | 996 | 0.492 | Hard | 16,224 |
https://leetcode.com/problems/number-of-squareful-arrays/discuss/1991455/orPYTHON-SOL-or-BACKTRACKING-%2B-HASHMAP-or-SIMPLE-SOLUTION-or-WELL-EXPLAINED-or | class Solution:
def isSquare(self,num):
return int(num**0.5)**2 == num
def makePermutation(self,used,vis,prev,n):
if used == n:
#we reached the end
self.ans += 1
return
tmp = {}
for i in range(n):
if vis[i] == False and self.nums[i] not in tmp:
tmp[self.nums[i]] = True
if self.nums[i] in self.d[prev]:
vis[i] = True
self.makePermutation(used+1,vis,self.nums[i],n)
vis[i] = False
def numSquarefulPerms(self, nums: List[int]) -> int:
d = { x:{} for x in nums}
n = len(nums)
for i in range(n):
for j in range(i+1,n):
if self.isSquare(nums[i] + nums[j]):
d[nums[i]][nums[j]] = True
d[nums[j]][nums[i]] = True
self.nums = nums
self.ans = 0
self.d = d
vis = [False]*n
tmp = {}
for i in range(n):
if nums[i] in tmp: continue
tmp[nums[i]] = True
vis[i] = True
self.makePermutation(1,vis,self.nums[i],n)
vis[i] = False
return self.ans | number-of-squareful-arrays | |PYTHON SOL | BACKTRACKING + HASHMAP | SIMPLE SOLUTION | WELL EXPLAINED | | reaper_27 | 0 | 96 | number of squareful arrays | 996 | 0.492 | Hard | 16,225 |
https://leetcode.com/problems/number-of-squareful-arrays/discuss/1691089/Python-optimal-backtrackingdfs-solution-(clean-code) | class Solution:
def numSquarefulPerms(self, nums: List[int]) -> int:
@lru_cache
def square(m):
left, right = 1, m
while left < right:
mid = (left + right) // 2
if mid**2 >= m:
right = mid
else:
left = mid + 1
return m == right**2
n = len(nums)
cnt = set()
stack = []
visited = set()
for i in range(n):
stack.append((nums[:i] + nums[i+1:], [nums[i]]))
while stack:
arr, res = stack.pop()
visited.add((tuple(arr), tuple(res)))
if len(arr) == 0:
cnt.add(tuple(res))
for i in range(len(arr)):
if square(res[-1] + arr[i]):
if (tuple(arr[:i] + arr[i+1:]), tuple(res + [arr[i]])) not in visited:
stack.append((arr[:i] + arr[i+1:], res + [arr[i]]))
return len(cnt) | number-of-squareful-arrays | Python optimal backtracking/dfs solution (clean code) | byuns9334 | 0 | 125 | number of squareful arrays | 996 | 0.492 | Hard | 16,226 |
https://leetcode.com/problems/number-of-squareful-arrays/discuss/831137/Similar-as-problem-47-and-use-DFS | class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
res = []
visited = [0] * len(A)
A.sort()
def helper(nums,out, res):
if len(out) == len(nums):
res.append(out[:])
return
else:
for i in range(len(A)):
if visited[i]:
continue
if i > 0 and A[i] == A[i-1] and visited[i -1]:
continue
if len(out) >= 2 and (out[-1] +out[-2])**0.5 != int((out[-1] +out[-2])**0.5):
continue
if len(out) >= 1 and (out[-1] +A[i])**0.5 != int((out[-1] +A[i])**0.5):
continue
visited[i] = 1
out.append(A[i])
helper(nums,out, res)
out.pop()
visited[i] = 0
helper(A,[], res)
#print(res)
return len(res) | number-of-squareful-arrays | Similar as problem 47 and use DFS | jppooo888 | 0 | 116 | number of squareful arrays | 996 | 0.492 | Hard | 16,227 |
https://leetcode.com/problems/find-the-town-judge/discuss/1663344/C%2B%2BJavaPython3Javascript-Everything-you-need-to-know-from-start-to-end-. | class Solution:
def findJudge(self, N: int, trust: List[List[int]]) -> int:
Trusted = [0] * (N+1)
for (a, b) in trust:
Trusted[a] -= 1
Trusted[b] += 1
for i in range(1, len(Trusted)):
if Trusted[i] == N-1:
return i
return -1 | find-the-town-judge | [C++/Java/Python3/Javascript] Everything you need to know from start to end . | Cosmic_Phantom | 144 | 9,500 | find the town judge | 997 | 0.493 | Easy | 16,228 |
https://leetcode.com/problems/find-the-town-judge/discuss/1663192/Python3-EASY-TO-UNDERSTAND-CODE-Explained | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
trust_to, trusted = defaultdict(int), defaultdict(int)
for a, b in trust:
trust_to[a] += 1
trusted[b] += 1
for i in range(1, n+1):
if trust_to[i] == 0 and trusted[i] == n - 1:
return i
return -1 | find-the-town-judge | ✔️ [Python3] EASY TO UNDERSTAND CODE, Explained | artod | 7 | 864 | find the town judge | 997 | 0.493 | Easy | 16,229 |
https://leetcode.com/problems/find-the-town-judge/discuss/1621150/O(n)-solution-in-Python | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
dg = [0] * (n + 1)
for a, b in trust:
dg[a] -= 1 # out
dg[b] += 1 # in
return next((i for i in range(1, n + 1) if dg[i] == n - 1), -1) | find-the-town-judge | O(n) solution in Python | mousun224 | 3 | 266 | find the town judge | 997 | 0.493 | Easy | 16,230 |
https://leetcode.com/problems/find-the-town-judge/discuss/404001/Python-Logical-solution.-No-hashing-required. | class Solution(object):
def findJudge(self, N, trust):
if trust==[] and N==1:
return 1
x1 = [x[1] for x in trust]
x0 = [x[0] for x in trust]
for i in range(1, N+1):
if i in x1:
if x1.count(i)==(N-1):
if i not in x0:
return i
return -1 | find-the-town-judge | Python Logical solution. No hashing required. | saffi | 3 | 877 | find the town judge | 997 | 0.493 | Easy | 16,231 |
https://leetcode.com/problems/find-the-town-judge/discuss/1664882/Python-easy-and-clean-solution-with-full-explanation | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
no_of_trust = [0] * (n+1) #because in trust numbers starts from 1 to N
for a,b in trust:
no_of_trust[a] -= 1 # a trusts b so a will become less
no_of_trust[b] += 1 # a trusts b so b will become more trustworthy.
for i in range(1,n+1): #because values are modified in range of 1 to N only
if no_of_trust[i] == n-1: # n-1 is the higghest possible value if a judge is present
return i #return the index where judge is found
return -1 | find-the-town-judge | Python easy and clean solution with full explanation | yashitanamdeo | 2 | 201 | find the town judge | 997 | 0.493 | Easy | 16,232 |
https://leetcode.com/problems/find-the-town-judge/discuss/382225/Two-Short-Solutions-in-Python-3 | class Solution:
def findJudge(self, n: int, t: List[List[int]]) -> int:
N = set(range(1,n+1))
for i in t: N.discard(i[0])
if len(N) == 0: return -1
a = list(N)[0]
return a if sum(i[1] == a for i in t) == n-1 else -1 | find-the-town-judge | Two Short Solutions in Python 3 | junaidmansuri | 2 | 479 | find the town judge | 997 | 0.493 | Easy | 16,233 |
https://leetcode.com/problems/find-the-town-judge/discuss/382225/Two-Short-Solutions-in-Python-3 | class Solution:
def findJudge(self, n: int, t: List[List[int]]) -> int:
N = set(range(1,n+1))
for i in t: N.discard(i[0])
return (lambda x: x if sum(i[1] == x for i in t) == n-1 and len(N) == 1 else -1)(list(N)[0] if len(N) != 0 else -1)
- Junaid Mansuri
(LeetCode ID)@hotmail.com | find-the-town-judge | Two Short Solutions in Python 3 | junaidmansuri | 2 | 479 | find the town judge | 997 | 0.493 | Easy | 16,234 |
https://leetcode.com/problems/find-the-town-judge/discuss/242937/Python3-List-O(N)-space-O(N)-time | class Solution:
def findJudge(self, N: int, trust: List[List[int]]) -> int:
a = [0] * (N + 1)
for l in trust:
a[l[1]] += 1
a[l[0]] -= 1
for i in range(1, len(a)):
if a[i] == N - 1:
return i
return -1 | find-the-town-judge | Python3 List O(N) space, O(N) time | jimmyyentran | 2 | 319 | find the town judge | 997 | 0.493 | Easy | 16,235 |
https://leetcode.com/problems/find-the-town-judge/discuss/2515433/Efficient-Python-Solution-or-Memory-less-than-91.50 | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
if not trust and n == 1:
return 1
degree = [0 for i in range(0,n+1)]
for u, v in trust:
degree[u] -= 1 #indegree = -1 for that node
degree[v] += 1 #outdegree = +1 for that node
for i in degree:
if i == (n - 1):
return degree.index(i)
return -1 | find-the-town-judge | Efficient Python Solution | Memory less than 91.50% | nikhitamore | 1 | 73 | find the town judge | 997 | 0.493 | Easy | 16,236 |
https://leetcode.com/problems/find-the-town-judge/discuss/1810855/Python-3-hashmap-solution | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
trustCount = collections.Counter()
trustedCount = collections.Counter()
for a, b in trust:
trustCount[a] += 1
trustedCount[b] += 1
for i in range(1, n + 1):
if trustCount[i] == 0 and trustedCount[i] == n - 1:
return i
return -1 | find-the-town-judge | Python 3, hashmap solution | dereky4 | 1 | 195 | find the town judge | 997 | 0.493 | Easy | 16,237 |
https://leetcode.com/problems/find-the-town-judge/discuss/1664607/Python3-Explanation-and-Intuition-of-complete-solution. | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
trusted_by = [0] * n
for a, b in trust:
[a - 1] -= 1
trusted_by[b - 1] += 1
for i in range(n):
if trusted_by[i] == n - 1:
return i + 1
return -1 | find-the-town-judge | [Python3] Explanation and Intuition of complete solution. | Crimsoncad3 | 1 | 66 | find the town judge | 997 | 0.493 | Easy | 16,238 |
https://leetcode.com/problems/find-the-town-judge/discuss/1663944/Python3-2-liner-and-one-liner | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
counts= collections.Counter([edge for p1,p2 in trust for edge in ((p1,0),(0,p2))])
return next(itertools.chain((p for p in range(1,n+1) if counts[(0,p)]-counts[(p,0)] == n-1),[-1])) | find-the-town-judge | Python3 2-liner and one-liner | pknoe3lh | 1 | 80 | find the town judge | 997 | 0.493 | Easy | 16,239 |
https://leetcode.com/problems/find-the-town-judge/discuss/1663944/Python3-2-liner-and-one-liner | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
return (lambda counts: next(itertools.chain((p for p in range(1,n+1) if counts[(0,p)]-counts[(p,0)] == n-1),[-1])))(collections.Counter([edge for p1,p2 in trust for edge in ((p1,0),(0,p2))])) | find-the-town-judge | Python3 2-liner and one-liner | pknoe3lh | 1 | 80 | find the town judge | 997 | 0.493 | Easy | 16,240 |
https://leetcode.com/problems/find-the-town-judge/discuss/1663227/Python3-O(V-%2B-E)-or-Clean-%2B-Simple-Solution-or-In-Degree-and-Out-Degree | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
inDegree = [0] * n
outDegree = [0] * n
for node, neighb in trust:
inDegree[neighb - 1] += 1
outDegree[node - 1] += 1
for i, (inD, outD) in enumerate(zip(inDegree, outDegree)):
if inD == n - 1 and outD == 0:
return i + 1
return -1 | find-the-town-judge | ✅ [Python3] O(V + E) | Clean + Simple Solution | In-Degree & Out-Degree | PatrickOweijane | 1 | 207 | find the town judge | 997 | 0.493 | Easy | 16,241 |
https://leetcode.com/problems/find-the-town-judge/discuss/1258626/Python3-solution-faster-100 | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
first = []
second = []
if n==1 and len(trust)==0:
return 1
for i in trust:
first.append(i[0])
second.append(i[1])
x = list((set(second)-set(first)))
if len(x)!=0:
x = x[0]
else:
return -1
if second.count(x)<n-1:
return -1
return x | find-the-town-judge | Python3 solution faster 100% | Sanyamx1x | 1 | 253 | find the town judge | 997 | 0.493 | Easy | 16,242 |
https://leetcode.com/problems/find-the-town-judge/discuss/1219967/Python3-simple-solution-using-two-lists | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
if n == 1:
return 1
l1 = list(range(1,n+1))
l2 = []
for i in trust:
if i[0] in l1:
l1.remove(i[0])
if i[1] in l1:
l2.append(i[1])
for i in l1:
if l2.count(i) == n-1:
return i
return -1 | find-the-town-judge | Python3 simple solution using two lists | EklavyaJoshi | 1 | 97 | find the town judge | 997 | 0.493 | Easy | 16,243 |
https://leetcode.com/problems/find-the-town-judge/discuss/891198/Python3-simple-using-iteration-and-degree | class Solution:
def findJudge(self, N: int, trust: List[List[int]]) -> int:
inDegree = [0]*N
outDegree = [0]*N
for a,b in trust:
outDegree[a-1] += 1
inDegree[b-1] += 1
for i in range(N):
if outDegree[i] == 0 and inDegree[i] == N-1:
return i+1
return -1 | find-the-town-judge | Python3 - simple using iteration and degree | gargprat | 1 | 112 | find the town judge | 997 | 0.493 | Easy | 16,244 |
https://leetcode.com/problems/find-the-town-judge/discuss/760354/Python-3Find-the-Town-Judge. | class Solution:
def findJudge(self, N: int, trust: List[List[int]]) -> int:
if N==1:
return 1
# Since it is a Directed Graph
# if -> income degree +=1
# if -> outgoing degree -=1
degree = [0]*(N+1)
for i,j in trust:
degree[i] -=1
degree[j] +=1
for i in range(1,N+1):
if degree[i] == N-1:
return i
return -1 | find-the-town-judge | [Python 3]Find the Town Judge. | tilak_ | 1 | 186 | find the town judge | 997 | 0.493 | Easy | 16,245 |
https://leetcode.com/problems/find-the-town-judge/discuss/624957/Python3-indeg-and-outdeg | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
degree = [0]*n
for u, v in trust:
degree[v-1] += 1
degree[u-1] -= 1
return next((i+1 for i, x in enumerate(degree) if x == n-1), -1) | find-the-town-judge | [Python3] indeg & outdeg | ye15 | 1 | 42 | find the town judge | 997 | 0.493 | Easy | 16,246 |
https://leetcode.com/problems/find-the-town-judge/discuss/2757946/Python3-81-faster-with-explanation | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
trustMap = {}
for i in range(1, n + 1):
trustMap[i] = [0, 0]
for tPath in trust:
trustMap[tPath[0]][1] += 1
trustMap[tPath[1]][0] += 1
for person in trustMap:
if trustMap[person][0] == n - 1 and trustMap[person][1] == 0:
return person
return -1 | find-the-town-judge | Python3, 81% faster with explanation | cvelazquez322 | 0 | 9 | find the town judge | 997 | 0.493 | Easy | 16,247 |
https://leetcode.com/problems/find-the-town-judge/discuss/2733453/Simple-Python-Solution | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
tracker = [0] * n
for a, b in trust:
tracker[a-1] -= 1
tracker[b-1] += 1
for i in range(0, n):
if tracker[i] == n - 1:
return i + 1
return -1 | find-the-town-judge | Simple Python Solution | ekomboy012 | 0 | 3 | find the town judge | 997 | 0.493 | Easy | 16,248 |
https://leetcode.com/problems/find-the-town-judge/discuss/2708890/Graph-or-Python-or-O(n) | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
t = defaultdict(int)
for i in range(n):
t[i] = 0
for a, b in trust:
t[a - 1] -= 1
t[b - 1] += 1
for k, _ in t.items():
if t[k] == n - 1:
return k + 1
return -1 | find-the-town-judge | Graph | Python | O(n) | Kiyomi_ | 0 | 12 | find the town judge | 997 | 0.493 | Easy | 16,249 |
https://leetcode.com/problems/find-the-town-judge/discuss/1959649/Python-3-or-faster-than-99.91 | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
if not trust and n == 1:
return 1
elif not trust:
return -1
judgeCnt = Counter([ y for x, y in trust]).most_common()[0]
if judgeCnt[1] != n - 1 or judgeCnt[0] in [ x for x, y in trust]:
return -1
return judgeCnt[0] | find-the-town-judge | Python 3 | faster than 99.91% | anels | 0 | 194 | find the town judge | 997 | 0.493 | Easy | 16,250 |
https://leetcode.com/problems/find-the-town-judge/discuss/1806350/3-Lines-Python-Solution-oror-slow-oror-Memory-less-than-60 | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
for i in range(1,n+1):
if sorted([trus[0] for trus in trust if trus[1]==i])==[x for x in range(1,n+1) if x!=i] and i not in [trus[0] for trus in trust]: return i
return -1 | find-the-town-judge | 3-Lines Python Solution || slow || Memory less than 60% | Taha-C | 0 | 107 | find the town judge | 997 | 0.493 | Easy | 16,251 |
https://leetcode.com/problems/find-the-town-judge/discuss/1664970/Using-sets-and-intersection-python-O(n)-solution | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
if trust == []:
return 1 if n == 1 else -1
memory = {}
for t in trust:
memory.setdefault(t[0], set()).add(t[1])
trusted = set.intersection(*memory.values())
if len(memory.keys()) == n - 1: #continue only if a single person does not trust anyone
for people in trusted:
if people not in memory:
return people
return -1 | find-the-town-judge | Using sets & intersection python O(n) solution | Sima24 | 0 | 50 | find the town judge | 997 | 0.493 | Easy | 16,252 |
https://leetcode.com/problems/find-the-town-judge/discuss/1664611/Python-3-Easy-Solution | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
if n==1:
return 1
ct={}
t={}
for i in trust:
if i[1] in ct:
ct[i[1]]+=1
else:
ct[i[1]]=1
for i in trust:
t[i[0]]=i[1]
for key in ct:
if n-1==ct[key] and key not in t:
return key
return -1 | find-the-town-judge | Python 3 Easy Solution | aryanagrawal2310 | 0 | 74 | find the town judge | 997 | 0.493 | Easy | 16,253 |
https://leetcode.com/problems/find-the-town-judge/discuss/1664288/Unique-Approach-Python3-Solution-O(1)-Memory | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
trust = list(sorted(trust, key=lambda x: x[1])) # Sort list based on the trustee
if n == 1: # Only one person condition
return 1
if not trust:
return -1
potential_judge = trust[0][1] # Assign the potential_judge to the first trustee
trust_count = 1 # Initialize the trust count to 1
for _, trustee in trust[1:]:
if potential_judge == trustee: # Increase the trust_count if trustee is the potential_judge
trust_count += 1
elif trust_count == n-1:
break
else:
potential_judge = trustee # Assign the potential_judge to the new trustee
trust_count = 1 # Initialize the trust count to 1
for truster, _ in trust:
if truster == potential_judge: # If the potential_judge is a truster return -1
return -1
return potential_judge if trust_count == n-1 else -1 # If trust_count == n-1 then return the judge found else -1 | find-the-town-judge | [Unique Approach] Python3 Solution O(1) Memory | Sparkles4 | 0 | 73 | find the town judge | 997 | 0.493 | Easy | 16,254 |
https://leetcode.com/problems/find-the-town-judge/discuss/1663815/Python3-hashmap-solution-or-easy-understanding | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
if n == 1: return 1
if not trust: return -1
potential_judge = dict()
normal_people = []
for i in trust:
if i[1] in potential_judge.keys():
potential_judge[i[1]] += 1
else:
if i[1] not in normal_people:
potential_judge[i[1]] = 1
if i[0] not in normal_people:
normal_people.append(i[0])
if i[0] in potential_judge:
potential_judge.pop(i[0])
for j in potential_judge:
if potential_judge[j] == n-1:
return j
return -1 | find-the-town-judge | Python3 hashmap solution | easy-understanding | Janetcxy | 0 | 52 | find the town judge | 997 | 0.493 | Easy | 16,255 |
https://leetcode.com/problems/find-the-town-judge/discuss/1663483/Python-Solution-SImple-to-understand | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
if n == 1 and len(trust) == 0:
return 1
if len(trust) == 0:
return -1
persons = []
for i in range(n+1):
persons.append({"id": i, "trusted_by": 0, "trusts": 0})
for i, v in enumerate(trust):
persons[v[0]]["trusts"] += 1
persons[v[1]]["trusted_by"] += 1
for p in persons:
if p["trusts"] == 0 and p["trusted_by"] == n - 1:
return p["id"]
return -1 | find-the-town-judge | Python Solution SImple to understand | pradeep288 | 0 | 156 | find the town judge | 997 | 0.493 | Easy | 16,256 |
https://leetcode.com/problems/find-the-town-judge/discuss/1663177/python3-Simple-O(n)-Solution | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
votes = [0] * n
# track the current most popular candidate
c = 0
for a, b in trust:
# the judge trusts noone, so anyone that votes cannot possibly be in the running
votes[a-1] = -inf
votes[b-1] += 1
# update our likely candidate if needed
if votes[b-1] >= votes[c]:
c = b - 1
if votes[c] == n-1:
return c + 1
else:
return -1 | find-the-town-judge | python3 Simple O(n) Solution | zldobbs | 0 | 51 | find the town judge | 997 | 0.493 | Easy | 16,257 |
https://leetcode.com/problems/find-the-town-judge/discuss/1342456/Easy-Python-Solution | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
if not trust and n!=1:
return -1
s=set()
j=0
for i in (trust):
s.add(i[0])
for i in range(1,n+1):
if(i not in s):
j=i
break
d=dict()
for i in (trust):
if i[0] not in d:
d[i[0]] = list()
d[i[0]].append(i[1])
if(len(d)<n-1):
return -1
for i,v in d.items():
if(j not in v):
return -1
return j | find-the-town-judge | Easy Python Solution | Sneh17029 | 0 | 316 | find the town judge | 997 | 0.493 | Easy | 16,258 |
https://leetcode.com/problems/find-the-town-judge/discuss/1092248/Python-Solution-using-a-Dictionary | class Solution:
def findJudge(self, N: int, trust: List[List[int]]) -> int:
"""
Uses a hash table to store the valid candidates and who trusted this candidate.
Time complexity: O(N). Space complexity: O(N)
"""
# A dictionary maps a candidate to who trusted this person.
# !!! The people are 1-indexed.
candidates = {n: set() for n in range(1, N+1)}
for j in range(len(trust)):
# Because trust[j][0] trusts other people,
# this person is no longer a valid candidate.
if trust[j][0] in candidates:
candidates.pop(trust[j][0])
# if the person being trusted is a valid candidate,
# add to the dictionary that trust[j][0] trusts this person.
if trust[j][1] in candidates:
candidates[trust[j][1]].add(trust[j][0])
# Loop through remaining candidates,
for key, val in candidates.items():
# If this person is trusted by all other N-1 people.
if len(val) == (N-1):
return key
# We get here if none of the valid candidates is trusted by
# all other people in the town.
return -1 | find-the-town-judge | Python Solution using a Dictionary | QizhangJia | 0 | 263 | find the town judge | 997 | 0.493 | Easy | 16,259 |
https://leetcode.com/problems/find-the-town-judge/discuss/1080127/a-Python-solution-based-on-%22277.-Find-the-Celebrity%22 | class Solution:
def findJudge(self, N: int, trust: List[List[int]]) -> int:
# main ideas:
# 1. if a trusts b -> a is not a judge
# 2. if a doesn't trust b -> b is not a judge
candidate = 1
for i in range(2, N+1): # 1~N
if [candidate, i] in trust:
candidate = i
# check the candidate is a judge
for i in range(1, N+1):
if i == candidate:
continue
if [i, candidate] not in trust or [candidate, i] in trust:
return -1
return candidate | find-the-town-judge | a Python solution based on "277. Find the Celebrity" | kylu | 0 | 146 | find the town judge | 997 | 0.493 | Easy | 16,260 |
https://leetcode.com/problems/find-the-town-judge/discuss/991887/Python-easy-to-understand | class Solution:
def findJudge(self, N: int, trust: List[List[int]]) -> int:
if N==1:
return 1
d = defaultdict(list)
for n in trust:
d[n[0]].append(1)
d[n[1]].append(2)
for k,v in d.items():
cond = [True if a==2 else False for a in v]
if all(cond) and len(cond)==(N-1):
return k
return -1 | find-the-town-judge | Python easy to understand | vimoxshah | 0 | 207 | find the town judge | 997 | 0.493 | Easy | 16,261 |
https://leetcode.com/problems/find-the-town-judge/discuss/959284/Python3-O(n)-with-explanation | class Solution:
def findJudge(self, N: int, trust: List[List[int]]) -> int:
seen = {t[0] for t in trust}
j = None
for i in range(1, N+1):
if i in seen:
continue
if j:
return -1
j = i
if not j:
return -1
for t in trust:
if t[0] in seen and t[1] == j:
seen.remove(t[0])
return j if not seen else -1 | find-the-town-judge | [Python3] O(n) with explanation | gdm | 0 | 201 | find the town judge | 997 | 0.493 | Easy | 16,262 |
https://leetcode.com/problems/find-the-town-judge/discuss/624177/Python3-Beautiful-and-detailed-solution-with-O(N)-Time-and-O(N)-Extra-Space | class Solution:
def findJudge(self, N: int, trust: List[List[int]]) -> int:
all_people = set(range(1, N + 1))
people_who_trust = set([x[0] for x in trust])
people_who_dont_trust = all_people - people_who_trust
if len(people_who_dont_trust) != 1:
return - 1
judge = people_who_dont_trust.pop()
people_who_need_to_trust = all_people - {judge}
for who_trust, to_whom_trust in trust:
if to_whom_trust == judge:
people_who_need_to_trust.discard(who_trust)
return judge if len(people_who_need_to_trust) == 0 else - 1 | find-the-town-judge | [Python3] Beautiful & detailed solution with O(N) Time & O(N) Extra Space | timetoai | 0 | 46 | find the town judge | 997 | 0.493 | Easy | 16,263 |
https://leetcode.com/problems/find-the-town-judge/discuss/243955/Celebrity-question-detailed-explanation | class Solution:
def findJudge(self, N: int, trust: List[List[int]]) -> int:
a_trust_b = set()
for a, b in trust:
a_trust_b.add((a, b))
if N == 1:
return 1
# find candidate judge as b
# each round elimnate 1 candidate
# after all iterations, b may be judge, all others are not
a, b = 1, 2
while a <= N and b <= N:
if (a,b) in a_trust_b:
# a not judge
# b may be judge
a = max(a,b) + 1
else:
# a may be judge
# b not judge
b = max(a,b) + 1
a,b = b,a
for j in range(1,N+1):
# judge b doesn't trust himself
if j == b:
continue
# judge b don't trust anyone, everyone trusts judge
if (b, j) in a_trust_b or (j, b) not in a_trust_b:
# if b is not judge, no one else is
return -1
return b | find-the-town-judge | Celebrity question detailed explanation | leonmak | 0 | 158 | find the town judge | 997 | 0.493 | Easy | 16,264 |
https://leetcode.com/problems/find-the-town-judge/discuss/1520554/Python3-Two-kind-of-solutions | class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
if n == 1:
return 1
d = {}
trusted = set()
for t in trust:
if t[1] not in d:
d[t[1]] = []
d[t[1]].append(t[0])
trusted.add(t[0])
for key in d:
if len(d[key]) == n - 1 and key not in trusted:
return key
return -1
class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
count = [0] * (n + 1)
for t in trust:
count[t[0]] -= 1
count[t[1]] += 1
for i in range(1, n + 1):
if count[i] == n - 1:
return i
return -1 | find-the-town-judge | [Python3] Two kind of solutions | maosipov11 | -1 | 111 | find the town judge | 997 | 0.493 | Easy | 16,265 |
https://leetcode.com/problems/maximum-binary-tree-ii/discuss/2709985/Python-short-python-solution | class Solution:
def insertIntoMaxTree(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root: return TreeNode(val)
if val > root.val: return TreeNode(val, root)
root.right = self.insertIntoMaxTree(root.right, val)
return root | maximum-binary-tree-ii | [Python] short python solution | scrptgeek | 0 | 6 | maximum binary tree ii | 998 | 0.665 | Medium | 16,266 |
https://leetcode.com/problems/maximum-binary-tree-ii/discuss/2533846/Python-Commented-and-simple-DFS-solution | class Solution:
def insertIntoMaxTree(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
# that can be solved using DFS, as it is quite easy to
# keep track of the parent node there
# take care of the edge case that there is no root
if not root:
return TreeNode(val=val)
# take care of the edge case that root is smaller
if root.val < val:
return TreeNode(val=val, left=root)
# get into the dfs (we need to keep track of the parent)
# self.attached = False
dfs(root.right, root, val)
return root
def dfs(node, parent, val):
# check the break conditions
if node is None or node.val < val:
# we always attach the node to the parent right (as it
# is the last value in the array)
# also we append the previous subtree to the left
# following the same logic
parent.right = TreeNode(val=val, left=parent.right)
return
# we alway go to the right (since this is the
# way it would be done during build as our value
# is appended to the right of a to make b)
# Names a and b are from the examples
dfs(node.right, node, val) | maximum-binary-tree-ii | [Python] - Commented and simple DFS solution | Lucew | 0 | 18 | maximum binary tree ii | 998 | 0.665 | Medium | 16,267 |
https://leetcode.com/problems/maximum-binary-tree-ii/discuss/2533846/Python-Commented-and-simple-DFS-solution | class Solution:
def insertIntoMaxTree(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root:
return TreeNode(val=val)
if root.val < val:
return TreeNode(val=val, left=root)
dfs(root.right, root, val)
return root
def dfs(node, parent, val):
if node is None or node.val < val:
parent.right = TreeNode(val=val, left=parent.right)
return
dfs(node.right, node, val) | maximum-binary-tree-ii | [Python] - Commented and simple DFS solution | Lucew | 0 | 18 | maximum binary tree ii | 998 | 0.665 | Medium | 16,268 |
https://leetcode.com/problems/maximum-binary-tree-ii/discuss/985315/Python3-move-down-the-tree-O(logN) | class Solution:
def insertIntoMaxTree(self, root: TreeNode, val: int) -> TreeNode:
prev, node = None, root
while node and val < node.val: prev, node = node, node.right
temp = TreeNode(val, left=node)
if prev: prev.right = temp
else: root = temp
return root | maximum-binary-tree-ii | [Python3] move down the tree O(logN) | ye15 | 0 | 76 | maximum binary tree ii | 998 | 0.665 | Medium | 16,269 |
https://leetcode.com/problems/available-captures-for-rook/discuss/356593/Solution-in-Python-3-(beats-~97)-(three-lines) | class Solution:
def numRookCaptures(self, b: List[List[str]]) -> int:
I, J = divmod(sum(b,[]).index('R'),8)
C = "".join([i for i in [b[I]+['B']+[b[i][J] for i in range(8)]][0] if i != '.'])
return C.count('Rp') + C.count('pR')
- Junaid Mansuri
(LeetCode ID)@hotmail.com | available-captures-for-rook | Solution in Python 3 (beats ~97%) (three lines) | junaidmansuri | 8 | 839 | available captures for rook | 999 | 0.679 | Easy | 16,270 |
https://leetcode.com/problems/available-captures-for-rook/discuss/1601678/Python-3-easy-to-understand-faster-than-96 | class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
n = 8
for i in range(n): # find rook location
for j in range(n):
if board[i][j] == 'R':
x, y = i, j
break
res = 0
for i in range(x-1, -1, -1): # check north
if board[i][y] == 'p':
res += 1
break
if board[i][y] == 'B':
break
for i in range(x+1, n): # check south
if board[i][y] == 'p':
res += 1
break
if board[i][y] == 'B':
break
for j in range(y-1, -1, -1): # check west
if board[x][j] == 'p':
res += 1
break
if board[x][j] == 'B':
break
for j in range(y+1, n): # check east
if board[x][j] == 'p':
res += 1
break
if board[x][j] == 'B':
break
return res | available-captures-for-rook | Python 3 easy to understand, faster than 96% | dereky4 | 3 | 159 | available captures for rook | 999 | 0.679 | Easy | 16,271 |
https://leetcode.com/problems/available-captures-for-rook/discuss/1112858/Easiest-Recursive-solution-or-97.6-time-98.2-space | class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
def find(rx, ry, direction, count):
if rx == 8 or ry == 8 or rx == -1 or ry == -1: return count
if board[rx][ry] == "B": return 0
if board[rx][ry] == "p": return count + 1
if direction == "L": return find(rx, ry - 1, "L", count)
elif direction == "R": return find(rx, ry + 1, "R", count)
elif direction == "U": return find(rx - 1, ry, "U", count)
else: return find(rx + 1, ry, "D", count)
rookx = rooky = -1
for i in range(len(board)):
if "R" in board[i]:
rookx, rooky = i, board[i].index("R")
break
return find(rookx, rooky, "L", 0) + find(rookx, rooky, "R", 0) + find(rookx, rooky, "U", 0) + find(rookx, rooky, "D", 0) | available-captures-for-rook | Easiest Recursive solution | 97.6% time, 98.2% space | vanigupta20024 | 3 | 243 | available captures for rook | 999 | 0.679 | Easy | 16,272 |
https://leetcode.com/problems/available-captures-for-rook/discuss/500938/Python3%3A-not-pretty-but-straight-forward | class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 'R':
count = 0;
l, r = j - 1, j + 1
while l >= 0:
if board[i][l] in 'pB':
count += board[i][l] == 'p'
break
l -= 1
while r < len(board[0]):
if board[i][r] in 'pB':
count += board[i][r] == 'p'
break
r += 1
u, d = i - 1, i + 1
while u >= 0:
if board[u][j] in 'pB':
count += board[u][j] == 'p'
break
u -= 1
while d < len(board):
if board[d][j] in 'pB':
count += board[d][j] == 'p'
break
d += 1
return count | available-captures-for-rook | Python3: not pretty, but straight forward | andnik | 1 | 157 | available captures for rook | 999 | 0.679 | Easy | 16,273 |
https://leetcode.com/problems/available-captures-for-rook/discuss/379640/Simon's-Note-Python3 | class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
res=0
n_row=len(board)
n_col=len(board[0])
dirs=[[0,1],[0,-1],[-1,0],[1,0]]
for i in range(n_row):
for j in range(n_col):
if board[i][j]=="R":
for dir in dirs:
cur_r=i
cur_c=j
while 0<=cur_r<n_row and 0<=cur_c<n_col:
if board[cur_r][cur_c]=='B':
break
if board[cur_r][cur_c]=="p":
res+=1
break
cur_r+=dir[0]
cur_c+=dir[1]
return res
return 0 | available-captures-for-rook | [🎈Simon's Note🎈] Python3 | SunTX | 1 | 101 | available captures for rook | 999 | 0.679 | Easy | 16,274 |
https://leetcode.com/problems/available-captures-for-rook/discuss/2843995/Python3-Solution-using-DFS | class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
def dfs(r, c, i, j):
ans = 0
while 0 <= r < 8 and 0 <= c < 8:
if board[r][c] == 'p':
ans += 1
break
if board[r][c] == 'B':
break
r, c = r + i, c + j
return ans
for i in range(8):
for j in range(8):
if board[i][j] == 'R':
return dfs(i, j, 0, 1) + dfs(i, j, 0, -1) + dfs(i, j, 1, 0) + dfs(i, j, -1, 0)
return 0 | available-captures-for-rook | [Python3] Solution using DFS | BLOCKS | 0 | 3 | available captures for rook | 999 | 0.679 | Easy | 16,275 |
https://leetcode.com/problems/available-captures-for-rook/discuss/2716302/Python-Easy-to-follow-with-comments | class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
def find_pawn(board_slice):
for square in board_slice:
if square == 'B':
return 0
if square == 'p':
return 1
return 0
output = 0
# This will be where the rook is located
rook_row_i = -1
rook_col_i = -1
# We have a list or rows, let's also get a list of columns
board_cols = list(zip(*board))
# Find the rook
for i in range(len(board)):
for j in range(len(board)):
if board[i][j] == 'R':
rook_row_i = i
rook_col_i = j
# We now know where the rook is, let's get just the row and column we care about
rook_row = board[rook_row_i]
rook_col = board_cols[rook_col_i]
# Send the relevant chunks of our row and column to our find_pawn
output += find_pawn(reversed(rook_col[0:rook_row_i]))
output += find_pawn(rook_col[rook_row_i + 1: len(board)])
output += find_pawn(reversed(rook_row[0: rook_col_i]))
output += find_pawn(rook_row[rook_col_i: len(board)])
return output | available-captures-for-rook | Python - Easy to follow with comments | ptegan | 0 | 10 | available captures for rook | 999 | 0.679 | Easy | 16,276 |
https://leetcode.com/problems/available-captures-for-rook/discuss/2711816/Python-!-Simple-Solution | class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
bod = board[::]
rows = [[i for i in ro if i != "."] for ro in bod]
cols = [[i for i in list(co) if i != "."]for co in list(zip(*bod))]
count = 0
rows = rows + cols
for row in rows:
if len(row) < 2:
continue
if "pR" in "".join(row):
count += 1
if "Rp" in "".join(row):
count += 1
return count | available-captures-for-rook | Python ! Simple Solution | w7Pratham | 0 | 11 | available captures for rook | 999 | 0.679 | Easy | 16,277 |
https://leetcode.com/problems/available-captures-for-rook/discuss/2681421/Python-Solution-Fast-and-Easy | class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
ans = 0
boardT = list(zip(*board))
for i in range(8):
if "R" in board[i]:
j = board[i].index("R")
rookIndex = (i, j)
if "p" in board[i][:j]:
if "B" in board[i][:j]:
indexOfp = "".join(board[i][:j]).rindex("p")
indexOfB = "".join(board[i][:j]).rindex("B")
if indexOfp > indexOfB:
ans += 1
else:
ans += 1
if "p" in board[i][j+1:]:
if "B" in board[i][j+1:]:
indexOfp = board[i][j+1:].index("p")
indexOfB = board[i][j+1:].index("B")
if indexOfp < indexOfB:
ans += 1
else:
ans += 1
if "p" in boardT[j][:i]:
if "B" in boardT[j][:i]:
indexOfp = "".join(boardT[j][:i]).rindex("p")
indexOfB = "".join(boardT[j][:i]).rindex("B")
if indexOfp > indexOfB:
ans += 1
else:
ans += 1
if "p" in boardT[j][i+1:]:
if "B" in boardT[j][i+1:]:
indexOfp = boardT[j][i+1:].index("p")
indexOfB = boardT[j][i+1:].index("B")
if indexOfp < indexOfB:
ans += 1
else:
ans += 1
break
return ans | available-captures-for-rook | Python Solution - Fast and Easy | scifigurmeet | 0 | 2 | available captures for rook | 999 | 0.679 | Easy | 16,278 |
https://leetcode.com/problems/available-captures-for-rook/discuss/1991449/easy-soln | class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
rookcoord=[]
i=j=0
while i < len(board):
j=0
while j < len(board[0]):
if board[i][j] == "R":
#print("Rook found", i,j)
r = i
c = j
rookcoord = [ r , c]
break
j+=1
i+=1
#while i < :
#i+=1
#go north
r1 = r
c1 = c
captures = 0
while r1 >= 0:
if board[r1][c1] =="B":
break
if board[r1][c1] =="p":
captures+=1
break
r1-=1
#go south
r1 = r
c1 = c
while r1 < len(board):
if board[r1][c1] =="B":
break
if board[r1][c1] =="p":
captures+=1
break
r1+=1
#go east
r1 = r
c1 = c
while c1 < len(board[0]):
if board[r1][c1] =="B":
break
if board[r1][c1] =="p":
captures+=1
break
c1+=1
#go west
r1 = r
c1 = c
while c1 >= 0:
if board[r1][c1] =="B":
break
if board[r1][c1] =="p":
captures+=1
break
c1-=1
return captures | available-captures-for-rook | easy soln | golden-eagle | 0 | 18 | available captures for rook | 999 | 0.679 | Easy | 16,279 |
https://leetcode.com/problems/available-captures-for-rook/discuss/1980496/python3-easy-solution-for-rook | class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
counter=0
number=0
number2=0
for i in range(len(board)):
temp=board[i]
for j in range(len(temp)):
if temp[j] == 'R':
index_rook = j
index_place = i
break;
temp_list = board[index_place]
for i in range(len(temp_list)):
if temp_list[i] == 'p':
if i < index_rook:
c=1
for j in range(i+1,index_rook):
if temp_list[j] == 'B':
c=0
break;
if c==1:
# print("hi")
number=number+1
elif i > index_rook:
c=1
for j in range(i-1,index_rook,-1):
if temp_list[j] == 'B':
c=0
break;
if c==1:
number2=number2+1
if number>0:
counter=counter+1
if number2>0:
counter=counter+1
for i in range(index_place,0,-1):
temp=board[i-1]
k=temp[index_rook]
if k == 'B':
break;
elif k =='p':
counter+=1
break;
for i in range(index_place+1,len(board)):
temp=board[i]
k=temp[index_rook]
if k == 'B':
break;
elif k =='p':
counter+=1
break;
return counter | available-captures-for-rook | python3 easy solution for rook | vishwahiren16 | 0 | 44 | available captures for rook | 999 | 0.679 | Easy | 16,280 |
https://leetcode.com/problems/available-captures-for-rook/discuss/1650582/Simple-Python-Solution | class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
x=y=0
for i in range(len(board)):
flag=0
for j in range(len(board[0])):
if board[i][j]=='R':
x,y=i,j
# print(x, y)
count=0
for i in range(x, -1, -1):
if board[i][y]=='B':
break
elif board[i][y]=='p':
count+=1
break
print(i, y)
for i in range(x, len(board)):
if board[i][y]=='B':
break
elif board[i][y]=='p':
count+=1
break
print(i, y)
for i in range(y, -1, -1):
if board[x][i]=='B':
break
elif board[x][i]=='p':
count+=1
break
print(x, i)
for i in range(y, len(board[0])):
if board[x][i]=='B':
break
elif board[x][i]=='p':
count+=1
break
print(x, i)
return count | available-captures-for-rook | Simple Python Solution | Siddharth_singh | 0 | 83 | available captures for rook | 999 | 0.679 | Easy | 16,281 |
https://leetcode.com/problems/available-captures-for-rook/discuss/1398741/Python3-Simulation-Faster-Than-95.27-Memory-Less-Than-63.43 | class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
for i in range(8):
for j in range(8):
if board[i][j] == 'R':
x, y = i, j
break
cap = 0
flag1, flag2, flag3, flag4 = False, False, False, False
x1, x2 = x - 1, x + 1
y1, y2 = y - 1, y + 1
while(True):
if not flag1:
if board[x1][y] == 'p':
cap += 1
flag1 = True
elif board[x1][y] == 'B':
flag1 = True
else:
x1 -= 1
if x1 < 0:
flag1 = True
if not flag2:
if board[x2][y] == 'p':
cap += 1
flag2 = True
elif board[x2][y] == 'B':
flag2 = True
else:
x2 += 1
if x2 == 8:
flag2 = True
if not flag3:
if board[x][y1] == 'p':
cap += 1
flag3 = True
elif board[x][y1] == 'B':
flag3 = True
else:
y1 -= 1
if y1 < 0:
flag3 = True
if not flag4:
if board[x][y2] == 'p':
cap += 1
flag4 = True
elif board[x][y2] == 'B':
flag4 = True
else:
y2 += 1
if y2 == 8:
flag4 = True
if (flag1 and flag2 and flag3 and flag4):
return cap | available-captures-for-rook | Python3 Simulation Faster Than 95.27%, Memory Less Than 63.43% | Hejita | 0 | 48 | available captures for rook | 999 | 0.679 | Easy | 16,282 |
https://leetcode.com/problems/available-captures-for-rook/discuss/1268386/Simple-Python-Solution-Recursive-Approach-(DFS-like) | class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
# to store result
res = [0]
# recursive function to find number of available captures
def find(i,j,dirn):
# checking if the position is still out of bound or is 'B' meaning it cannot move forward therefore return
if i<0 or i>7 or j<0 or j>7 or board[i][j]=='B':
return
# checking if the position is in bound and is 'p' meaning it can capture the pawn, incrementing result and returning
if i>=0 and i<8 and j>=0 and j<8 and board[i][j]=='p':
res[0]+=1
return
# recursively checking all north positions moves
if dirn == 'north':
find(i+1,j,'north')
# recursively checking all south positions moves
elif dirn == 'south':
find(i-1,j,'south')
# recursively checking all east positions moves
elif dirn == 'east':
find(i,j+1,'east')
# recursively checking all west positions moves
elif dirn == 'west':
find(i,j-1,'west')
# recursively checking all positions moves in north, south, east and west direction to capture pawns
elif dirn == 'start':
find(i+1,j,'north')
find(i-1,j,'south')
find(i,j+1,'east')
find(i,j-1,'west')
#iterating through the board to find 'R' and check its moves
for i in range(8):
for j in range(8):
if board[i][j] == 'R':
find(i,j,'start') #calling the find function on the R position i & j
break #since only one white rook in the board
#returning the final result of number of available captures
return res[0] | available-captures-for-rook | Simple Python Solution - Recursive Approach (DFS-like) | nagashekar | 0 | 77 | available captures for rook | 999 | 0.679 | Easy | 16,283 |
https://leetcode.com/problems/available-captures-for-rook/discuss/1060944/Python3-simple-solution | class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
def check(board, row, col):
res = 0
a = [[1,0],[-1,0],[0,1],[0,-1]]
for n in a:
x,y = row,col
i = n[0]
j = n[1]
while 0<=x<=7 and 0<=y<=7 :
if board[x][y] == 'p':
res += 1
break
if board[x][y] == 'B':
break
x += i
y += j
return res
for i in range(8):
for j in range(8):
if board[i][j] == 'R':
return check(board,i,j) | available-captures-for-rook | Python3 simple solution | EklavyaJoshi | 0 | 78 | available captures for rook | 999 | 0.679 | Easy | 16,284 |
https://leetcode.com/problems/available-captures-for-rook/discuss/1004621/Python-Faster-than-99.49-20-ms-Search-and-Capture | class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
def total_captures(i,j):
res = 0
# here we are searching for a pawn in top,
# bottom, left, and right directions
# If we find a pawn first, we can capture it
# If we find a bishop, then we can't capture
# any pawn
for a,b in [[1,0], [-1,0], [0,1], [0,-1]]:
x,y = i+a, j+b
while 0<x<8 and 0<y<8:
if board[x][y]=='p':
res+=1
break
elif board[x][y]=='B':
break
x+=a
y+=b
return res
for i in range(8):
for j in range(8):
if board[i][j]=='R':
x,y = i,j
return total_captures(x, y) | available-captures-for-rook | Python Faster than 99.49% 20 ms - Search and Capture | prashantsengar | 0 | 181 | available captures for rook | 999 | 0.679 | Easy | 16,285 |
https://leetcode.com/problems/available-captures-for-rook/discuss/777981/Intuitive-approach-by-searching-four-directions | class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
R, C = len(board), len(board[0])
# 1) Search for rock
rock_r = rock_c = 0
for i in range(R):
for j in range(C):
if board[i][j] == 'R':
rock_r, rock_c = i, j
# print("Rock is round in ({:d}, {:d})".format(rock_r, rock_c))
break
# 2) Start searching P
ans = 0
for ci in range(rock_c-1, -1, -1):
# print("Search board[{},{}]={}...".format(rock_r, ci, board[rock_r][ci]))
if board[rock_r][ci] == '.':
continue
elif board[rock_r][ci] == 'p':
ans += 1
break
else:
break
for ci in range(rock_c+1, C):
# print("Search board[{},{}]={}...".format(rock_r, ci, board[rock_r][ci]))
if board[rock_r][ci] == '.':
continue
elif board[rock_r][ci] == 'p':
ans += 1
break
else:
break
for ri in range(rock_r-1, -1, -1):
# print("Search board[{},{}]={}...".format(ri, rock_c, board[ri][rock_c]))
if board[ri][rock_c] == '.':
continue
elif board[ri][rock_c] == 'p':
ans += 1
break
else:
break
for ri in range(rock_r+1, R):
# print("Search board[{},{}]={}...".format(ri, rock_c, board[ri][rock_c]))
if board[ri][rock_c] == '.':
continue
elif board[ri][rock_c] == 'p':
ans += 1
break
else:
break
return ans | available-captures-for-rook | Intuitive approach by searching four directions | puremonkey2001 | 0 | 52 | available captures for rook | 999 | 0.679 | Easy | 16,286 |
https://leetcode.com/problems/available-captures-for-rook/discuss/512642/Python3-94.24-extremely-easy-to-write-using-too-many-'break'-though...... | class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
# find R
for j in range(8):
for i in range(8):
if board[j][i] == 'R':
count = 0
# find if there is any p vertically above R
for n in range(j,-1,-1):
if board[n][i] == "B":
break
elif board[n][i] == 'p':
count += 1
break
# find if there is any p vertically below R
for s in range(j,8):
if board[s][i] == 'B':
break
elif board[s][i] == 'p':
count += 1
break
# find if there is any p horizontally on the left of R
for w in range(i,-1,-1):
if board[j][w] == 'B':
break
elif board[j][w] == 'p':
count += 1
break
# find if there is any p horizontally on the right of R
for e in range(i,8):
if board[j][e] == 'B':
break
elif board[j][e] == 'p':
count += 1
break
# break once find 'R'
break
return count | available-captures-for-rook | Python3 94.24% - extremely easy to write using too many 'break' though...... | Bannbuuu | 0 | 111 | available captures for rook | 999 | 0.679 | Easy | 16,287 |
https://leetcode.com/problems/available-captures-for-rook/discuss/248407/Faster-Than-100-Python-Solution | class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
row,column=self.findRook(board)
if(row is None and column is None):
return 0
count=0
#Above Rook
for i in range(row,0,-1):
if(board[i][column]=='B'):
break
elif(board[i][column]=='p'):
count+=1
break
#Below Rook
for i in range(row,len(board)):
if(board[i][column]=='B'):
break
elif(board[i][column]=='p'):
count+=1
break
#Left Side
for i in range(column,0,-1):
if(board[row][i]=='B'):
break
elif(board[row][i]=='p'):
count+=1
break
#Right side
for i in range(column,len(board)):
if(board[row][i]=='B'):
break
elif(board[row][i]=='p'):
count+=1
break
return count
def findRook(self,board):
for row in range (len(board)):
for j in range(row,len(board)):
if board[row][j]=='R':
return row,j
return None,None | available-captures-for-rook | Faster Than 100% Python Solution | bismeet | 0 | 117 | available captures for rook | 999 | 0.679 | Easy | 16,288 |
https://leetcode.com/problems/available-captures-for-rook/discuss/244982/Easy-to-read-and-understand-Python-16ms | class Solution(object):
def numRookCaptures(self, board):
"""
:type board: List[List[str]]
:rtype: int
"""
found, i, j = self.findWhiteRook(board)
if not found:
print ('Rook not found.')
return False
p = 0
p = self.blackPondCounter(board, i-1, j, p, 'N') #North
p = self.blackPondCounter(board, i+1, j, p, 'S') #South
p = self.blackPondCounter(board, i, j-1, p, 'W') #West
p = self.blackPondCounter(board, i, j+1, p, 'E') #East
return p
def findWhiteRook(self, b):
for i in range(8):
for j in range(8):
if b[i][j] == 'R':
return True, i, j
return True, 0, 0
def blackPondCounter(self, b, i, j, p, d):
while i >= 0 and i <= 7 and j >= 0 and j <= 7:
if b[i][j] == 'p':
return p + 1
elif b[i][j] == 'B':
print p
return p
if d == 'N':
i = i - 1
elif d == 'S':
i = i + 1
elif d == 'W':
j = j - 1
elif d == 'E':
j = j + 1
return p | available-captures-for-rook | Easy to read and understand Python 16ms | jujbates | 0 | 113 | available captures for rook | 999 | 0.679 | Easy | 16,289 |
https://leetcode.com/problems/available-captures-for-rook/discuss/251469/Python-3-100-faster-100-memory | class Solution:
def numRookCaptures(self, board: List[List[str]]) -> int:
# At first find position of rook and save in 'iR' and 'jR' variables
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == 'R':
iR = i
jR = j
# find all first figures on line and row
res = []
for j in range(jR + 1, len(board)):
if board[iR][j] != '.':
res.append(board[iR][j])
break
for j in range(jR - 1, -1, -1):
if board[iR][j] != '.':
res.append(board[iR][j])
break
for i in range(iR + 1, len(board)):
if board[i][jR] != '.':
res.append(board[i][jR])
break
for i in range(iR - 1, -1, -1):
if board[i][jR] != '.':
res.append(board[i][jR])
break
# calculate how many pawns
resCount = 0
for i in range(len(res)):
if res[i] == 'p':
resCount += 1
return resCount | available-captures-for-rook | Python 3, 100% faster, 100% memory | astepano | -1 | 174 | available captures for rook | 999 | 0.679 | Easy | 16,290 |
https://leetcode.com/problems/minimum-cost-to-merge-stones/discuss/1465680/Python3-dp | class Solution:
def mergeStones(self, stones: List[int], k: int) -> int:
if (len(stones)-1) % (k-1): return -1 # impossible
prefix = [0]
for x in stones: prefix.append(prefix[-1] + x)
@cache
def fn(lo, hi):
"""Return min cost of merging stones[lo:hi]."""
if hi - lo < k: return 0 # not enough stones
ans = inf
for mid in range(lo+1, hi, k-1):
ans = min(ans, fn(lo, mid) + fn(mid, hi))
if (hi-lo-1) % (k-1) == 0: ans += prefix[hi] - prefix[lo]
return ans
return fn(0, len(stones)) | minimum-cost-to-merge-stones | [Python3] dp | ye15 | 1 | 654 | minimum cost to merge stones | 1,000 | 0.423 | Hard | 16,291 |
https://leetcode.com/problems/minimum-cost-to-merge-stones/discuss/781323/python-Top-Down-solution | class Solution:
def minCost(self, n: int, cuts: List[int]) -> int:
_cuts = [0] + sorted(cuts) + [n]
N = len(_cuts)
@lru_cache(None)
def helper(lp,rp):
nonlocal _cuts
if rp-lp==1:
return 0
return _cuts[rp]-_cuts[lp] + min([helper(lp,i)+helper(i,rp) for i in range(lp+1,rp)])
return helper(0,N-1) | minimum-cost-to-merge-stones | python Top Down solution | e-yi | 1 | 564 | minimum cost to merge stones | 1,000 | 0.423 | Hard | 16,292 |
https://leetcode.com/problems/minimum-cost-to-merge-stones/discuss/2633516/Top-down-dynamic-programming-in-concise-Python | class Solution:
@cache
def dp(self, l, r, piles) -> int:
if r - l < piles:
return inf
if r - l == piles:
return 0
if piles == 1:
return self.dp(l, r, self.k) + self.prefix_sum[r] - self.prefix_sum[l]
return min(self.dp(l, m, i) + self.dp(m, r, piles - i) for i in range(1, piles) for m in range(l+i, r-i+1))
def mergeStones(self, stones: List[int], k: int) -> int:
if (len(stones) - k) % (k - 1) != 0:
return -1
self.k = k
self.prefix_sum = [0]
for i in range(0, len(stones)):
self.prefix_sum.append(self.prefix_sum[-1] + stones[i])
return self.dp(0, len(stones), 1) | minimum-cost-to-merge-stones | Top-down dynamic programming in concise Python | metaphysicalist | 0 | 36 | minimum cost to merge stones | 1,000 | 0.423 | Hard | 16,293 |
https://leetcode.com/problems/grid-illumination/discuss/1233528/Python-or-HashMap-or-O(L%2BQ)-or-928ms | class Solution:
def gridIllumination(self, n: int, lamps: List[List[int]], queries: List[List[int]]) -> List[int]:
lamps = {(r, c) for r, c in lamps}
row, col, left, right = dict(), dict(), dict(), dict()
for r, c in lamps:
row[r] = row.get(r, 0) + 1
col[c] = col.get(c, 0) + 1
left[r - c] = left.get(r - c, 0) + 1
right[r + c] = right.get(r + c, 0) + 1
res = list()
for qr, qc in queries:
if row.get(qr, 0) or col.get(qc, 0) or left.get(qr - qc, 0) or right.get(qr + qc, 0):
res.append(1)
else:
res.append(0)
for r, c in product(range(qr - 1, qr + 2), range(qc - 1, qc + 2)):
if (r, c) in lamps:
lamps.remove((r, c))
row[r] -= 1
col[c] -= 1
left[r - c] -= 1
right[r + c] -= 1
return res | grid-illumination | Python | HashMap | O(L+Q) | 928ms | PuneethaPai | 2 | 103 | grid illumination | 1,001 | 0.362 | Hard | 16,294 |
https://leetcode.com/problems/grid-illumination/discuss/2181052/python-3-or-simple-4-hash-map-solution | class Solution:
def gridIllumination(self, n: int, lamps: List[List[int]], queries: List[List[int]]) -> List[int]:
rows = collections.Counter()
cols = collections.Counter()
diags1 = collections.Counter()
diags2 = collections.Counter()
lamps = {tuple(lamp) for lamp in lamps}
for i, j in lamps:
rows[i] += 1
cols[j] += 1
diags1[i + j] += 1
diags2[i - j] += 1
ans = []
directions = ((-1, -1), (-1, 0), (-1, 1),
(0, -1), (0, 0), (0, 1),
(1, -1), (1, 0), (1, 1))
for i, j in queries:
if rows[i] or cols[j] or diags1[i + j] or diags2[i - j]:
ans.append(1)
else:
ans.append(0)
for di, dj in directions:
newI, newJ = i + di, j + dj
if (newI, newJ) not in lamps:
continue
lamps.remove((newI, newJ))
rows[newI] -= 1
cols[newJ] -= 1
diags1[newI + newJ] -= 1
diags2[newI - newJ] -= 1
return ans | grid-illumination | python 3 | simple 4 hash map solution | dereky4 | 1 | 142 | grid illumination | 1,001 | 0.362 | Hard | 16,295 |
https://leetcode.com/problems/grid-illumination/discuss/2115766/Python3-solution-or-Hashmap-or-Explained | class Solution:
def gridIllumination(self, n: int, lamps: List[List[int]], queries: List[List[int]]) -> List[int]:
def check(i, j, dRow, dCol, dDiagS, dDiagP):
if (i in dRow and dRow[i] > 0) or (j in dCol and dCol[j] > 0) or (
i + j in dDiagS and dDiagS[i + j] > 0) or (
i - j in dDiagP and dDiagP[i - j] > 0):
return True
return False
def decrement(i, j, dRow, dCol, dDiagS, dDiagP):
dRow[i] -= 1
dCol[j] -= 1
dDiagS[i + j] -= 1
dDiagP[i - j] -= 1
my_set = set()
dRow, dCol, dDiagS, dDiagP = {}, {}, {}, {}
for i in range(len(lamps)):
if (lamps[i][0], lamps[i][1]) not in my_set:
if lamps[i][0] not in dRow:
dRow[lamps[i][0]] = 1
else:
dRow[lamps[i][0]] += 1
if lamps[i][1] not in dCol:
dCol[lamps[i][1]] = 1
else:
dCol[lamps[i][1]] += 1
if sum(lamps[i]) not in dDiagS:
dDiagS[sum(lamps[i])] = 1
else:
dDiagS[sum(lamps[i])] += 1
if lamps[i][0] - lamps[i][1] not in dDiagP:
dDiagP[lamps[i][0] - lamps[i][1]] = 1
else:
dDiagP[lamps[i][0] - lamps[i][1]] += 1
my_set.add((lamps[i][0], lamps[i][1]))
ans = []
directions = [(-1, -1), (-1, 0), (0, -1), (0, 0), (0, 1), (1, 0), (1, 1), (1, -1), (-1, 1)]
for i in range(len(queries)):
# check if it's lighted up
if check(queries[i][0], queries[i][1], dRow, dCol, dDiagS, dDiagP):
ans.append(1)
# check for lamp at 9 blocks
for x in directions:
if (queries[i][0]+x[0], queries[i][1]+x[1]) in my_set:
decrement(queries[i][0]+x[0], queries[i][1]+x[1], dRow, dCol, dDiagS, dDiagP)
my_set.remove((queries[i][0]+x[0], queries[i][1]+x[1]))
else:
ans.append(0)
return ans | grid-illumination | Python3 solution | Hashmap | Explained | FlorinnC1 | 1 | 51 | grid illumination | 1,001 | 0.362 | Hard | 16,296 |
https://leetcode.com/problems/grid-illumination/discuss/1998042/PYTHON-SOL-oror-WELL-EXPLAINED-oror-HASHMAP-BASED-oror-SIMPLE-oror-EFFICIENT-oror | class Solution:
def checkIsOn(self,row,col):
return 1 if (self.rows[row] > 0 or self.cols[col] > 0 \
or self.digonal1[row-col] > 0 or self.digonal2[row+col] > 0) else 0
def TurnOff(self,row,col):
adj = ((row,col),(row+1,col),(row-1,col),(row,col-1),(row,col+1),\
(row+1,col-1),(row+1,col+1),(row-1,col-1),(row-1,col+1))
for xy in adj:
if xy in self.origin:
self.rows[xy[0]] -= 1
self.cols[xy[1]] -= 1
self.digonal1[xy[0]-xy[1]] -= 1
self.digonal2[xy[0]+xy[1]] -= 1
self.origin.pop(xy)
def turnOn(self,row,col):
self.rows[row] += 1
self.cols[col] += 1
self.digonal1[row-col] += 1
self.digonal2[row+col] += 1
def gridIllumination(self, n: int, lamps: List[List[int]], queries: List[List[int]]) -> List[int]:
self.rows = defaultdict(int)
self.cols = defaultdict(int)
self.digonal1 = defaultdict(int)
self.digonal2 = defaultdict(int)
self.origin = {}
ans = []
for r,c in lamps:
if (r,c) not in self.origin:
self.origin[(r,c)] = True
self.turnOn(r,c)
for r,c in queries:
ans.append(self.checkIsOn(r,c))
self.TurnOff(r,c)
return ans | grid-illumination | PYTHON SOL || WELL EXPLAINED || HASHMAP BASED || SIMPLE || EFFICIENT || | reaper_27 | 1 | 51 | grid illumination | 1,001 | 0.362 | Hard | 16,297 |
https://leetcode.com/problems/grid-illumination/discuss/1638153/python-solution-with-tables-tracking-rows-cols-and-diags-lit | class Solution:
from collections import defaultdict
from itertools import product
def gridIllumination(self, n: int, lamps: List[List[int]], queries: List[List[int]]) -> List[int]:
rows = defaultdict(int)
cols = defaultdict(int)
downright = defaultdict(int)
downleft = defaultdict(int)
lampset = set(map(tuple, lamps))
def turn_on_off(r, c, k):
rows[r] += k
cols[c] += k
downright[c - r] += k
downleft[c + r] += k
def is_illuminated(r, c):
return rows[r] > 0 or cols[c] > 0 or downright[c - r] > 0 or downleft[c + r] > 0
for r, c in lampset:
turn_on_off(r, c, 1)
res = []
for r, c in queries:
res.append(int(is_illuminated(r, c)))
for pos in product(range(r - 1, r + 2), range(c - 1, c + 2)):
if pos in lampset:
lampset.remove(pos)
turn_on_off(pos[0], pos[1], -1)
return res | grid-illumination | python solution with tables tracking rows, cols, and diags lit | PsyKosh | 1 | 95 | grid illumination | 1,001 | 0.362 | Hard | 16,298 |
https://leetcode.com/problems/grid-illumination/discuss/1521789/Python3-freq-table | class Solution:
def gridIllumination(self, n: int, lamps: List[List[int]], queries: List[List[int]]) -> List[int]:
lamps = {(i, j) for i, j in lamps}
rows = defaultdict(int)
cols = defaultdict(int)
anti = defaultdict(int)
diag = defaultdict(int)
for i, j in lamps:
rows[i] += 1
cols[j] += 1
anti[i+j] += 1
diag[i-j] += 1
ans = []
for i, j in queries:
if rows[i] or cols[j] or anti[i+j] or diag[i-j]: ans.append(1)
else: ans.append(0)
for ii in range(i-1, i+2):
for jj in range(j-1, j+2):
if (ii, jj) in lamps:
lamps.remove((ii, jj))
rows[ii] -= 1
cols[jj] -= 1
anti[ii+jj] -= 1
diag[ii-jj] -= 1
return ans | grid-illumination | [Python3] freq table | ye15 | 0 | 92 | grid illumination | 1,001 | 0.362 | Hard | 16,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.