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/flood-fill/discuss/2811701/Flood-fill-or-Easy-python-solution | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
def dfs(image,sr,sc,color,rows,cols,source):
if sr < 0 or sr >= rows or sc < 0 or sc >= cols:
return
elif image[sr][sc] != source:
return
image[sr][sc] = color
dfs(image,sr+1,sc,color,rows,cols,source)
dfs(image,sr-1,sc,color,rows,cols,source)
dfs(image,sr,sc+1,color,rows,cols,source)
dfs(image,sr,sc-1,color,rows,cols,source)
if color == image[sr][sc]:
return image
rows = len(image)
cols = len(image[0])
source = image[sr][sc]
dfs(image,sr,sc,color,rows,cols,source)
return image | flood-fill | Flood fill | Easy python solution | nishanrahman1994 | 0 | 3 | flood fill | 733 | 0.607 | Easy | 12,000 |
https://leetcode.com/problems/flood-fill/discuss/2810558/Python-(Faster-than-97)-or-DFS-solution | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
rows, cols = len(image), len(image[0])
val = image[sr][sc]
visited = set()
def dfs(r, c):
visited.add((r, c))
image[r][c] = color
for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
nr, nc = r + dr, c + dc
if nr in range(rows) and nc in range(cols) and (nr, nc) not in visited and image[nr][nc] == val:
dfs(nr, nc)
dfs(sr, sc)
return image | flood-fill | Python (Faster than 97%) | DFS solution | KevinJM17 | 0 | 3 | flood fill | 733 | 0.607 | Easy | 12,001 |
https://leetcode.com/problems/flood-fill/discuss/2802647/O(n)-Solution-in-python | class Solution:
def floodFill(self, image: List[List[int]], row: int, column: int, newColor: int) -> List[List[int]]:
if image[row][column]==newColor or image==None:
return image
self.fill(image, row, column, image[row][column], newColor)
return image
def fill(self,image, row, column, startPoint, newColor):
if row <0 or row>=len(image) or column<0 or column >= len(image[0]) or image[row][column]!=startPoint:
return
image[row][column]= newColor
self.fill(image, row+1, column, startPoint, newColor)# check up
self.fill(image, row-1, column, startPoint, newColor)# check down
self.fill(image, row, column+1, startPoint, newColor)# check left
self.fill(image, row, column-1, startPoint, newColor)# check right | flood-fill | O(n) Solution in python | rdlong718 | 0 | 2 | flood fill | 733 | 0.607 | Easy | 12,002 |
https://leetcode.com/problems/flood-fill/discuss/2792963/Flood-Fill-algo-using-BFS-oror-Python | class Solution:
def __init__(self):
self.row = [0,0,-1,1]
self.col = [-1,1,0,0]
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
if len(image) == 1:
return image
q = []
q.append((sr,sc))
target = image[sr][sc]
if target == color:
return image
while q:
x,y = q.pop(0)
image[x][y] = color
for k in range(len(self.row)):
if self.isSafe(image, x+self.row[k], y+self.col[k],target):
q.append((x+self.row[k],y+self.col[k]))
#print(image)
return image
def isSafe(self, image, x, y, target):
m = len(image)
n = len(image[0])
return 0 <= x < m and 0 <= y < n and image[x][y] == target | flood-fill | Flood Fill algo using BFS || Python | Sai_Chandan_30 | 0 | 1 | flood fill | 733 | 0.607 | Easy | 12,003 |
https://leetcode.com/problems/flood-fill/discuss/2789031/Python-DFS-solution-explained | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
m,n,colorstart = len(image),len(image[0]),image[sr][sc]
def dfs(i,j,cs):
if i < 0 or j < 0 or i >=m or j >= n or image[i][j]!=cs:
return
# The (i,j) pixel is currently visited, so
# we color it with the new color
image[i][j] = color
dfs(i-1, j, cs)
dfs(i, j-1, cs)
dfs(i+1, j, cs)
dfs(i, j+1, cs)
if colorstart != color:
dfs(sr,sc,colorstart)
return image | flood-fill | Python DFS solution explained | Pirmil | 0 | 3 | flood fill | 733 | 0.607 | Easy | 12,004 |
https://leetcode.com/problems/flood-fill/discuss/2764881/Python-BFS-easy-solution-(94-runtime-99-memory) | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
m = len(image)
n = len(image[0])
queue = [(sr, sc)]
visited = set()
val = image[sr][sc]
if val == color:
return image
# maintain a list of flood points to fill
flood = [(sr, sc)]
while queue:
cell = queue.pop(0)
visited.add(cell)
neighbors = [(0,1), (0,-1), (1, 0), (-1,0)]
for newcell in neighbors:
ele = (cell[0] + newcell[0], cell[1] + newcell[1])
if 0 <= ele[0] < m and 0 <= ele[1] < n and ele not in visited and image[ele[0]][ele[1]] == val:
flood.append(ele)
queue.append(ele)
visited.add(ele)
for pt in flood:
image[pt[0]][pt[1]] = color
return image | flood-fill | Python BFS easy solution (94% runtime, 99% memory) | sakshampandey273 | 0 | 15 | flood fill | 733 | 0.607 | Easy | 12,005 |
https://leetcode.com/problems/flood-fill/discuss/2743451/Python3-straightforward-recursive-solution | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
m = len(image)
n = len(image[0])
scolor = image[sr][sc]
# in case of infinite dfs
if scolor == color:
return image
# check row and column
def dfs(r,c):
if image[r][c] == scolor:
image[r][c] = color
if r > 0:
dfs(r-1, c)
if c > 0:
dfs(r, c-1)
if r < m-1:
dfs(r+1, c)
if c < n-1:
dfs(r, c+1)
dfs(sr, sc)
return image | flood-fill | Python3 straightforward recursive solution | damaolee | 0 | 6 | flood fill | 733 | 0.607 | Easy | 12,006 |
https://leetcode.com/problems/flood-fill/discuss/2704123/Here-is-my-simple-solution-using-one-function | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
if sr > len(image) or sc > len(image[0]) or sr == -1 or sc == -1: # do not exceed the matrix
return image
if(image[sr][sc] == color): # check if this element is colored -> then return
return image
# if not
temp = image[sr][sc] # save the color
image[sr][sc] = color # color the element
if sr+1 < len(image):
if (image[sr+1][sc] == temp):
image = self.floodFill(image, sr+1, sc, color) # right
if sr-1 > -1:
if (image[sr-1][sc] == temp):
imgae = self.floodFill(image, sr-1, sc, color) # left
if sc+1 < len(image[0]):
if (image[sr][sc+1] == temp):
image = self.floodFill(image, sr, sc+1, color) # up
if sc-1 > -1:
if (image[sr][sc-1] == temp):
image = self.floodFill(image, sr, sc-1, color) # down
return image | flood-fill | Here is my simple solution using one function | user4038B | 0 | 9 | flood fill | 733 | 0.607 | Easy | 12,007 |
https://leetcode.com/problems/flood-fill/discuss/2674237/Python-Beats-98.96-(BFS) | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
M, N = len(image), len(image[0])
def validIndex(r,c):
nonlocal M, N, image, sr, sc
return 0<=r and r<=M-1 and 0<=c and c<=N-1 and image[r][c] == origin_color
if image[sr][sc] == color: return image
origin_color = image[sr][sc]
queue = []
queue.append((sr, sc))
while queue:
for i in range(len(queue)):
(r, c) = queue.pop(0)
image[r][c] = color
if validIndex(r-1, c) : queue.append((r-1, c))
if validIndex(r+1, c) : queue.append((r+1, c))
if validIndex(r, c-1) : queue.append((r, c-1))
if validIndex(r, c+1) : queue.append((r, c+1))
return image | flood-fill | Python Beats 98.96% (BFS) | SYLin117 | 0 | 2 | flood fill | 733 | 0.607 | Easy | 12,008 |
https://leetcode.com/problems/flood-fill/discuss/2661430/Super-basic-python-DFS-(O(n)) | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
# This is not necessary but returns a faster solution
source_color = image[sr][sc]
if source_color == color:
return image
stack = [(sr, sc)]
visited = set()
while stack:
r, c = stack.pop()
visited.add((r, c))
if image[r][c] == source_color:
image[r][c] = color
else:
continue
if r > 0 and image[r - 1][c] == source_color:
if (r - 1, c) not in visited:
stack.append((r - 1, c))
if r < len(image) - 1 and image[r + 1][c] == source_color:
if (r + 1, c) not in visited:
stack.append((r + 1, c))
if c > 0 and image[r][c - 1] == source_color:
if (r, c - 1) not in visited:
stack.append((r, c - 1))
if c < len(image[0]) - 1 and image[r][c + 1] == source_color:
if (r, c + 1) not in visited:
stack.append((r, c + 1))
return image | flood-fill | Super basic python DFS (O(n)) | AlecLeetcode | 0 | 3 | flood fill | 733 | 0.607 | Easy | 12,009 |
https://leetcode.com/problems/flood-fill/discuss/2657627/Python-Solution-using-DFS-and-Hash-Map | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
visited = set() # Tuples already traversed in image
NUM_ROW = len(image)
NUM_COL = len(image[0])
START_COLOR = image[sr][sc]
if START_COLOR == color:
return image
def recursChangeColor(row,column):
if (row,column) in visited:
return
if image[row][column] == START_COLOR:
image[row][column] = color
visited.add((row, column))
if row-1 >= 0 and (row-1,column) not in visited:
recursChangeColor(row-1,column) # Down
if row+1 <= NUM_ROW-1 and (row+1,column) not in visited:
recursChangeColor(row+1,column) # Up
if column-1 >= 0 and (row,column-1) not in visited:
recursChangeColor(row,column-1) # Left
if column+1 <= NUM_COL-1 and (row,column+1) not in visited:
recursChangeColor(row,column+1) # Right
else:
return
recursChangeColor(sr,sc)
return image | flood-fill | Python Solution, using DFS and Hash Map | BrandonTrastoy | 0 | 2 | flood fill | 733 | 0.607 | Easy | 12,010 |
https://leetcode.com/problems/flood-fill/discuss/2632886/Python-easy-solution | class Solution:
img = None
def paint(self, sr: int, sc: int, old_color: int, new_color: int):
if(self.img[sr][sc] == new_color):
return
elif(self.img[sr][sc] == old_color):
self.img[sr][sc] = new_color
else:
return
# up, down, left, right
if(sr != 0):
self.paint(sr-1, sc, old_color, new_color)
if(sr != len(self.img)-1):
self.paint(sr+1, sc, old_color, new_color)
if(sc!=0):
self.paint(sr, sc-1, old_color, new_color)
if(sc != len(self.img[0])-1):
self.paint(sr, sc+1, old_color, new_color)
return
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
self.img = image
self.paint(sr, sc, image[sr][sc], color)
return self.img | flood-fill | Python easy solution | Jack_Chang | 0 | 35 | flood fill | 733 | 0.607 | Easy | 12,011 |
https://leetcode.com/problems/flood-fill/discuss/2599378/Fast-concise-solution-self-explanatory | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
def fill_rec(r, c, ref_color, new_color):
# recursive function that paints a pixel and calls itself for the 4 neighbor pixels.
if image[r][c] != ref_color: # must be same color as the starting pixel
return
image[r][c] = new_color
if r>0: fill_rec(r-1, c, ref_color, new_color)
if c>0: fill_rec(r, c-1, ref_color, new_color)
if r<len(image)-1: fill_rec(r+1, c, ref_color, new_color)
if c<len(image[0])-1: fill_rec(r, c+1, ref_color, new_color)
ref_color = image[sr][sc] # reference color of starting pixel
if ref_color != color:
fill_rec(sr, sc, ref_color, color) # call the recursive function for the starting pixel
return image | flood-fill | Fast concise solution self-explanatory | alexion1 | 0 | 13 | flood fill | 733 | 0.607 | Easy | 12,012 |
https://leetcode.com/problems/flood-fill/discuss/2538141/python-solution-or-space-O(1)-or-time-O(mn) | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
if image[sr][sc]==color:
return image
set_col=image[sr][sc]
r,c=len(image),len(image[0])
st=[(sr,sc)]
direction=[(1,0),(-1,0),(0,1),(0,-1)]
while len(st)>0:
temr,temc=st.pop(-1)
image[temr][temc]=color
for dr,dc in direction:
calr=temr+dr
calc=temc+dc
if 0<=calr<r and 0<=calc<c and image[calr][calc]==set_col:
st.append((calr,calc))
return image | flood-fill | python solution | space-O(1) | time - O(mn) | I_am_SOURAV | 0 | 66 | flood fill | 733 | 0.607 | Easy | 12,013 |
https://leetcode.com/problems/flood-fill/discuss/2494794/Python-solution-with-DFS | class Solution:
def DFS(self,i:int , j:int , initialColor:int , newColor:int , image: List[List[int]])->List[List[int]]:
n , m = len(image)-1 , len(image[0])-1
if i<0 or j<0 : return
if i > n or j > m : return
if image[i][j]!= initialColor: return
image[i][j] = newColor
self.DFS(i+1,j,initialColor,newColor,image)
self.DFS(i-1,j,initialColor,newColor,image)
self.DFS(i,j+1,initialColor,newColor,image)
self.DFS(i,j-1,initialColor,newColor,image)
return image
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
initialColor = image[sr][sc]
if color!=initialColor:
image=self.DFS(sr,sc,initialColor,color,image)
return image | flood-fill | Python solution with DFS | ronipaul9972 | 0 | 53 | flood fill | 733 | 0.607 | Easy | 12,014 |
https://leetcode.com/problems/flood-fill/discuss/2491756/Simple-python-solution-or-DFS-or-93-faster | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
oldColor = image[sr][sc]
n = len(image)
m = len(image[0])
if color == oldColor:
return image
self.floodFillDFS(image, sr, sc, n, m, oldColor, color)
return image
def isValid(self, image, r, c, n, m, oldColor):
if (r >= 0 and r < n and c >= 0 and c < m and image[r][c] == oldColor):
return True
return False
def floodFillDFS(self, image, sr, sc, n, m, oldColor, color):
image[sr][sc] = color
if self.isValid(image, sr + 1, sc, n, m, oldColor):
self.floodFillDFS(image, sr + 1, sc, n, m, oldColor, color)
if self.isValid(image, sr - 1, sc, n, m, oldColor):
self.floodFillDFS(image, sr - 1, sc, n, m, oldColor, color)
if self.isValid(image, sr, sc + 1, n, m, oldColor):
self.floodFillDFS(image, sr, sc + 1, n, m, oldColor, color)
if self.isValid(image, sr, sc - 1, n, m, oldColor):
self.floodFillDFS(image, sr, sc - 1, n, m, oldColor, color) | flood-fill | Simple python solution | DFS | 93% faster | nikhitamore | 0 | 39 | flood fill | 733 | 0.607 | Easy | 12,015 |
https://leetcode.com/problems/flood-fill/discuss/2449342/Flood-Fill-oror-Python3-oror-DFS | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
if(image[sr][sc] == color):
return image
def dfs(sr, sc, src_color, color, image):
image[sr][sc] = color
for nx, ny in ((sr+1, sc), (sr, sc+1), (sr-1, sc), (sr, sc-1)):
if(nx < 0 or ny < 0 or nx >= len(image) or ny >= len(image[0]) or image[nx][ny] != src_color):
continue
dfs(nx, ny, src_color, color, image)
dfs(sr, sc, image[sr][sc], color, image)
return image | flood-fill | Flood Fill || Python3 || DFS | vanshika_2507 | 0 | 62 | flood fill | 733 | 0.607 | Easy | 12,016 |
https://leetcode.com/problems/flood-fill/discuss/2448952/Python-Easy-DFS-Solution-oror-Documented | class Solution:
# Time: O(m * n) Space: O(m * n)
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
if image[sr][sc] == color: # color is already set
return image
oldColor = image[sr][sc] # old color at starting pixel
rows, cols = len(image), len(image[0]) # number of rows and columns
def dfs(i, j):
image[i][j] = color # modify the new color
if i+1 < rows and image[i+1][j] == oldColor: # check and go downward
dfs(i+1, j)
if j+1 < cols and image[i][j+1] == oldColor: # check and go right side
dfs(i, j+1)
if i-1 >= 0 and image[i-1][j] == oldColor: # check and go upward
dfs(i-1, j)
if j-1 >= 0 and image[i][j-1] == oldColor: # check and go left side
dfs(i, j-1)
dfs(sr, sc) # start with given pixel
return image | flood-fill | [Python] Easy DFS Solution || Documented | Buntynara | 0 | 28 | flood fill | 733 | 0.607 | Easy | 12,017 |
https://leetcode.com/problems/flood-fill/discuss/2414184/Different-And-Intuitive-Solution-or-Actually-flood-filling | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
if image[sr][sc] == color:
return image
m = len(image)
n = len(image[0])
stack = [(sr,sc, image[sr][sc] + color)]
while stack:
x = stack.pop(0)
if x[0] + 1 < m and image[x[0] + 1][x[1]] == x[2] - color:
stack.append((x[0] + 1, x[1], x[2]))
if x[0] - 1 > -1 and image[x[0] - 1][x[1]] == x[2] - color:
stack.append((x[0] - 1, x[1], x[2]))
if x[1] + 1 < n and image[x[0]][x[1] + 1] == x[2] - color:
stack.append((x[0], x[1] + 1, x[2]))
if x[1] - 1 > - 1 and image[x[0]][x[1] -1] == x[2] - color:
stack.append((x[0], x[1] - 1, x[2]))
image[x[0]][x[1]] = color
return image | flood-fill | Different And Intuitive Solution | Actually flood filling | May-i-Code | 0 | 33 | flood fill | 733 | 0.607 | Easy | 12,018 |
https://leetcode.com/problems/flood-fill/discuss/2408774/C%2B%2BPython-Best-Optimized-Solution-with-best-approach | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
m = len(image)
n = len(image[0])
visited = [[None for _ in range(n)] for _ in range(m)]
initialColor = image[sr][sc]
queue = [(sr,sc)]
while queue:
sr, sc = queue.pop(0)
visited[sr][sc] = True
image[sr][sc] = newColor
for dsr, dsc in [(sr+1, sc), (sr-1, sc), (sr, sc+1), (sr, sc-1)]:
if 0 <= dsr < m and 0 <= dsc < n and not visited[dsr][dsc] and image[dsr][dsc] == initialColor:
queue.append((dsr, dsc))
return image | flood-fill | C++/Python Best Optimized Solution with best approach | arpit3043 | 0 | 65 | flood fill | 733 | 0.607 | Easy | 12,019 |
https://leetcode.com/problems/flood-fill/discuss/2398563/Easy-Python-BFS | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
# if starting pixel is already the target color, no change needed
if image[sr][sc] == color:
return image
original_color = image[sr][sc]
q = deque([(sr, sc)])
directions = [[-1, 0], # up
[0, 1], # right
[1, 0], # down
[0, -1]] # left
image[sr][sc] = color # change source pixel to new color
while q:
current = q.popleft()
row = current[0]
col = current[1]
for direction in directions:
next_row = row + direction[0]
next_col = col + direction[1]
if 0 <= next_row < len(image) and 0 <= next_col < len(image[0]) and image[next_row][next_col] == original_color:
image[next_row][next_col] = color
q.append((next_row, next_col))
return image | flood-fill | Easy Python BFS | lau125 | 0 | 27 | flood fill | 733 | 0.607 | Easy | 12,020 |
https://leetcode.com/problems/flood-fill/discuss/2366222/Python3-or-Straightforward-BFS-%2B-Queue-%2B-Set-No-Helper-Needed | class Solution:
#Time-Complexity: O(rows*cols)
#Space-Complexity: O(rows*cols + rows*cols) -> O(rows*cols)
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
#this is a standard bfs problem!
#we will add to queue pixels that share same color as the starting pixel point
#that have not already been visited!
#For each element we dequeue from queue, we will overwrite that entry with the new
#color!
#our answer will return image parameter that is modified in-place!
rows, cols = len(image), len(image[0])
visited = set()
q = collections.deque()
orig_color = image[sr][sc]
q.append([sr, sc])
visited.add((sr, sc))
four_directions = [[1,0],[-1,0], [0,1], [0,-1]]
#initiate bfs!
while q:
cr, cc = q.popleft()
image[cr][cc] = color
#iterate through each of four directional neighbors!
for direction in four_directions:
r_change, c_change = direction
if(cr + r_change in range(rows) and
cc + c_change in range(cols) and
image[cr+r_change][cc+c_change] == orig_color and
(cr+r_change, cc+c_change) not in visited):
q.append([cr+r_change, cc+c_change])
visited.add((cr+r_change, cc+c_change))
#once bfs ends, return grid changed in place!
return image | flood-fill | Python3 | Straightforward BFS + Queue + Set No Helper Needed | JOON1234 | 0 | 41 | flood fill | 733 | 0.607 | Easy | 12,021 |
https://leetcode.com/problems/flood-fill/discuss/2245485/Python%3A-Faster-than-93-using-queue | class Solution:
def add_connected(self, image, e, src_color, color, maxr, maxc, queue):
if e[0] < 0 or e[0] > maxr or e[1] < 0 or e[1] > maxc:
return
if image[e[0]][e[1]] != src_color:
return
queue.append(e)
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
if image[sr][sc] == color:
return image
src_color = image[sr][sc]
maxr = len(image) - 1
maxc = len(image[0]) - 1
queue = [(sr,sc)]
while queue:
e = queue.pop()
image[e[0]][e[1]] = color
self.add_connected(image, (e[0]-1,e[1]), src_color, color, maxr, maxc, queue)
self.add_connected(image, (e[0],e[1]-1), src_color, color, maxr, maxc, queue)
self.add_connected(image, (e[0],e[1]+1), src_color, color, maxr, maxc, queue)
self.add_connected(image, (e[0]+1,e[1]), src_color, color, maxr, maxc, queue)
return image | flood-fill | Python: Faster than 93% using queue | pradyumna04 | 0 | 62 | flood fill | 733 | 0.607 | Easy | 12,022 |
https://leetcode.com/problems/flood-fill/discuss/2235994/Python-runtime-15.95-memory-65.65 | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
oriColor = image[sr][sc]
if oriColor == newColor:
return image
image[sr][sc] = newColor
for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
if -1<sr+dr<len(image) and -1<sc+dc<len(image[0]) and image[sr+dr][sc+dc] == oriColor:
self.floodFill(image, sr+dr, sc+dc, newColor)
return image | flood-fill | Python, runtime 15.95% memory 65.65% | tsai00150 | 0 | 39 | flood fill | 733 | 0.607 | Easy | 12,023 |
https://leetcode.com/problems/flood-fill/discuss/2235994/Python-runtime-15.95-memory-65.65 | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
oriColor = image[sr][sc]
if oriColor == newColor:
return image
queue = [(sr, sc)]
while queue:
row, col = queue.pop()
image[row][col] = newColor
for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
if -1<row+dr<len(image) and -1<col+dc<len(image[0]) \
and image[row+dr][col+dc] == oriColor:
queue.append((row+dr, col+dc))
return image | flood-fill | Python, runtime 15.95% memory 65.65% | tsai00150 | 0 | 39 | flood fill | 733 | 0.607 | Easy | 12,024 |
https://leetcode.com/problems/flood-fill/discuss/2165553/Easy-and-Simple-DFS | class Solution:
def isSafe(self, i,j,grid):
n = len(grid)
m = len(grid[0])
if 0 <= i < n and 0 <= j < m:
return True
else:
return False
def dfs(self,i,j,value,grid,color):
if not self.isSafe(i,j,grid) or grid[i][j] == color:
return
if grid[i][j] == value:
grid[i][j] = color
self.dfs(i,j-1,value,grid,color)
self.dfs(i-1,j,value,grid,color)
self.dfs(i+1,j,value,grid,color)
self.dfs(i,j+1,value,grid,color)
return
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
n = len(image)
m = len(image[0])
val = image[sr][sc]
self.dfs(sr, sc,val, image,color)
return image | flood-fill | Easy and Simple DFS | Vaibhav7860 | 0 | 86 | flood fill | 733 | 0.607 | Easy | 12,025 |
https://leetcode.com/problems/flood-fill/discuss/2065951/Python-Simple-DFS-Solution | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
self.dfs(image, sr, sc, image[sr][sc], newColor)
return image
def dfs(self, image, m, n, oldValue, newValue):
if m < 0 or m > len(image)-1 or n < 0 or n > len(image[0])-1 or image[m][n] == newValue:
return
if image[m][n] == oldValue:
image[m][n] = newValue
self.dfs(image, m-1, n, oldValue, newValue)
self.dfs(image, m+1, n, oldValue, newValue)
self.dfs(image, m, n-1, oldValue, newValue)
self.dfs(image, m, n+1, oldValue, newValue)
return | flood-fill | Python Simple DFS Solution | yashchandani98 | 0 | 77 | flood fill | 733 | 0.607 | Easy | 12,026 |
https://leetcode.com/problems/flood-fill/discuss/2061286/Python-Simple-readable-easy-to-understand-DFS-solution-(Faster-than-69) | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
startColor = image[sr][sc]
if startColor != newColor:
self.fill(image, sr, sc, startColor, newColor)
return image
def fill(self, image: List[List[int]], r:int, c:int, start:int, new: int):
if image[r][c] == start:
image[r][c] = new
if r > 0:
self.fill(image, r - 1, c, start, new)
if c > 0:
self.fill(image, r, c - 1, start, new)
if r < len(image) - 1:
self.fill(image, r + 1, c, start, new)
if c < len(image[0]) - 1:
self.fill(image, r, c + 1, start, new) | flood-fill | [Python] Simple, readable, easy to understand DFS solution (Faster than 69%) | FedMartinez | 0 | 62 | flood fill | 733 | 0.607 | Easy | 12,027 |
https://leetcode.com/problems/flood-fill/discuss/1928649/Easy-and-90ms-Fast-Solution-in-Python-using-Set-T.C-greaterO(n) | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
color=image[sr][sc]
height=len(image)
width=len(image[0])
visit=set()
def dfs(image,sr,sc,newColor,visit):
image[sr][sc]=newColor
visit.add((sr,sc))
if sr>0 and (sr-1,sc) not in visit and image[sr-1][sc]==color:
dfs(image,sr-1,sc,newColor,visit)
if sr<height-1 and (sr+1,sc) not in visit and image[sr+1][sc]==color:
dfs(image,sr+1,sc,newColor,visit)
if sc>0 and (sr,sc-1) not in visit and image[sr][sc-1]==color:
dfs(image,sr,sc-1,newColor,visit)
if sc<width-1 and (sr,sc+1) not in visit and image[sr][sc+1]==color:
dfs(image,sr,sc+1,newColor,visit)
return image
return dfs(image,sr,sc,newColor,visit) | flood-fill | Easy and 90ms Fast Solution in Python using Set T.C->O(n) | karansinghsnp | 0 | 55 | flood fill | 733 | 0.607 | Easy | 12,028 |
https://leetcode.com/problems/flood-fill/discuss/1892383/Easy-Python3-DFS-Solution-oror-Recursion | class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
rows = len(image)
cols = len(image[0])
color_to_change = image[sr][sc]
def dfs(r,c):
if(r<0 or c<0 or r>rows-1 or c>cols-1 or image[r][c] == newColor or image[r][c]!=color_to_change):
return
image[r][c] = newColor
#iterate through all four directions
dfs(r+1,c)
dfs(r-1,c)
dfs(r,c+1)
dfs(r,c-1)
dfs(sr,sc)
return image | flood-fill | Easy Python3 DFS Solution || Recursion | darshanraval194 | 0 | 69 | flood fill | 733 | 0.607 | Easy | 12,029 |
https://leetcode.com/problems/asteroid-collision/discuss/646757/Python3-concise-solution-Asteroid-Collision | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
for a in asteroids:
if a > 0:
stack.append(a)
else:
while stack and stack[-1] > 0 and stack[-1] + a < 0:
stack.pop()
if not stack or stack[-1] < 0:
stack.append(a)
elif stack[-1] + a == 0:
stack.pop()
return stack | asteroid-collision | Python3 concise solution - Asteroid Collision | r0bertz | 5 | 426 | asteroid collision | 735 | 0.444 | Medium | 12,030 |
https://leetcode.com/problems/asteroid-collision/discuss/1794866/Python-or-Stack-or-Explanation-%2B-Complexity | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
for asteroid in asteroids:
# if there's things on the stack, we need to consider if we've got case 4
while stack and stack[-1] > 0 and asteroid < 0:
# determine which asteroids are exploding
if abs(stack[-1]) < abs(asteroid):
stack.pop()
# considered asteroid might still destroy others so continue checking
continue
elif abs(stack[-1]) == abs(asteroid):
stack.pop()
break
# if nothing on the stack, or cases 1-3, just append
else:
stack.append(asteroid)
return stack | asteroid-collision | Python | Stack | Explanation + Complexity | leetbeet73 | 4 | 241 | asteroid collision | 735 | 0.444 | Medium | 12,031 |
https://leetcode.com/problems/asteroid-collision/discuss/1566988/Extremely-Easy-oror-100-faster-oror-Well-Coded | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
st = []
for a in asteroids:
if a>0:
st.append(a)
else:
while len(st)>0 and st[-1]>0 and st[-1]<abs(a):
st.pop()
if len(st)==0 or st[-1]<0:
st.append(a)
elif st[-1]==abs(a):
st.pop()
return st | asteroid-collision | 📌📌 Extremely Easy || 100% faster || Well-Coded 🐍 | abhi9Rai | 2 | 175 | asteroid collision | 735 | 0.444 | Medium | 12,032 |
https://leetcode.com/problems/asteroid-collision/discuss/2844008/Asteroid-Collisions-oror-Simple-stack-solution | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack=[]
for i in asteroids:
if not len(stack): stack.append(i);continue
if stack[-1]<0 or i>0: stack.append(i);continue
while len(stack) and stack[-1]>0 and i<0:
if -i>stack[-1]:
stack.pop()
else:
curr = stack.pop()
i = None if curr==-i else curr
break
if i: stack.append(i)
# if len(stack): stack.pop()
# stack.append(i)
return stack | asteroid-collision | Asteroid Collisions || Simple stack solution | kushagra2709 | 0 | 1 | asteroid collision | 735 | 0.444 | Medium | 12,033 |
https://leetcode.com/problems/asteroid-collision/discuss/2840525/Python-Other-approach-%3A-Finite-state-machine-or-2-stacks-solution | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
INITIAL, PROCESS = 0, 1
state = INITIAL
s1, s2 = asteroids, []
while True:
if state == INITIAL:
s2.append(s1.pop())
state = PROCESS
elif state == PROCESS:
a, b = s1.pop(), s2.pop()
if (a > 0 and b < 0) and a + b == 0: pass #Wrong directions and equal magnitude
elif (a < 0 and b > 0) or a * b > 0: #Same sign or right direction
s2.append(b)
s2.append(a)
elif a * b < 0: #Diff sign
if abs(a) > abs(b): s1.append(a)
else: s2.append(b)
if not s1: break
if not s2: state = INITIAL
return reversed(s2) | asteroid-collision | [Python] Other approach : Finite state machine | 2 stacks solution | Nezuko-NoBamboo | 0 | 1 | asteroid collision | 735 | 0.444 | Medium | 12,034 |
https://leetcode.com/problems/asteroid-collision/discuss/2797753/Python3-solution-with-continue-and-break | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
# Start with empty stack
output = []
# Add asteroids to stack on the right, one by one.
for asteroid in asteroids: # O(n)
# If new asteroid is going left.
while output and asteroid < 0 < output[-1]:
# If same size as asteroid going right, both explode.
if abs(output[-1]) == abs(asteroid): # O(1)
output.pop() # O(1)
break
# If bigger than asteroid going right, destroy it
# "continue" so that re re-do the check with next asteroid
# on the right.
elif abs(output[-1]) < abs(asteroid): # O(1)
output.pop() # O(1)
continue
# If smaller than asteroid going right, it gets destroyed.
else:
break
# Add new asteroid to the stack (won't happen
# if we reached a break above).
else:
output.append(asteroid) # O(1)
return output | asteroid-collision | Python3 solution with continue and break | lucieperrotta | 0 | 2 | asteroid collision | 735 | 0.444 | Medium | 12,035 |
https://leetcode.com/problems/asteroid-collision/discuss/2790711/Python3-solution-with-a-more-clear-code-readability-than-official-solution | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
res = []
for a in asteroids:
while res and res[-1] > 0 and a < 0:
l,r = abs(res[-1]), abs(a)
if r < l:
break
elif r > l:
res.pop()
else:
res.pop()
break
else:
res.append(a)
return res | asteroid-collision | Python3 solution with a more clear code readability than official solution | ryabkin | 0 | 2 | asteroid collision | 735 | 0.444 | Medium | 12,036 |
https://leetcode.com/problems/asteroid-collision/discuss/2778646/Solution-to-Asteroid-Collison-Using-Stack | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
for asteroid in asteroids:
if asteroid < 0:
while stack and stack[-1] > 0 and abs(asteroid) > stack[-1]:
stack.pop()
if stack and stack[-1] > abs(asteroid):
continue
elif stack and stack[-1] == abs(asteroid):
stack.pop()
else:
stack.append(asteroid)
else:
stack.append(asteroid)
return stack | asteroid-collision | Solution to Asteroid Collison Using Stack | aman_22y | 0 | 9 | asteroid collision | 735 | 0.444 | Medium | 12,037 |
https://leetcode.com/problems/asteroid-collision/discuss/2680853/Python-stack-solution-with-comments | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
ans, q, i, n = [], deque(), 0, len(asteroids)
while i < len(asteroids):
should_append = True
while q and q[-1]> 0 and asteroids[i] < 0:
if abs(asteroids[i]) > q[-1]:
# If negative asteroid destroys all positive then append this negative to queue
q.pop()
elif asteroids[i] == -q[-1]:
# Shouldn't append negative asteroid since both are destroyed
q.pop()
should_append = False
break
else:
# Shouldn't append negative asteroid since positive astreroid destroyed negative one
should_append = False
break
if should_append:
# two cases can reach here
# 1. Asteroid is positive
# 2. Negative asteroid which has destroyed all smaller positive asteroids
q.append(asteroids[i])
i += 1
return q | asteroid-collision | Python - stack solution with comments | phantran197 | 0 | 5 | asteroid collision | 735 | 0.444 | Medium | 12,038 |
https://leetcode.com/problems/asteroid-collision/discuss/2671874/EASY-oror-Using-Stack-oror-SC-and-TC-O(N) | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stck = []
n = len(asteroids)
for i in range(len(asteroids)-1, -1, -1):
if asteroids[i] < 0:
stck.append(asteroids[i])
else:
while stck and stck[-1] < 0 and asteroids[i] > abs(stck[-1]):
stck.pop(-1)
if stck and stck[-1] < 0 and asteroids[i] == abs(stck[-1]):
stck.pop(-1)
elif stck and stck[-1] < 0 and asteroids[i] < abs(stck[-1]):
continue
else:
stck.append(asteroids[i])
stck.reverse()
return stck | asteroid-collision | EASY || Using Stack || SC & TC = O(N) | mihirshah0114 | 0 | 3 | asteroid collision | 735 | 0.444 | Medium | 12,039 |
https://leetcode.com/problems/asteroid-collision/discuss/2475782/Python-runtime-72.35-memory-25.35 | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
for e in asteroids:
while stack and stack[-1] > 0 and e < 0:
if stack[-1] < -e:
stack.pop()
elif stack[-1] == -e:
stack.pop()
break
else:
break
else:
stack.append(e)
return stack | asteroid-collision | Python, runtime 72.35%, memory 25.35% | tsai00150 | 0 | 31 | asteroid collision | 735 | 0.444 | Medium | 12,040 |
https://leetcode.com/problems/asteroid-collision/discuss/2333697/Python-Plain-Stack-90-faster | class Solution(object):
def asteroidCollision(self, asteroids):
stack = []
for ch in asteroids:
if ch>0:
stack.append(ch)
elif ch<0:
stack.append(ch)
while len(stack)>1 and stack[-2]>0 and stack[-1]<0:
ch = stack.pop()
val = stack.pop()
if ch == val:
pass
elif abs(val)>abs(ch):
stack.append(val)
elif abs(ch)>abs(val):
stack.append(ch)
return stack | asteroid-collision | Python Plain Stack 90% faster | Abhi_009 | 0 | 62 | asteroid collision | 735 | 0.444 | Medium | 12,041 |
https://leetcode.com/problems/asteroid-collision/discuss/2332787/Python-oror-Easy-(but-not-efficient)-Recursion | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
if all( asteroids[i] > 0 for i in range(len(asteroids))): return asteroids
if all( asteroids[i] < 0 for i in range(len(asteroids))): return asteroids
if not asteroids: return asteroids
n = len(asteroids)
j = 0
while asteroids[j] < 0: j += 1
while j < n and asteroids[j] > 0: j += 1
if j == n: return asteroids
i = 0
while i + 1 < n:
if asteroids[i] < 0:
i += 1
continue
if asteroids[i] > 0 and asteroids[i+1] < 0:
if asteroids[i] > abs(asteroids[i+1]):
return self.asteroidCollision(asteroids[:i+1] + asteroids[i+2:])
elif abs(asteroids[i+1]) > asteroids[i]:
return self.asteroidCollision(asteroids[:i] + asteroids[i+1:])
else: return self.asteroidCollision(asteroids[:i] + asteroids[i+2:])
i += 1 | asteroid-collision | Python || Easy (but not efficient) Recursion | morpheusdurden | 0 | 21 | asteroid collision | 735 | 0.444 | Medium | 12,042 |
https://leetcode.com/problems/asteroid-collision/discuss/2270364/stack-solution | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = [asteroids[0]]
for a in asteroids[1:]:
if len(stack) == 0 or a * stack[-1] > 0:
stack.append(a)
else:
while len(stack) > 0 and stack[-1] > 0 and abs(a) > stack[-1]:
stack.pop()
if len(stack) > 0 and stack[-1] == abs(a):
stack.pop()
continue
if len(stack) == 0 or stack[-1] < 0:
stack.append(a)
return stack | asteroid-collision | stack solution | Mujojo | 0 | 31 | asteroid collision | 735 | 0.444 | Medium | 12,043 |
https://leetcode.com/problems/asteroid-collision/discuss/1807130/Python-Solution | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack=[]
for asteroid in asteroids:
if asteroid > 0:
stack.append(asteroid)
else:
append=True
while stack and stack[-1]>0:
if stack[-1]==abs(asteroid):
append=False
stack.pop()
break
elif stack[-1]>abs(asteroid):
append=False
break
else:
stack.pop()
append=True
if append is True:
stack.append(asteroid)
return stack | asteroid-collision | Python Solution | Siddharth_singh | 0 | 82 | asteroid collision | 735 | 0.444 | Medium | 12,044 |
https://leetcode.com/problems/asteroid-collision/discuss/1780271/Python-easy-to-read-and-understand-or-stack | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
for asteroid in asteroids:
if asteroid > 0:
stack.append(asteroid)
else:
while stack and stack[-1] > 0 and abs(stack[-1]) < abs(asteroid):
stack.pop()
if stack and stack[-1] == abs(asteroid):
stack.pop()
elif not stack or stack[-1] < 0:
stack.append(asteroid)
#print(stack)
return stack | asteroid-collision | Python easy to read and understand | stack | sanial2001 | 0 | 82 | asteroid collision | 735 | 0.444 | Medium | 12,045 |
https://leetcode.com/problems/asteroid-collision/discuss/1711954/Python-or-Stack | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stk=[]
for n in asteroids:
if n>0 or not stk or stk[-1]<0:
stk.append(n)
continue
else:
m=-n
if m>=stk[-1]:
while stk and stk[-1]>0 and stk[-1]<m:#first remove all the smaller pices
stk.pop()
if stk and stk[-1]==m:#then remove equal piece
stk.pop()
continue
if not stk or (stk and stk[-1]<0):
stk.append(n)
return stk | asteroid-collision | Python | Stack | heckt27 | 0 | 33 | asteroid collision | 735 | 0.444 | Medium | 12,046 |
https://leetcode.com/problems/asteroid-collision/discuss/1675846/Python-stack.-Time%3A-O(N)-Space%3A-O(N) | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
left = []
right = []
for a in asteroids:
if a > 0:
right.append(a)
else:
while right and -a > right[-1]:
right.pop()
if not right:
left.append(a)
elif right[-1] == -a:
right.pop()
return left + right | asteroid-collision | Python, stack. Time: O(N), Space: O(N) | blue_sky5 | 0 | 68 | asteroid collision | 735 | 0.444 | Medium | 12,047 |
https://leetcode.com/problems/asteroid-collision/discuss/1670099/WEEB-DOES-PYTHON-USING-STACK-(BEATS-89.93) | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
low, high = 0, 0
result = []
isPositive = False
stack = [] # stores right asteroids
for i in range(len(asteroids)):
if asteroids[i] < 0 and isPositive:
if stack[-1] > abs(asteroids[i]): # right > left
continue
elif stack[-1] == abs(asteroids[i]): # right == left
stack.pop()
if not stack: # what if we pop the last element in the stack?? If so, then no more positive valyes, so isPositive = False
isPositive = False
continue
else: # right < left
while stack and stack[-1] < abs(asteroids[i]): # keep popping until right > left
stack.pop()
if stack and stack[-1] == abs(asteroids[i]): #edge case checking,if right == left
stack.pop()
if not stack: #edge case in another edge case, what if we pop the last element in the stack?? If so, then no more positive values, so isPositive = False
isPositive = False
continue
elif stack and stack[-1] > abs(asteroids[i]): #edge case checking,if right > left
continue
elif not stack: # edge case checking, if stack doesn't exist at all after popping
isPositive = False
if asteroids[i] > 0 and not isPositive: # get the first right moving asteroid
isPositive = True
if isPositive: # we only want right moving asteroids in stack
stack.append(asteroids[i])
if asteroids[i] < 0 and not stack: # stack is empty, so nothing can explode left moving asteroids
result.append(asteroids[i])
result += stack # add the remaining right moving asteroid since no more left moving asteroids
return result | asteroid-collision | WEEB DOES PYTHON USING STACK (BEATS 89.93%) | Skywalker5423 | 0 | 57 | asteroid collision | 735 | 0.444 | Medium | 12,048 |
https://leetcode.com/problems/asteroid-collision/discuss/1621744/Python-90-faster | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
for asteroid in asteroids:
if asteroid < 0 and stack and stack[-1] > 0:
while stack and stack[-1] > 0 and asteroid < 0:
if abs(stack[-1]) == abs(asteroid):
stack.pop()
break
if abs(stack[-1]) < abs(asteroid):
stack.pop()
if not stack or stack[-1] < 0:
stack.append(asteroid)
else:
break
else:
stack.append(asteroid)
return stack | asteroid-collision | Python 90% faster | daniela-andreea | 0 | 101 | asteroid collision | 735 | 0.444 | Medium | 12,049 |
https://leetcode.com/problems/asteroid-collision/discuss/1536851/Python3-Stack-Time%3A-O(n)-and-Space%3A-O(n) | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
# Time: O(n)
# Space: O(n)
stackRight = []
ans = []
for a in asteroids:
if a < 0:
if len(stackRight) > 0:
val = abs(a)
while stackRight:
if val == stackRight[-1]:
stackRight.pop()
val = 0
break
elif val > stackRight[-1]:
stackRight.pop()
else:
val = 0
break
if val > 0:
ans.append(a)
else:
ans.append(a)
else:
stackRight.append(a)
return ans + stackRight | asteroid-collision | [Python3] Stack - Time: O(n) & Space: O(n) | jae2021 | 0 | 84 | asteroid collision | 735 | 0.444 | Medium | 12,050 |
https://leetcode.com/problems/asteroid-collision/discuss/1446968/Self-explanatory-python-code | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
# O(n) O(n)
stack = []
res = []
for i in range(len(asteroids)):
collid = False
if asteroids[i] > 0:
stack.append(asteroids[i])
continue
while stack and asteroids[i] < 0:
if stack[-1] < abs(asteroids[i]):
stack.pop()
elif stack[-1] == abs(asteroids[i]):
collid = True
stack.pop()
break
else:
break
if stack == [] and collid == False:
res.append(asteroids[i])
res.extend(stack)
return res | asteroid-collision | Self explanatory python code | maflint7 | 0 | 85 | asteroid collision | 735 | 0.444 | Medium | 12,051 |
https://leetcode.com/problems/asteroid-collision/discuss/1441107/Python3-Solution-based-on-stack | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = [0]
for asteroid in asteroids:
if asteroid < 0 and stack[-1] > 0:
while asteroid != 0 and stack[-1] > 0:
to_right = stack.pop()
if to_right > abs(asteroid):
stack.append(to_right)
asteroid = 0
elif to_right == abs(asteroid):
asteroid = 0
if asteroid != 0:
stack.append(asteroid)
else:
stack.append(asteroid)
return stack[1:] | asteroid-collision | [Python3] Solution based on stack | maosipov11 | 0 | 40 | asteroid collision | 735 | 0.444 | Medium | 12,052 |
https://leetcode.com/problems/asteroid-collision/discuss/958014/Easy-Python3-solution | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
i = 0
while i < len(asteroids)-1:
if i >= 0:
#if right element is negative and current is positive then do further checking
if asteroids[i] > 0 and asteroids[i+1] < 0:
if abs(asteroids[i]) < abs(asteroids[i+1]):
asteroids.pop(i)
i = i - 1 #reset i
elif abs(asteroids[i]) > abs(asteroids[i+1]):
asteroids.pop(i+1)
i = i - 1 #reset i
else:
asteroids.pop(i)
asteroids.pop(i)
i = i - 2 #reset i
else:
i += 1
else:
i = 0 #reset i
return asteroids | asteroid-collision | Easy Python3 solution | Pseudocoder_Ravina | 0 | 95 | asteroid collision | 735 | 0.444 | Medium | 12,053 |
https://leetcode.com/problems/asteroid-collision/discuss/602232/Python3-Runtime-easy-to-understand | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
survivalStack = []
for asteroid in asteroids:
while survivalStack and asteroid < 0 < survivalStack[-1]:
challenger = survivalStack[-1]
_challenger, _asteroid = abs(challenger), abs(asteroid)
if _challenger < _asteroid:
survivalStack.pop()
continue
elif _challenger == _asteroid:
survivalStack.pop()
break
else:
survivalStack.append(asteroid)
return survivalStack | asteroid-collision | Python3 Runtime easy to understand | lastnamehurt | 0 | 102 | asteroid collision | 735 | 0.444 | Medium | 12,054 |
https://leetcode.com/problems/asteroid-collision/discuss/509953/Python-O(n)-Code-with-Clear-Explanation | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
ans = []
for a in asteroids:
if a > 0:
ans.append(a)
else:
appendFlag = True
while ans:
if ans[-1] < 0:
break
else:
if ans[-1] + a < 0:
ans.pop(-1)
elif ans[-1] + a == 0:
ans.pop(-1)
appendFlag = False
break
else:
appendFlag = False
break
if appendFlag:
ans.append(a)
return ans | asteroid-collision | Python O(n) Code with Clear Explanation | sjtuluo | 0 | 198 | asteroid collision | 735 | 0.444 | Medium | 12,055 |
https://leetcode.com/problems/parse-lisp-expression/discuss/2149196/Python3-Solution | class Solution:
def evaluate(self, expression: str) -> int:
stack = []
parenEnd = {}
# Get the end parenthesis location
for idx, ch in enumerate(expression):
if ch == '(':
stack.append(idx)
if ch == ')':
parenEnd[stack.pop()] = idx
# Parses the expression into a list, each new sublist is a set of parenthesis
# Example:
# Input: "(let x 2 (mult x (let x 3 y 4 (add x y))))"
# Output: ['let', 'x', '2', ['mult', 'x', ['let', 'x', '3', 'y', '4', ['add', 'x', 'y']]]]
def parse(lo, hi):
arr = []
word = []
i = lo
while i < hi:
if expression[i] == '(':
arr.append(parse(i + 1, parenEnd[i]))
i = parenEnd[i]
elif expression[i] == ' ' or expression[i] == ')' and word != []:
if ''.join(word) != '':
arr.append(''.join(word))
word = []
i += 1
elif expression[i] != ')':
word.append(expression[i])
i += 1
else:
i += 1
if word != []:
arr.append(''.join(word))
return arr
# Change string expression into the list expression
expressionList = parse(1, len(expression) - 1)
# Eval expression with starting scope (variables)
return self.genEval(expressionList, {})
def genEval(self, expression, scope):
if type(expression) != list:
# If expression is just a variable or int
try:
return int(expression)
except:
return scope[expression]
else:
if expression[0] == 'let':
# Remove "let" from expression list
expression = expression[1:]
# This loop updates the scope (variables)
while len(expression) > 2:
scope = self.letEval(expression, scope.copy())
expression = expression[2:]
# Return the last value
return self.genEval(expression[0], scope.copy())
if expression[0] == 'add':
return self.addEval(expression, scope.copy())
if expression[0] == 'mult':
return self.multEval(expression, scope.copy())
def letEval(self, expression, scope):
scope[expression[0]] = self.genEval(expression[1], scope)
return scope
def addEval(self, expression, scope):
return self.genEval(expression[1], scope) + self.genEval(expression[2], scope)
def multEval(self, expression, scope):
return self.genEval(expression[1], scope) * self.genEval(expression[2], scope) | parse-lisp-expression | Python3 Solution | krzys2194 | 1 | 113 | parse lisp expression | 736 | 0.515 | Hard | 12,056 |
https://leetcode.com/problems/parse-lisp-expression/discuss/1358397/Python3-recursion | class Solution:
def evaluate(self, expression: str) -> int:
loc = {}
stack = []
for i, x in enumerate(expression):
if x == "(": stack.append(i)
elif x == ")": loc[stack.pop()] = i
def fn(lo, hi, mp):
"""Return value of given expression."""
if expression[lo] == "(": return fn(lo+1, hi-1, mp)
i = lo
vals = []
while i < hi:
if expression[i:i+3] in ("let", "add"):
op = expression[i:i+3]
i += 3
elif expression[i:i+4] == "mult":
op = "mult"
i += 4
elif expression[i].isalpha():
x = ""
while i < hi and expression[i].isalnum():
x += expression[i]
i += 1
if op in ("add", "mult"): vals.append(mp[x])
elif expression[i].isdigit() or expression[i] == "-":
v = ""
while i < hi and (expression[i].isdigit() or expression[i] == "-"):
v += expression[i]
i += 1
if op == "let": mp[x] = int(v)
else: vals.append(int(v))
elif expression[i] == "(":
v = fn(i+1, loc[i], mp.copy())
i = loc[i] + 1
if op == "let": mp[x] = v
else: vals.append(v)
else: i += 1
if op == "let": return int(v)
elif op == "add": return sum(vals)
else: return reduce(mul, vals)
return fn(0, len(expression), {}) | parse-lisp-expression | [Python3] recursion | ye15 | -1 | 203 | parse lisp expression | 736 | 0.515 | Hard | 12,057 |
https://leetcode.com/problems/monotone-increasing-digits/discuss/921119/Python3-O(N)-via-stack | class Solution:
def monotoneIncreasingDigits(self, N: int) -> int:
nums = [int(x) for x in str(N)] # digits
stack = []
for i, x in enumerate(nums):
while stack and stack[-1] > x: x = stack.pop() - 1
stack.append(x)
if len(stack) <= i: break
return int("".join(map(str, stack)).ljust(len(nums), "9")) # right padding with "9" | monotone-increasing-digits | [Python3] O(N) via stack | ye15 | 1 | 126 | monotone increasing digits | 738 | 0.471 | Medium | 12,058 |
https://leetcode.com/problems/monotone-increasing-digits/discuss/362053/Solution-in-Python-3-(beats-95) | class Solution:
def monotoneIncreasingDigits(self, n: int) -> int:
N = [int(i) for i in str(n)]
L = len(N)
for I in range(L-1):
if N[I] > N[I+1]: break
if N[I] <= N[I+1]: return n
N[I+1:], N[I] = [9]*(L-I-1), N[I] - 1
for i in range(I,0,-1):
if N[i] >= N[i-1]: break
N[i], N[i-1] = 9, N[i-1] - 1
return sum([N[i]*10**(L-i-1) for i in range(L)])
- Junaid Mansuri
(LeetCode ID)@hotmail.com | monotone-increasing-digits | Solution in Python 3 (beats 95%) | junaidmansuri | 1 | 440 | monotone increasing digits | 738 | 0.471 | Medium | 12,059 |
https://leetcode.com/problems/monotone-increasing-digits/discuss/2739671/Python-3-Solution | class Solution:
def monotoneIncreasingDigits(self, n: int) -> int:
res = ""
temp = str(n)[0]
last = str(n)[0]
d = len(str(n))
k = 1
for x in str(n)[1:]:
if int(x)>int(temp):
res += str(temp)*k
k = 1
elif int(x) == int(temp):
k += 1
else:
last = str(temp)
return int(res + str(int(last)-1) + "9"*(d-len(res)-1))
temp = x
return int(res+str(n)[-1]*k) | monotone-increasing-digits | Python 3 Solution | mati44 | 0 | 6 | monotone increasing digits | 738 | 0.471 | Medium | 12,060 |
https://leetcode.com/problems/monotone-increasing-digits/discuss/2672029/Greedy-oror-O(N)-oror-Python | class Solution:
def monotoneIncreasingDigits(self, n: int) -> int:
n = str(n)
n = list(n)
n[0] = int(n[0])
for i in range(1, len(n)):
n[i] = int(n[i])
if n[i] < n[i-1]:
for j in range(i-1, -1, -1):
if n[j+1] < n[j]:
n[j] = n[j] - 1
n[j+1] = 9
for k in range(i, len(n)):
n[k] = 9
break
res = n[0]
for i in range(1, len(n)):
res *= 10
res += n[i]
return res | monotone-increasing-digits | Greedy || O(N) || Python | mihirshah0114 | 0 | 4 | monotone increasing digits | 738 | 0.471 | Medium | 12,061 |
https://leetcode.com/problems/monotone-increasing-digits/discuss/2667810/Python3-Solution | class Solution:
def monotoneIncreasingDigits(self, n: int) -> int:
digits = [int(d) for d in str(n)]
if len(digits) == 1:
return n
l = 0
for i in range(1,len(digits)):
if digits[i] > digits[i-1]:
l = i
elif digits[i] < digits[i-1]:
digits[l] -= 1
for j in range(l+1,len(digits)):
digits[j] = 9
break
if digits[0] == 0:
digits.pop(0)
return int("".join([str(d) for d in digits])) | monotone-increasing-digits | Python3 Solution | tawaca | 0 | 4 | monotone increasing digits | 738 | 0.471 | Medium | 12,062 |
https://leetcode.com/problems/monotone-increasing-digits/discuss/2284761/Only-change-to-'9's-one-time!-By-Python | class Solution:
def monotoneIncreasingDigits(self, n: int) -> int:
num = list(str(n))
for i in range(len(num)-1):
# Step1: When don't meet the condition, num[i]-=1 and repalce all num left into '9' and directly return
# However, there is the case that num[i-1]==num[i], which will make num[i]-1<num[i-1]
# So, traverse back to find the num that its num[i-1] != num[i](to make sure num[i-1]<=num[i]-1), then do step1 and return
if num[i] > num[i+1]:
while i >= 1 and num[i-1] == num[i]:
i -= 1
num[i] = chr(ord(num[i])-1)
return int(''.join(num[:i+1]+['9']*(len(num)-i-1)))
return n | monotone-increasing-digits | Only change to '9's one time! By Python | XRFXRF | 0 | 42 | monotone increasing digits | 738 | 0.471 | Medium | 12,063 |
https://leetcode.com/problems/monotone-increasing-digits/discuss/1427954/Short-Python-with-detailed-explaination | class Solution:
def monotoneIncreasingDigits(self, N: int) -> int:
N = str(N)
cur = last = 0
# we scan through the string while keeping track of the
# last index such that its digit is STRICTLY GREATER than
# its next. This is the digits that we'll need to decrement
# and all digits after it will be 9. And all digits before it can
# stay the same for maximization.
# Consider "333333333322222", the solution of which is "299999999999999".
# The while loop breaks when we encounter the first "2". However, we can't
# simple decrement the "3" to the left of this "2" because decrementing it
# will cause further violations. This is way we need to keep track of the last digits
# that is STRICTLY GREATER than its next to leave room for the decrement.
while cur < len(N)-1 and int(N[cur]) <= int(N[cur+1]):
if int(N[cur]) != int(N[cur+1]):
last = cur+1
cur += 1
if cur == len(N)-1:
return int(N)
s1 = "" if last == 0 else str(int(N[:last])) # digits before last stay the same
s2 = str(int(N[last])-1) # digit at last decrement by 1
s3 = (len(N)-last-1)*'9' # digits after last changed to 9
return int(s1+s2+s3) | monotone-increasing-digits | Short Python with detailed explaination | Charlesl0129 | 0 | 107 | monotone increasing digits | 738 | 0.471 | Medium | 12,064 |
https://leetcode.com/problems/monotone-increasing-digits/discuss/1547284/O(n)-98-faster-oror-Simple-Logic-oror-Well-Explained | class Solution:
def monotoneIncreasingDigits(self, n: int) -> int:
s = str(n)
for i in range(len(s)-1,0,-1):
if s[i]<s[i-1]:
n = n-(int(s[i:])+1)
s = str(n)
return n | monotone-increasing-digits | 📌📌 O(n) 98% faster || Simple Logic || Well-Explained 🐍 | abhi9Rai | -3 | 139 | monotone increasing digits | 738 | 0.471 | Medium | 12,065 |
https://leetcode.com/problems/daily-temperatures/discuss/2506436/Python-Stack-97.04-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Monotonic-Stack | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
result = [0] * len(temperatures) # having list with 0`s elements of same lenght as temperature array.
stack = [] # taking empty stack.
for index, temp in enumerate(temperatures): # Traversing through provided list.
while stack and temperatures[stack[-1]] < temp: # stack should not be empty and checking previous temp with current temp.
# the above while loop and taking stack for saving index is very common practice in monotonic stack questions. Suggestion: understand it properly.
prev_temp = stack.pop() # stack.pop() will provide index of prev temp, taking in separate var as we are using it more then on place.
result[prev_temp] = index - prev_temp #at the index of prev_temp and i - prev_temp by this we`ll get how many step we moved to have greater temp.
stack.append(index) # in case stack is empty we`ll push index in it.
return result # returing the list of number of days to wait. | daily-temperatures | Python Stack 97.04% faster | Simplest solution with explanation | Beg to Adv | Monotonic Stack | rlakshay14 | 6 | 473 | daily temperatures | 739 | 0.666 | Medium | 12,066 |
https://leetcode.com/problems/daily-temperatures/discuss/1574891/Python-Brute-Force-Stack-Solutions-with-Explanation | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
l = len(temperatures)
result = [0] * l
for i in range(l-1):
for j in range(i+1, l):
if temperatures[j] > temperatures[i]:
result[i] = j-i
break
return result | daily-temperatures | [Python] Brute Force / Stack Solutions with Explanation | zayne-siew | 5 | 545 | daily temperatures | 739 | 0.666 | Medium | 12,067 |
https://leetcode.com/problems/daily-temperatures/discuss/1574891/Python-Brute-Force-Stack-Solutions-with-Explanation | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
l = len(temperatures)
result, stack = [0]*l, deque()
for i in range(l):
while stack and temperatures[stack[-1]] < temperatures[i]:
index = stack.pop()
result[index] = i-index
stack.append(i)
return result | daily-temperatures | [Python] Brute Force / Stack Solutions with Explanation | zayne-siew | 5 | 545 | daily temperatures | 739 | 0.666 | Medium | 12,068 |
https://leetcode.com/problems/daily-temperatures/discuss/486692/Python-Single-Pass-(Using-Stack)-6-liner | class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
res, stack = [0] * len(T), []
for i in range(len(T)):
while stack and T[stack[-1]] < T[i]:
res[stack.pop()] = i - stack[-1]
stack.append(i)
return res | daily-temperatures | Python - Single Pass (Using Stack) - 6 liner | mmbhatk | 4 | 1,100 | daily temperatures | 739 | 0.666 | Medium | 12,069 |
https://leetcode.com/problems/daily-temperatures/discuss/1446319/Python3-Decreasing-Stack | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
# decreasing stack
stack = []
n = len(temperatures)
res = [0] * n
for i in range(n):
t = temperatures[i]
while stack != [] and temperatures[stack[-1]] < t:
less_index = stack.pop()
res[less_index] = i - less_index
stack.append(i)
return res | daily-temperatures | [Python3] Decreasing Stack | zhanweiting | 3 | 274 | daily temperatures | 739 | 0.666 | Medium | 12,070 |
https://leetcode.com/problems/daily-temperatures/discuss/916764/Python3-forward-and-backward-via-mono-stack | class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
ans = [0]*len(T)
stack = []
for i in range(len(T)):
while stack and T[stack[-1]] < T[i]:
ii = stack.pop()
ans[ii] = i - ii
stack.append(i)
return ans | daily-temperatures | [Python3] forward & backward via mono-stack | ye15 | 3 | 159 | daily temperatures | 739 | 0.666 | Medium | 12,071 |
https://leetcode.com/problems/daily-temperatures/discuss/916764/Python3-forward-and-backward-via-mono-stack | class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
ans = [0]*len(T)
stack = []
for i in reversed(range(len(T))):
while stack and T[stack[-1]] <= T[i]: stack.pop() # mono-stack (decreasing)
if stack: ans[i] = stack[-1] - i
stack.append(i)
return ans | daily-temperatures | [Python3] forward & backward via mono-stack | ye15 | 3 | 159 | daily temperatures | 739 | 0.666 | Medium | 12,072 |
https://leetcode.com/problems/daily-temperatures/discuss/1573015/WEEB-DOES-PYTHON-MONOTONIC-STACK | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
result = [0] * len(temperatures)
stack = [] # stores index
# decreasing stack implementation
for i in range(len(temperatures)):
while stack and temperatures[stack[-1]] < temperatures[i]:
idx = stack.pop()
result[idx] = i - idx
stack.append(i)
return result | daily-temperatures | WEEB DOES PYTHON MONOTONIC STACK | Skywalker5423 | 2 | 136 | daily temperatures | 739 | 0.666 | Medium | 12,073 |
https://leetcode.com/problems/daily-temperatures/discuss/723606/Python-Stack-Solution-Easy-to-Understand | class Solution:
# Time: O(n)
# Space: O(n)
def dailyTemperatures(self, T: List[int]) -> List[int]:
stack = []
res = [0 for _ in range(len(T))]
for i, t1 in enumerate(T):
while stack and t1 > stack[-1][1]:
j, t2 = stack.pop()
res[j] = i - j
stack.append((i, t1))
return res | daily-temperatures | Python Stack Solution Easy to Understand | whissely | 2 | 484 | daily temperatures | 739 | 0.666 | Medium | 12,074 |
https://leetcode.com/problems/daily-temperatures/discuss/312214/Python3-concise-solution-with-stack | class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
stack=[]
res=[0]*len(T)
tem=list(enumerate(T))
for i,j in tem:
while stack and j>T[stack[-1]]:
res[stack[-1]]=i-stack[-1]
stack.pop()
stack.append(i)
return res | daily-temperatures | Python3 concise solution with stack | jasperjoe | 2 | 250 | daily temperatures | 739 | 0.666 | Medium | 12,075 |
https://leetcode.com/problems/daily-temperatures/discuss/2619084/Python3-Solution-or-Stack-or-O(n) | class Solution:
def dailyTemperatures(self, T):
n = len(T)
stack = []
ans = [0] * n
for i in range(n):
while stack and T[stack[-1]] < T[i]:
ans[stack.pop()] = i - stack[-1]
stack.append(i)
return ans | daily-temperatures | ✔ Python3 Solution | Stack | O(n) | satyam2001 | 1 | 64 | daily temperatures | 739 | 0.666 | Medium | 12,076 |
https://leetcode.com/problems/daily-temperatures/discuss/2177822/Easy-Python-Solution-with-steps-and-explanation.-Very-Fast | class Solution(object):
def dailyTemperatures(self, temperatures):
'''
====================================================================================================
1. Initialise result list with zeroes
2. Initialise the stack with the tuple of the first element and its index: (element,index)
3. Loop through the rest
4. If we find a temperature greater than what's on top of the stack,
we add the difference between their indices in results list
a) We then pop the stack and compare the next element while there are elements in the stack
5. Then we add the current temperature to the stack and repeat
6. The result list contains the index differences between the current and the next high temperature
====================================================================================================
'''
res=[0]*len(temperatures) # Step 1
stack=[(temperatures[0],0)] # Step 2
for i in range(1,len(temperatures)): # Step 3
while(stack and temperatures[i]>stack[-1][0]): # <———–––——————
res[stack[-1][1]] = i-stack[-1][1] # Step 4 |
stack.pop() # Step 4a __|
stack.append((temperatures[i],i)) # Step 5
return res # Step 6 | daily-temperatures | Easy Python Solution with steps and explanation. Very Fast | arnavjaiswal149 | 1 | 80 | daily temperatures | 739 | 0.666 | Medium | 12,077 |
https://leetcode.com/problems/daily-temperatures/discuss/1975705/Python3-Runtime%3A-1392ms-63.30-Memory%3A-24.9mb-58.78 | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
waitingList = [0] * len(temperatures)
stack = []
for idx, val in enumerate(temperatures):
while len(stack) > 0 and temperatures[stack[len(stack) - 1]] < val:
current = stack.pop()
waitingList[current] = idx - current
stack.append(idx)
return waitingList | daily-temperatures | Python3 Runtime: 1392ms 63.30% Memory: 24.9mb 58.78% | arshergon | 1 | 42 | daily temperatures | 739 | 0.666 | Medium | 12,078 |
https://leetcode.com/problems/daily-temperatures/discuss/1777898/Python-faster-than-80 | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
answer = [0] * len(temperatures)
maxi = temperatures[-1]
for i in range(len(answer) - 2, -1, -1):
if temperatures[i] >= maxi:
maxi = temperatures[i]
answer[i] = 0
else:
j = i + 1
while True:
if temperatures[j] > temperatures[i]:
answer[i] = j - i
break
j = j + answer[j]
return answer | daily-temperatures | Python faster than 80% | Swizop | 1 | 214 | daily temperatures | 739 | 0.666 | Medium | 12,079 |
https://leetcode.com/problems/daily-temperatures/discuss/1576457/Python-Solution | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
N = len(temperatures)
dp = [0] * N
stack = []
for i in range(N-1, -1, -1):
curr_temp, curr_idx = temperatures[i], i
while stack:
prev_temp, prev_idx = stack[-1]
if prev_temp > curr_temp:
dp[i] = abs(prev_idx - curr_idx)
break
else:
stack.pop()
stack.append((curr_temp,curr_idx))
return dp | daily-temperatures | Python Solution | ErikRodriguez-webdev | 1 | 70 | daily temperatures | 739 | 0.666 | Medium | 12,080 |
https://leetcode.com/problems/daily-temperatures/discuss/1360656/Python-using-monotonic-stack | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
n = len(temperatures)
stack = []
res = [0] * n
for i in range(n - 1, -1, -1):
temp = temperatures[i]
while stack and temperatures[stack[-1]] <= temp:
stack.pop()
res[i] = stack[-1] - i if stack else 0
stack.append(i)
return res | daily-temperatures | Python using monotonic stack | sherryfansf | 1 | 178 | daily temperatures | 739 | 0.666 | Medium | 12,081 |
https://leetcode.com/problems/daily-temperatures/discuss/1235383/Python-Simple-Stack-Solution | class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
stack=[]
res=[0]*len(T)
for x in range(len(T)-1,-1,-1):
while(stack and stack[-1][0]<=T[x]):
stack.pop()
if stack:
res[x]=stack[-1][1]-x
stack.append((T[x],x))
return res | daily-temperatures | Python Simple Stack Solution | abhinav4202 | 1 | 399 | daily temperatures | 739 | 0.666 | Medium | 12,082 |
https://leetcode.com/problems/daily-temperatures/discuss/650914/Intuitive-approach-by-using-cache-to-hold-examined-information-to-look-for-warmer-position | class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
ans = [0]
''' answer. The last temperature is always 0'''
cache = [(T[-1], len(T)-1)]
''' cache is used to hold the previous examined values'''
# Algorithm
# Cache is a list to hold a list of tuple(temperature, position)
# We example from the tail of the temperature list
# and look for nearest tuple with temperature just greater than
# the current temperature
for p in range(len(T)-2, -1, -1):
v = T[p]
while cache and cache[0][0] <= v:
# Pop out the tuple with temperature less than
# the current temperature. So the first element
# of cache should be the nearest position to have
# the temperature which just greater than the
# current temperature `v`
cache.pop(0)
if cache:
# Calculate the distance from current position
# from the nearest position to have higher temperature
ans.append(cache[0][1] - p)
else:
# Cache has no element which means no possibility
# to have temperature higher than current temperature
ans.append(0)
# Insert tuple(current temperature, position) into cache
cache.insert(0, (v, p))
return ans[::-1] | daily-temperatures | Intuitive approach by using cache to hold examined information to look for warmer position | puremonkey2001 | 1 | 63 | daily temperatures | 739 | 0.666 | Medium | 12,083 |
https://leetcode.com/problems/daily-temperatures/discuss/352495/Python-3-(-O(n)-time-)-(five-lines) | class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
N, F = [math.inf]*102, [0]*len(T)
for i in range(len(T)-1,-1,-1):
N[T[i]], m = i, min([N[i] for i in range(T[i]+1,102)])
if m != math.inf: F[i] = m - i
return F
- Junaid Mansuri
- Chicago, IL | daily-temperatures | Python 3 ( O(n) time ) (five lines) | junaidmansuri | 1 | 820 | daily temperatures | 739 | 0.666 | Medium | 12,084 |
https://leetcode.com/problems/daily-temperatures/discuss/2847280/Python-Monotonous-Stack-Solution | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
n = len(temperatures)
output_array = [0 for i in range(n)]
stack = []
for i in range(n):
while stack and temperatures[stack[-1]] < temperatures[i]:
index = stack.pop()
output_array[index] = i - index
stack.append(i)
return output_array | daily-temperatures | Python [Monotonous Stack Solution] | jamesg6198 | 0 | 1 | daily temperatures | 739 | 0.666 | Medium | 12,085 |
https://leetcode.com/problems/daily-temperatures/discuss/2840760/python3-easy-solution-using-stack | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
stack = []
t = temperatures
n = len(t)
out = []
for i in range(n-1,-1,-1):
if not stack:
out.append(0)
elif stack and stack[-1][0]>t[i]:
out.append(stack[-1][1]-i)
else:
while stack and stack[-1][0]<=t[i]:
stack.pop()
if stack:
out.append(stack[-1][1]-i)
else:
out.append(0)
stack.append([t[i],i])
# print(out)
return out[::-1] | daily-temperatures | python3 easy solution using stack | shashank732001 | 0 | 3 | daily temperatures | 739 | 0.666 | Medium | 12,086 |
https://leetcode.com/problems/daily-temperatures/discuss/2807606/Easy-Python-Solution-with-Stack | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
l=[]
stk=[]
for i in range(len(temperatures)-1,-1,-1):
if(len(stk)<=0):
l.append(0)
stk.append([i,temperatures[i]])
elif(len(stk) and stk[-1][1]>temperatures[i]):
l.append(1)
stk.append([i,temperatures[i]])
else:
while(len(stk)>0 and stk[-1][1]<=temperatures[i]):
stk.pop()
if(len(stk)<=0):
l.append(0)
stk.append([i,temperatures[i]])
else:
l.append(abs(i-stk[-1][0]))
stk.append([i,temperatures[i]])
return l[::-1] | daily-temperatures | Easy Python Solution with Stack | liontech_123 | 0 | 8 | daily temperatures | 739 | 0.666 | Medium | 12,087 |
https://leetcode.com/problems/daily-temperatures/discuss/2806120/739.-Daily-Temperatures-oror-Python3-oror-STACK | class Solution:
def dailyTemperatures(self, t: List[int]) -> List[int]:
stack=[]
ans=[0]*len(t)
res=[0]*len(t)
for i in range(len(t)-1,-1,-1):
curr=t[i]
while len(stack)!=0 and stack[-1][1]<=curr:
stack.pop()
#print(stack)
if len(stack)==0:
ans[i]=0
else:
ans[i]=stack[-1][0]
stack.append((i,curr))
#print(ans)
for i in range(len(ans)):
if ans[i]!=0:
res[i]=ans[i]-i
return res | daily-temperatures | 739. Daily Temperatures || Python3 || STACK | shagun_pandey | 0 | 5 | daily temperatures | 739 | 0.666 | Medium | 12,088 |
https://leetcode.com/problems/daily-temperatures/discuss/2723032/Python3-Simple-Stack-Solution | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
stack = []
res = [0] * len(temperatures)
for i, t in enumerate(temperatures):
while stack and t > stack[-1][0]:
_, idx = stack.pop()
res[idx] = i-idx
stack.append((t, i))
return res | daily-temperatures | Python3 Simple Stack Solution | jonathanbrophy47 | 0 | 16 | daily temperatures | 739 | 0.666 | Medium | 12,089 |
https://leetcode.com/problems/daily-temperatures/discuss/2715551/Python-Easy-to-Understand-oror-Logic-%2B-Code | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
'''
This is a classic example of monotonic stack
In this we will check if the temprature in the temp list is greater than the top of the stack , If yes then we will pop the temp and index from the stack and insert the difference between their indices into the output at the index of the popped temperature
If not then we will append the temp and index to the stack
'''
output = [0] * len(temperatures)
stack = [] #[temp,index]
for i,t in enumerate(temperatures):
while stack and t>stack[-1][0]:
stackT,stackIndex = stack.pop()
output[stackIndex] = i - stackIndex
stack.append([t,i])
return output | daily-temperatures | [Python] Easy to Understand || Logic + Code | Ron99 | 0 | 30 | daily temperatures | 739 | 0.666 | Medium | 12,090 |
https://leetcode.com/problems/daily-temperatures/discuss/2672188/Stack-oror-next-greater-element-oror-SC-and-TC-O(N) | class Solution:
def dailyTemperatures(self, arr: List[int]) -> List[int]:
stck = []
ans = []
for i in range(len(arr)-1, -1, -1):
counter = 0
while stck and stck[-1][0] <= arr[i]:
counter += stck[-1][1] + 1
stck.pop(-1)
if stck == []: ans.append(0)
else: ans.append(counter + 1)
stck.append([arr[i], counter])
ans.reverse()
return ans | daily-temperatures | Stack || next greater element || SC & TC - O(N) | mihirshah0114 | 0 | 6 | daily temperatures | 739 | 0.666 | Medium | 12,091 |
https://leetcode.com/problems/daily-temperatures/discuss/2660317/Daily-Temperatures-using-python | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
stack_temp = [(temperatures[-1], len(temperatures)-1)]
output = [0 for i in range(len(temperatures))]
for i in range(len(temperatures)-2, -1, -1):
while stack_temp and temperatures[i] >= stack_temp[-1][0]:
stack_temp.pop()
if stack_temp == []:
output[i] = 0
stack_temp.append((temperatures[i], i))
else:
output[i] = stack_temp[-1][1] - i
stack_temp.append((temperatures[i], i))
return output | daily-temperatures | Daily Temperatures- using python | D_Trivedi0607 | 0 | 7 | daily temperatures | 739 | 0.666 | Medium | 12,092 |
https://leetcode.com/problems/daily-temperatures/discuss/2649466/Clean-Monostack-solution-O(n) | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
mono_stack = []
if len(temperatures) == 1:
return [0]
res = [0]*len(temperatures)
for i,t in enumerate(temperatures):
while len(mono_stack)>0 and t>temperatures[mono_stack[-1]]:
popped_ind = mono_stack.pop()
res[popped_ind] = i-popped_ind
mono_stack.append(i)
return res | daily-temperatures | Clean Monostack solution, O(n) | Arana | 0 | 93 | daily temperatures | 739 | 0.666 | Medium | 12,093 |
https://leetcode.com/problems/daily-temperatures/discuss/2631619/Python-Solution-or-Monotonic-Stack | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
n=len(temperatures)
ans=[0]*n
stack=[]
for i in range(n-1, -1, -1):
while stack and stack[-1][0]<=temperatures[i]:
stack.pop()
if stack:
ans[i]=stack[-1][1]-i
else:
ans[i]=0
stack.append([temperatures[i], i])
return ans | daily-temperatures | Python Solution | Monotonic Stack | Siddharth_singh | 0 | 33 | daily temperatures | 739 | 0.666 | Medium | 12,094 |
https://leetcode.com/problems/daily-temperatures/discuss/2598856/Python-Solution-Stack | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
# add value to the stack when temp <= prev
# when temp > prev, keep popping from stack until temp <= prev, while updating values in the result array
res = [0] * len(temperatures)
stack = []
for i,temp in enumerate(temperatures):
while stack and temp > stack[-1][0]:
t,prevInd = stack.pop()
res[prevInd] = i - prevInd
stack.append([temp,i])
return res | daily-temperatures | Python Solution Stack | al5861 | 0 | 100 | daily temperatures | 739 | 0.666 | Medium | 12,095 |
https://leetcode.com/problems/daily-temperatures/discuss/2535658/Python3-or-Optimal-Time-Solution-using-Monotonic-Stack | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
# Monotonic Stack T.C: O(n)
stack = deque()
answer = [0] * len(temperatures)
for i,t in enumerate(temperatures):
while stack and t > stack[-1][0]:
temp, index = stack.pop()
answer[index] = i-index
stack.append((t,i))
return answer
# Search with tag chawlashivansh for my solutions. | daily-temperatures | Python3 | Optimal Time Solution using Monotonic Stack | chawlashivansh | 0 | 177 | daily temperatures | 739 | 0.666 | Medium | 12,096 |
https://leetcode.com/problems/daily-temperatures/discuss/2398648/Python3-solution-O(N)-time-complexity-O(N)-space-complexity-65-faster | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
stack = []
answer = [0] * len(temperatures)
#loops trough the input list, pair of index-temperature is used
for index, currTemp in enumerate(temperatures):
#until stack is empty or current temperature is lower than peeked temperature
while stack and currTemp > stack[-1][1]:
peekedTemp = stack.pop()
#insert in correct position the difference in indexes
answer[peekedTemp[0]] = (index - peekedTemp[0])
#push into the stack the current pair
stack.append([index, currTemp])
return answer | daily-temperatures | Python3 solution, O(N) time complexity, O(N) space complexity, 65% faster | matteogianferrari | 0 | 81 | daily temperatures | 739 | 0.666 | Medium | 12,097 |
https://leetcode.com/problems/daily-temperatures/discuss/2195397/Python-or-Stack-Solution-or-TC-O(n)-SC-O(n)-or-Easy-Solution | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
stack = list()
top = -1
res = [0]*len(temperatures)
#Base Case: For top == -1, pushing 1st elemnt to the stack
stack.append(0)
top += 1
for i in range(1,len(temperatures)):
if temperatures[i] <= temperatures[stack[top]]:
stack.append(i)
top += 1
else:
while top != -1 and temperatures[i] > temperatures[stack[top]]:
res[stack[top]] = i - stack[top]
stack.pop()
top -= 1
stack.append(i)
top += 1
return res | daily-temperatures | Python | Stack Solution | TC- O(n) SC- O(n) | Easy Solution | aadyant2019 | 0 | 116 | daily temperatures | 739 | 0.666 | Medium | 12,098 |
https://leetcode.com/problems/daily-temperatures/discuss/2184875/Simple-Beginner-Python-Stack-Solution | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
stack, output = [], [0] * len(temperatures)
t = enumerate(temperatures)
for i, temp in t:
if not stack:
stack.append((i,temp))
continue
while stack and stack[-1][1] < temp:
day = stack.pop()[0]
delta = i - day
output[day] = delta
stack.append((i,temp))
return output | daily-temperatures | Simple Beginner Python Stack Solution | 7yler | 0 | 72 | daily temperatures | 739 | 0.666 | Medium | 12,099 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.