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/where-will-the-ball-fall/discuss/2813254/Simple-and-Easy-to-Understand-Solution | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
ans = []
for drop_column in range(0, len(grid[0])):
x = 0
y = drop_column
is_stuck = self.isStuck(grid, x, y, grid[x][y])
while not is_stuck:
# Calculate next cordinates (x, y) to check if ball will stuck at this coordinates
y = y + 1 if grid[x][y] == 1 else y - 1
x = x + 1
# Ball falling out of grid
if x >= len(grid):
break
is_stuck = self.isStuck(grid, x, y, grid[x][y])
if is_stuck:
ans.append(-1)
else:
ans.append(y)
return ans
def isStuck(self, grid, i, j, slope):
m = len(grid)
n = len(grid[0])
if slope == 1:
# Cell next to wall
if j + 1 >= n:
return True
# V shape formed
if grid[i][j + 1] == -1:
return True
else:
# Cell next to wall
if j - 1 < 0:
return True
# V shape formed
if grid[i][j - 1] == 1:
return True
return False | where-will-the-ball-fall | Simple and Easy to Understand Solution | fire_icicle | 0 | 2 | where will the ball fall | 1,706 | 0.716 | Medium | 24,700 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2802832/Easy-Solution | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
lens = len(grid[0])
result = []
column, row = 0, 0
for i in range(0, lens):
column, row, skip = 0, 0, 0
column = i
for j in range(0, len(grid)):
pos = grid[row + j][column]
column = column + pos
if column == -1 or column == lens:
result.append(-1)
skip = 1
break
if pos + grid[row+j][column] == 0:
result.append(-1)
skip = 1
break
if skip == 0:
result.append(column)
return result | where-will-the-ball-fall | Easy Solution | Maclenak | 0 | 2 | where will the ball fall | 1,706 | 0.716 | Medium | 24,701 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2788166/Python-Solution-using-iterative-approach | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
n=len(grid)
a = len(grid[0])
ball = [i for i in range(0,a)]
# print("One",ball)
for i in range(n):
# print(newball,end="\n")
newball = [-1 for x in range(a)]
for j in range(a):
if ball[j]!=-1:
if grid[i][j]==1:
if j==a-1:
# newball[j]=-1
continue
elif grid[i][j+1]==1:
newball[j+1]=ball[j]
# print("new",i, j, newball)
elif grid[i][j+1]==-1:
ball[j]=-1
pass
elif grid[i][j]==-1:
if j==0:
continue
elif grid[i][j-1]==-1:
newball[j-1]=ball[j]
elif grid[i][j-1]==1:
ball[j]=-1
# print("ball",ball)
ball = newball
# print("newball",newball)
# print("Ans",ball)
y = [-1 for i in range(a)]
for i in range(a):
if ball[i]==-1:
continue
else:
y[ball[i]]=i
return y | where-will-the-ball-fall | Python Solution using iterative approach | muskanmaheshwari | 0 | 2 | where will the ball fall | 1,706 | 0.716 | Medium | 24,702 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2786241/Python-clean-self-explanatory-code-or-easy-solution | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
answer = []
rows, cols = len(grid), len(grid[0])
def stuck(row,col):
if grid[row][col] == 1 and ((col + 1) >= cols or grid[row][col + 1] == -1):
return True
elif grid[row][col] == -1 and ((col - 1) < 0 or grid[row][col - 1] == 1):
return True
return False
def canReach(row,col):
if row >= rows:
return col
if stuck(row,col):
return -1
if grid[row][col] == 1:
return canReach(row + 1, col + 1)
else:
return canReach(row + 1, col - 1)
for col in range(cols):
answer.append(canReach(0,col))
return answer | where-will-the-ball-fall | Python clean self explanatory code | easy solution | natnael_tadele | 0 | 7 | where will the ball fall | 1,706 | 0.716 | Medium | 24,703 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2777722/Simple-DFS-Solution-in-Python | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
n = len(grid)
i = 0
j = 0
def dfs(i, j):
if i == n:
return j
if grid[i][j] == -1 and j == 0:
return -1
if grid[i][j] == 1 and j == len(grid[0])-1:
return -1
if grid[i][j] == 1 and grid[i][j+1] == -1:
return -1
if grid[i][j] == -1 and grid[i][j-1] == 1:
return -1
if grid[i][j] == 1 and grid[i][j+1] == 1:
return dfs(i+1, j+1)
if grid[i][j] == -1 and grid[i][j-1] == -1:
return dfs(i+1, j-1)
ans = []
for aa in range(len(grid[0])):
print(aa)
ans.append(dfs(0, aa))
return ans | where-will-the-ball-fall | Simple DFS Solution in Python | Tushar-8799 | 0 | 1 | where will the ball fall | 1,706 | 0.716 | Medium | 24,704 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2772568/Python-Easy-Solution | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
rows,cols=len(grid),len(grid[0])
ans=[]
for i in range(cols):
c=i
r=0
stuck=False
while(stuck==False):
if r==rows:
ans.append(c)
break
elif grid[r][c]==1 and c!=cols-1 and grid[r][c]==grid[r][c + 1]:
r=r+1
c=c+1
elif grid[r][c]==-1 and c!=0 and grid[r][c]==grid[r][c - 1]:
r=r+1
c=c-1
else:
ans.append(-1)
stuck=True
return ans | where-will-the-ball-fall | Python Easy Solution | akashchaudhare12 | 0 | 5 | where will the ball fall | 1,706 | 0.716 | Medium | 24,705 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2769513/easy-code | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
m, n = len(grid), len(grid[0])
ans = []
for j in range(n):
col = j
for i in range(m):
if not (0 <= col + grid[i][col] < n and grid[i][col] == grid[i][col + grid[i][col]]):
col = -1
break
col += grid[i][col]
ans.append(col)
return ans | where-will-the-ball-fall | easy code | sanjeevpathak | 0 | 3 | where will the ball fall | 1,706 | 0.716 | Medium | 24,706 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2768530/Recursive-Solution-w-Python3 | class Solution:
def findWay(self, grid, column):
row = 0
while True:
# print("[",row,",",column,"]")
curr = grid[row][column]
try:
if ((column+curr < 0) or (grid[row][column+curr] != curr)):
return -1
else:
row += 1
column += curr
if ((row > len(grid) - 1) and (column >= 0)):
return column
elif ((row > len(grid) - 1) and (column < 0)):
return -1
except:
return -1
return -1
def findBall(self, grid: List[List[int]]) -> List[int]:
result = []
if (((len(grid) == 1) and (len(grid[0]) == 1)) or (len(grid[0]) == 1)):
return [-1]
elif (len(grid) == 1):
for i in range(len(grid[0])):
if (grid[0][i+grid[0][i]] == grid[0][i]):
result.append(i + grid[0][i])
else:
result.append(-1)
else:
for i in range(len(grid[0])):
result.append(self.findWay(grid, i))
return result | where-will-the-ball-fall | Recursive Solution w/ Python3 | berkcohadar | 0 | 6 | where will the ball fall | 1,706 | 0.716 | Medium | 24,707 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2768498/Python!-As-short-as-it-gets! | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
n, m = len(grid), len(grid[0])
def bt(y:int) -> int:
for x in range(n):
cval = grid[x][y]
ny = y + cval
if not (0 <= ny <m) or cval != grid[x][ny]:
return -1
y = ny
return y
return [bt(i) for i in range(m)] | where-will-the-ball-fall | 😎Python! As short as it gets! | aminjun | 0 | 5 | where will the ball fall | 1,706 | 0.716 | Medium | 24,708 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2768489/Python-Solution-(enumerate-O(nxm))-oror-T99.46-of-Python3-(188-ms) | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
n = len(grid[0])
result = [i for i in range(n)]
result_cache = result.copy()
for row in grid:
for index, position_ball in enumerate(result):
if position_ball != -1:
next_position = position_ball + row[position_ball]
if next_position < 0 or next_position >= n or row[next_position] != row[position_ball]:
result_cache[index] = -1
continue
result_cache[index] = next_position
result = result_cache.copy()
return result | where-will-the-ball-fall | Python Solution (enumerate, O(nxm)) || T99.46% of Python3 (188 ms) | MarcosReyes | 0 | 6 | where will the ball fall | 1,706 | 0.716 | Medium | 24,709 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2768253/Simple-solution-on-Python3 | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
rez = [] #it will be our list with result
for col in range(len(grid[0])): # first iteration will be by columns
row = 0
ball = col
start = grid[row][ball] #our start position for each ball
while row < len(grid): # second iteration by rows
start = grid[row][ball] # will change start position on each step
if start == -1 and ball == 0: # condition for left side
rez.append(-1) # write to the list with results -1
break #stop this step and go to the next ball
elif start == 1 and ball == len(grid[0])-1: # condition for right side
rez.append(-1)
break
elif (start == 1 and grid[row][ball + 1] == -1) or (start == -1 and grid[row][ball - 1] == 1): #condition for all other position in the grid where the ball will stop
rez.append(-1)
break
elif start == 1: #condition for all other position in the grid where mean is 1
row += 1
ball += 1
else: #condition for all other position in the grid mean is -1
row += 1
ball -= 1
if row == len(grid): rez.append(ball) #when we will reach the lower limit we write number of column to the list with results
return rez | where-will-the-ball-fall | Simple solution on Python3 | VorobeyPudic | 0 | 5 | where will the ball fall | 1,706 | 0.716 | Medium | 24,710 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2768032/Py-Easy-Soln-wd-Best-Approch | class Solution:
def dfs(self,i,j,grid):
if i>=len(grid):
return j
if grid[i][j]==1 and j+1<len(grid[0]) and grid[i][j+1]==1 :
return self.dfs(i+1,j+1,grid)
elif grid[i][j]==-1 and j-1>=0 and grid[i][j-1]==-1:
return self.dfs(i+1,j-1,grid)
elif grid[i][j]==1 and j+1>=len(grid[0]):
return -1
else:
return -1
def findBall(self, grid: List[List[int]]) -> List[int]:
m=len(grid)
n=len(grid[0])
ans=[]
for i in range(n):
ans.append(self.dfs(0,i,grid))
return ans | where-will-the-ball-fall | Py Easy Soln wd Best Approch 💯✅✅ | adarshg04 | 0 | 16 | where will the ball fall | 1,706 | 0.716 | Medium | 24,711 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2768006/Python-Iterative-Solution | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
ROW,COL = len(grid),len(grid[0])
def helper(r,c,pc):
i = 0
if r == ROW:
return c
while i < ROW:
if grid[i][c] == 1 and c+1 < COL and grid[i][c+1] == 1:
i+=1
c+=1
elif grid[i][c] == -1 and c-1 >= 0 and grid[i][c-1] == -1:
i+=1
c-=1
else:
return -1
return c
ans = []
for j in range(COL):
ans.append(helper(0,j,j))
return ans | where-will-the-ball-fall | Python Iterative Solution | DigantaC | 0 | 7 | where will the ball fall | 1,706 | 0.716 | Medium | 24,712 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2767858/Python-easy-to-understand-approach | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
row,col = len(grid), len(grid[0])
ans=[]
for c in range(col):
cur_col = c
for r in range(row):
next_col = cur_col + grid[r][cur_col]
if next_col<0 or next_col>=col or grid[r][cur_col]!=grid[r][next_col]:
cur_col=-1
break
cur_col=next_col
ans.append(cur_col)
return ans | where-will-the-ball-fall | Python easy to understand approach | kartikchoudhary96 | 0 | 5 | where will the ball fall | 1,706 | 0.716 | Medium | 24,713 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2767804/Simple-Python-Solution. | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
m = len(grid)
n = len(grid[0])
ans = []
for j in range(n):
i = 0
while(True):
if grid[i][j] == 1:
if j == n-1:
ans.append(-1)
break
if grid[i][j+1] == -1:
ans.append(-1)
break
if i == m-1:
ans.append(j+1)
break
else:
i += 1
j += 1
if grid[i][j] == -1:
if j == 0:
ans.append(-1)
break
if grid[i][j-1] == 1:
ans.append(-1)
break
if i==m-1:
ans.append(j-1)
break
else:
i += 1
j -= 1
return ans | where-will-the-ball-fall | Simple Python Solution. | imkprakash | 0 | 7 | where will the ball fall | 1,706 | 0.716 | Medium | 24,714 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2767690/Python3-or-Iterative | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
ROW, COL = len(grid), len(grid[0])
result = [index for index in range(COL)]
for row in range(ROW):
for col in range(COL):
if result[col] != -1:
if result[col] < COL and grid[row][result[col]] == 1 and result[col] + 1 < COL and grid[row][result[col] + 1] == 1:
result[col] = result[col] + 1
elif result[col] < COL and grid[row][result[col]] == -1 and result[col] - 1 >= 0 and grid[row][result[col] - 1] == -1:
result[col] = result[col] - 1
else:
result[col] = -1
return result | where-will-the-ball-fall | Python3 | Iterative | Dhanush_krish | 0 | 2 | where will the ball fall | 1,706 | 0.716 | Medium | 24,715 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2767582/Python3-Readable-with-comments | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
m = len(grid)
n = len(grid[0])
def step(row, col):
# Reached bottom, return current column
if row == m:
return col
# Reached a "Right"
if grid[row][col] == 1:
# Recurse one row lower, and one column right
if col != n-1 and grid[row][col+1] == 1:
return step(row+1, col+1)
# If grid to the right is out of bounds, or a left - we are stuck
else:
return -1
# Reached a "Left"
if grid[row][col] == -1:
# Recurse one row lower, and one column left
if col != 0 and grid[row][col-1] == -1:
return step(row+1, col-1)
# If grid to the left is out of bounds, or a right - we are stuck
else:
return -1
# Run the recursive function on each column, and return the result
output = []
for i in range(n):
output.append(step(0,i))
return output | where-will-the-ball-fall | [Python3] Readable with comments | connorthecrowe | 0 | 8 | where will the ball fall | 1,706 | 0.716 | Medium | 24,716 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2767428/Python-Easiest-Human-Readable-Solution | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
R, C = len(grid), len(grid[0])
ans = [None] * C
def isWall(c):
return c < 0 or c >= C
def hasDropped(r):
return r >= R
def isStuck(r, c):
if isWall(c + grid[r][c]) or grid[r][c + grid[r][c]] == -grid[r][c]:
return True
return False
for i in range(C):
r, c = 0, i
while 0 <= c < C and r < R:
if isStuck(r, c):
ans[i] = -1
break
r, c = r+1, c+1 if grid[r][c] == 1 else c-1
if isWall(c):
ans[i] = -1
continue
if hasDropped(r):
ans[i] = c
continue
return ans | where-will-the-ball-fall | [Python] Easiest Human-Readable Solution | Paranoidx | 0 | 10 | where will the ball fall | 1,706 | 0.716 | Medium | 24,717 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2767416/Easy-to-understand-Python3-solution | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
answer = [-1] * len(grid[0])
for col_idx in range(len(grid[0])):
r, c = 0, col_idx
# while ball hasn't reached bottom
while r < len(grid):
# within bounds
if c == 0 and grid[r][c] == -1:
break
if c == len(grid[0])-1 and grid[r][c] == 1:
break
# reaches V
if grid[r][c] == 1 and grid[r][c+1] == -1:
break
if grid[r][c] == -1 and grid[r][c-1] == 1:
break
# move left or right and down
c += grid[r][c]
r += 1
# didn't get stuck
if r == len(grid): answer[col_idx] = c
return answer | where-will-the-ball-fall | Easy to understand Python3 solution | rschevenin | 0 | 4 | where will the ball fall | 1,706 | 0.716 | Medium | 24,718 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2767235/python-easy-to-understand | class Solution(object):
def findBall(self, grid):
"""
:type grid: List[List[int]]
:rtype: List[int]
"""
n,m = len(grid), len(grid[0])
out = [-1 for i in range(m)]
for k in range(m): # for each starting col
que = [(0,k)] # build a que
while que:
(row,col) = que.pop()
if row==n: # reached last row --> return col
out[k] = col
else: # find the next cell
if grid[row][col] == 1 and col+1<m and grid[row][col+1] ==1: # if \O\
que.append((row+1,col+1))
elif grid[row][col] == -1 and col-1>=0 and grid[row][col-1] == -1: #if /o/
que.append((row+1,col-1))
return out
``` | where-will-the-ball-fall | python - easy to understand | jayr777 | 0 | 10 | where will the ball fall | 1,706 | 0.716 | Medium | 24,719 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2767221/Python-oror-Easy-Solution-oror-O(n*m) | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
n, m = len(grid), len(grid[0])
def is_valid(i, j):
return i < n and i >= 0 and j < m and j >= 0
def is_not_v(i, j):
if grid[i][j] == 1:
if is_valid(i, j+1):
return j+1 if grid[i][j] == grid[i][j+1] else None
return None
else:
if is_valid(i, j-1):
return j-1 if grid[i][j] == grid[i][j-1] else None
return None
ans = []
for j in range(m):
output = is_not_v(0, j)
i = 1
while i < n and output != None:
output = is_not_v(i, output)
i += 1
if i == n and output != None:
ans.append(output)
else:
ans.append(-1)
return ans | where-will-the-ball-fall | Python || Easy Solution || O(n*m) | Rahul_Kantwa | 0 | 4 | where will the ball fall | 1,706 | 0.716 | Medium | 24,720 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2767218/Simple-Python3-solution | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
m = len(grid)
n = len(grid[0])
answer = []
for i in range(0,n):
j = 0
c = i
while j < m:
if (grid[j][c] == 1):
if c+1 >= n:
answer.append(-1)
break
elif (grid[j][c+1] == -1):
answer.append(-1)
break
elif (grid[j][c] == -1):
if c-1 < 0:
answer.append(-1)
break
elif (grid[j][c-1] == 1):
answer.append(-1)
break
c += grid[j][c]
j += 1
else:
answer.append(c)
return answer | where-will-the-ball-fall | Simple Python3 solution | gbiagini | 0 | 6 | where will the ball fall | 1,706 | 0.716 | Medium | 24,721 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2767162/Where-Will-the-Ball-Fall-or-Pythonor-DFSor-Easy | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
def dfs(i,j, row, col, grid):
if i>=row:
return j
# Left -> Right
if (grid[i][j]==1 and j+1<col and grid[i][j+1]==1):
return dfs(i+1,j+1, row, col, grid)
# Right -> Left
elif (grid[i][j]==-1 and j-1>=0 and grid[i][j-1]==-1):
return dfs(i+1,j-1, row, col, grid)
else:
return -1
lst = []
row = len(grid)
col = len(grid[0])
for j in range(col):
lst.append(dfs(0,j, row, col, grid))
return lst | where-will-the-ball-fall | Where Will the Ball Fall | Python| DFS| Easy | ankan8145 | 0 | 4 | where will the ball fall | 1,706 | 0.716 | Medium | 24,722 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2766957/Descriptive-and-easy-to-follow-Python-solution | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
self.answer = [-1 for i in range(len(grid[0]))]
self.m = len(grid) # rows
self.n = len(grid[0]) # columns
def rf(row, column, ball):
if row == self.m:
self.answer[ball] = column
return
current = grid[row][column]
adjacent = None
if current == 1:
if column >= self.n - 1:
return
adjacent = grid[row][column+1]
elif current == -1:
if column <= 0:
return
adjacent = grid[row][column-1]
# \/ this pattern equals 0 = 1 + (-1)
# \\ this pattern equals 2 = 1 + 1
# // this pattern equals -2 = (-1) + (-1)
if current + adjacent == 0:
return
elif current + adjacent == 2:
rf(row+1, column+1, ball)
elif current + adjacent == -2:
rf(row+1, column-1, ball)
for i in range(len(grid[0])):
rf(0, i, i)
return self.answer | where-will-the-ball-fall | Descriptive and easy to follow Python solution | zebra-f | 0 | 4 | where will the ball fall | 1,706 | 0.716 | Medium | 24,723 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2766861/Python3-Solution-with-using-simulation | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
res = [i for i in range(len(grid[0]))]
for i in range(len(grid)):
for bol_idx in range(len(res)):
if res[bol_idx] == -1:
continue
next_col = res[bol_idx] + grid[i][res[bol_idx]]
if next_col == -1 or next_col == len(grid[i]):
res[bol_idx] = -1
continue
if grid[i][res[bol_idx]] + grid[i][next_col] == 0:
res[bol_idx] = -1
else:
res[bol_idx] = next_col
return res | where-will-the-ball-fall | [Python3] Solution with using simulation | maosipov11 | 0 | 5 | where will the ball fall | 1,706 | 0.716 | Medium | 24,724 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2766737/Simulate-a-path-for-each-ball | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
n = len(grid[0])
rez = [-1]*n
for b in range(n):
i, j = 0, b
while i < len(grid):
if not 0 <= j + grid[i][j] < n or not grid[i][j] == grid[i][j + grid[i][j]]:
j = -1
break
else:
j += grid[i][j]
i += 1
rez[b] = j
return rez | where-will-the-ball-fall | Simulate a path for each ball | nonchalant-enthusiast | 0 | 3 | where will the ball fall | 1,706 | 0.716 | Medium | 24,725 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2766736/Python-faster-solution | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
m,n = len(grid),len(grid[0])
def check(row,col):
### If a ball get out of the box, return col
if row==m:
return col
### note that since grid contains 1 and -1 representing to right and to left,
### we can just add the grid[row][col] to current collumn to get the new column
new_col = col+grid[row][col]
### if the new column is already out of the box
### or the neighbor cell doesn't equal to grid[row][col]
### the ball will get stuck and we just return -1
if new_col==n or new_col==-1 or grid[row][new_col]!=grid[row][col]:
return -1
else:
return check(row+1,new_col)
res = []
for i in range(n):
res.append(check(0,i))
return res | where-will-the-ball-fall | Python faster solution | avs-abhishek123 | 0 | 6 | where will the ball fall | 1,706 | 0.716 | Medium | 24,726 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2766733/Python-Easy-to-understand-with-comments | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
res = []
for i in range(len(grid[0])):
res.append(self.dfs(grid,0,i,i))
return res
def dfs(self, grid, i, j, position):
#When we reach the bottom, return the position
if len(grid) <= i:
return position
#If we are still in bound
if 0 <= j + grid[i][j] < len(grid[0]):
#Check for opposing direction neighbor
if grid[i][j] < 0 and grid[i][j] + grid[i][j-1] == 0:
return -1
if grid[i][j] > 0 and grid[i][j] + grid[i][j+1] == 0:
return -1
#If we hit the wall, return -1
else:
return -1
return self.dfs(grid, i + 1, j + grid[i][j], position + grid[i][j]) | where-will-the-ball-fall | Python, Easy to understand with comments | IamCookie | 0 | 5 | where will the ball fall | 1,706 | 0.716 | Medium | 24,727 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2766683/Python-3-Easy-to-Understand-or-Faster-Solution-or-O(n*n)-Complexity | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
m, n = len(grid), len(grid[0])
ans = [-1 for i in range(n)]
for i in range(n):
row = 0
col = i
while row < m and col < n and col >= 0:
if grid[row][col] == 1:
if col+1 < n and grid[row][col+1] == -1: break
row += 1
col += 1
else:
if col-1 >= 0 and grid[row][col-1] == 1: break
row += 1
col -= 1
else:
if col < n and col >= 0: ans[i] = col
return ans | where-will-the-ball-fall | [Python 3] Easy to Understand | Faster Solution | O(n*n) Complexity | Rajesh1809 | 0 | 2 | where will the ball fall | 1,706 | 0.716 | Medium | 24,728 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2766676/Intuitive-Python3-Solution-with-Commented-Code | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
nRows = len(grid)
nCols = len(grid[0])
reachedBottom = [-1]*nCols
for ball in range(nCols):
# initial location
loc = ball
# as ball falls
for depth in range(nRows):
# if redirected to the right
if grid[depth][loc] == 1:
# if hit container wall
if loc == nCols - 1:
break
# if stuck in corner
if grid[depth][loc + 1] == -1:
break
loc += 1 # makes it through
# if reached bottom
if depth == nRows - 1:
reachedBottom[ball] = loc
continue
# otherwise, redirected to the left
# if hit container wall
if loc == 0:
break
# if stuck in corner
if grid[depth][loc - 1] == 1:
break
loc -= 1 # makes it through
# if reached bottom
if depth == nRows - 1:
reachedBottom[ball] = loc
return reachedBottom | where-will-the-ball-fall | Intuitive Python3 Solution with Commented Code | gequalspisquared | 0 | 3 | where will the ball fall | 1,706 | 0.716 | Medium | 24,729 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2766674/Simplest-way-possible | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
m,n = len(grid),len(grid[0])
res = []
for col in range(n):
row = 0
while True:
if row == m:
res.append(col)
break
if col == 0 and grid[row][col] == -1:
res.append(-1)
break
if col == n-1 and grid[row][col] == 1:
res.append(-1)
break
if grid[row][col] == 1:
if grid[row][col+1] == -1:
res.append(-1)
break
else:
row += 1
col += 1
elif grid[row][col] == -1:
if grid[row][col-1] == 1:
res.append(-1)
break
else:
row += 1
col -= 1
return res | where-will-the-ball-fall | Simplest way possible | shriyansnaik | 0 | 3 | where will the ball fall | 1,706 | 0.716 | Medium | 24,730 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2766639/python3-easy-way | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
m,n = len(grid),len(grid[0])
def check(row,col):
### If a ball get out of the box, return col
if row==m:
return col
### note that since grid contains 1 and -1 representing to right and to left,
### we can just add the grid[row][col] to current collumn to get the new column
new_col = col+grid[row][col]
### if the new column is already out of the box
### or the neighbor cell doesn't equal to grid[row][col]
### the ball will get stuck and we just return -1
if new_col==n or new_col==-1 or grid[row][new_col]!=grid[row][col]:
return -1
else:
return check(row+1,new_col)
res = []
for i in range(n):
res.append(check(0,i))
return res | where-will-the-ball-fall | python3 easy way | rupamkarmakarcr7 | 0 | 4 | where will the ball fall | 1,706 | 0.716 | Medium | 24,731 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2766583/Easy-Understanding-code | class Solution:
# Explanation for future:
# You maintain a res array for the positions of the balls
# Whenever the position of ball reaches out of bounds or the ball's next locaiton is just opposite to the
# ball's current location you assign that ball a position of -1 indicating this ball is no longer in use
# But how do you find the next location of the ball?
# You find out the current location of the ball as curr = res[j] where j is in the range of number of columns in grid
# and you you check where this ball is headed using grid[i][curr]
# now you add the current location with the headed direction to get the next location
# Now you can use the conditions explained above and after all the iterations the ball which has survived will be in res
# rest will have locaiton as -1
def findBall(self, grid: List[List[int]]) -> List[int]:
m, n = len(grid), len(grid[0])
res = list(range(n))
for i in range(m):
for j in range(n):
curr = res[j]
if curr == -1: continue
curr_next = curr + grid[i][curr]
if (not (0 <= curr_next < n)) or (grid[i][curr_next] == -grid[i][curr]):
res[j] = -1
else:
res[j] = curr_next
return res | where-will-the-ball-fall | Easy Understanding code | shiv-codes | 0 | 7 | where will the ball fall | 1,706 | 0.716 | Medium | 24,732 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2766432/Easy-to-understand-python3-and-java-iterative-solution | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
ans = []
n, m = len(grid), len(grid[0])
for j in range(m):
curr_col = j
can_place = True
for i in range(n):
if grid[i][curr_col] == 1:
if curr_col + 1 == m or grid[i][curr_col + 1] == -1:
can_place = False
break
curr_col += 1
else:
if curr_col - 1 < 0 or grid[i][curr_col - 1] == 1:
can_place = False
break
curr_col -= 1
if can_place:
ans.append(curr_col)
else:
ans.append(-1)
return ans | where-will-the-ball-fall | Easy to understand python3 and java iterative solution | Yoxbox | 0 | 5 | where will the ball fall | 1,706 | 0.716 | Medium | 24,733 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2766420/Python-or-With-Explanation-or-DFS-or-Faster-than-98.57 | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
m, n = len(grid), len(grid[0])
def dfs(x, y):
# if current index turns ball rightwards
if grid[x][y] == 1:
if y == n - 1: # if it is at the last column, ball will get stuck
return -1
if grid[x][y + 1] == -1: # if next column is leftwards, ball will get stuck
return -1
return y + 1 if x == m - 1 else dfs(x + 1, y + 1) # ball will continue or exit from right
# if current index turns ball leftwards
else:
if y == 0: # if it is at first column, ball will get stuck
return -1
if grid[x][y - 1] == 1: # if previous column is rightwards, ball will get stuck
return -1
return y - 1 if x == m - 1 else dfs(x + 1, y - 1) # ball will continue or exit from left
return [dfs(0, x) for x in range(n)] | where-will-the-ball-fall | Python | With Explanation | DFS | Faster than 98.57% | ayamdobhal | 0 | 8 | where will the ball fall | 1,706 | 0.716 | Medium | 24,734 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2766360/Python-O(n2)-solution-Accepted | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
ans: List[int] = [0] * len(grid[0])
for col in range(len(grid[0])):
stuck: int = 0
ball: int = col
for row in range(len(grid)):
if grid[row][ball] == 1 and ball < len(grid[0]) - 1 and grid[row][ball + 1] == 1:
ball += 1
elif grid[row][ball] == -1 and ball > 0 and grid[row][ball - 1] == -1:
ball -= 1
else:
stuck = 1
if stuck:
ans[col] = -1
else:
ans[col] = ball
return ans | where-will-the-ball-fall | Python O(n^2) solution [Accepted] | lllchak | 0 | 2 | where will the ball fall | 1,706 | 0.716 | Medium | 24,735 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2766307/Simple-exlpanation-with-memorization-and | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
count = 0
d = []
dict1 = {}
for i in range(len(grid[0])):
j = i
down = 0
case =True
while down < len(grid):
if dict1.get(str(down)+"_"+str(j)):
case = False
break
if (grid[down][j]==1 and j +1 >=len(grid[0])) or (grid[down][j]==-1 and j -1 <0) or (grid[down][j]==1 and grid[down ][j+1]==-1) or(grid[down][j]==-1 and grid[down][j -1]==1) :
case = False
dict1[str(down)+"_"+str(j)] = 1
break
if grid[down][j]==-1:
j = j - 1
else:
j = j+ 1
down = down + 1
if case :
count = 1
d.append(j)
else:
d.append(-1)
return d | where-will-the-ball-fall | Simple exlpanation with memorization and | darkgod | 0 | 2 | where will the ball fall | 1,706 | 0.716 | Medium | 24,736 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2766270/Python3-very-simple-approach-beats-87.6-runtime-and-98.48-memory | class Solution:
def new_position(self, position, grid):
x, y = position
board = grid[y][x]
if board == -1 and x == 0: return (x, y)
if board == 1 and x == len(grid[0]) - 1: return (x, y)
if (board == -1 and grid[y][x - 1] == 1) or (board == 1 and grid[y][x + 1] == -1):
return (x, y)
return (x + board, y + 1)
def findBall(self, grid):
@cache
def solve_ball(x):
current_position = (x, 0)
h = len(grid)
while current_position[1] < h:
new_pos = self.new_position(current_position, grid)
if new_pos == current_position: return -1
current_position = new_pos
return current_position[0]
return [solve_ball(x) for x in range(len(grid[0]))] | where-will-the-ball-fall | Python3, very simple approach, beats 87.6% runtime and 98.48% memory | JanFidor | 0 | 2 | where will the ball fall | 1,706 | 0.716 | Medium | 24,737 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2766240/Recursive-Simulation-O(mn)-easy-to-understand | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
result = []
m = len(grid)
n = len(grid[0])
def dfs(row, col) -> int:
if row == m:
return col # base case
if col + 1 < n and grid[row][col] == 1 and grid[row][col + 1] == 1: # can move to the right ?
return dfs(row + 1, col + 1)
if col - 1 >= 0 and grid[row][col] == -1 and grid[row][col - 1] == -1: # can move to the left?
return dfs(row + 1, col - 1)
return -1
for i in range(n):
b = dfs(0, i)
result.append(b)
return result | where-will-the-ball-fall | Recursive Simulation O(mn) - easy to understand | rrdlpl | 0 | 3 | where will the ball fall | 1,706 | 0.716 | Medium | 24,738 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2766235/Simple-python-solution | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
n = len(grid)
m = len(grid[0])
self.res = []
def drop(i, j):
if i >= n or j >= m:
return - 1
# check if right is the same
if grid[i][j] == 1:
if j + 1 < m:
if grid[i][j + 1] == 1:
if i == n - 1:
self.res.append(j + 1)
return
else:
drop(i + 1, j + 1)
else:
self.res.append(-1)
return
else:
self.res.append(-1)
return
# check left
else:
if j - 1 >= 0:
if grid[i][j -1] == -1:
if i == n - 1:
self.res.append(j - 1)
return
else:
drop(i + 1, j - 1)
else:
self.res.append(-1)
return
else:
self.res.append(-1)
return
for i in range(m):
drop(0, i)
return self.res | where-will-the-ball-fall | Simple python solution | aramkoorn | 0 | 3 | where will the ball fall | 1,706 | 0.716 | Medium | 24,739 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2766174/Python-solution-beats-95.53-users-with-explanation | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
m,n = len(grid),len(grid[0])
def check(row,col):
### If a ball get out of the box, return col
if row==m:
return col
### note that since grid contains 1 and -1 representing to right and to left,
### we can just add the grid[row][col] to current collumn to get the new column
new_col = col+grid[row][col]
### if the new column is already out of the box
### or the neighbor cell doesn't equal to grid[row][col]
### the ball will get stuck and we just return -1
if new_col==n or new_col==-1 or grid[row][new_col]!=grid[row][col]:
return -1
else:
return check(row+1,new_col)
res = []
for i in range(n):
res.append(check(0,i))
return res | where-will-the-ball-fall | Python solution beats 95.53% users with explanation | mritunjayyy | 0 | 4 | where will the ball fall | 1,706 | 0.716 | Medium | 24,740 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2765977/Recursive-solution-or-Easy-to-understand-or-Python-or-DFS | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
n=len(grid[0])
m=len(grid)
def dfs(i,j):
if i>=m:
return j
if grid[i][j]==1 and (j+1)<n and grid[i][j+1]==1:
return dfs(i+1,j+1)
elif grid[i][j]==-1 and j>0 and grid[i][j-1]==-1:
return dfs(i+1,j-1)
return -1
ans=[]
for i in range(n):
ans.append(dfs(0,i))
return ans | where-will-the-ball-fall | Recursive solution | Easy to understand | Python | DFS | ankush_A2U8C | 0 | 7 | where will the ball fall | 1,706 | 0.716 | Medium | 24,741 |
https://leetcode.com/problems/where-will-the-ball-fall/discuss/2765946/DFS-Fast-and-Easy-Solution | class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
def DFS(rows, columns, cur_row, cur_column):
//Base Case
if cur_row == rows:
return cur_column
//If direction is Right
if cur_column < columns - 1 and (grid[cur_row][cur_column] == 1 and grid[cur_row][cur_column + 1] == 1):
return DFS(rows, columns, cur_row + 1, cur_column + 1)
//If direction if Left
elif 0 < cur_column and (grid[cur_row][cur_column] == -1 and grid[cur_row][cur_column - 1] == -1):
return DFS(rows, columns, cur_row + 1, cur_column - 1)
//If direction is invalid
else:
return "X"
rows = len(grid)
columns = len(grid[0])
res = deque([])
for i in range(columns):
temp = DFS(rows, columns, 0, i)
res.append(-1) if temp == "X" else res.append(temp)
return res | where-will-the-ball-fall | DFS - Fast and Easy Solution | user6770yv | 0 | 5 | where will the ball fall | 1,706 | 0.716 | Medium | 24,742 |
https://leetcode.com/problems/maximum-xor-with-an-element-from-array/discuss/988468/Python3-trie | class Solution:
def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:
nums.sort()
queries = sorted((m, x, i) for i, (x, m) in enumerate(queries))
ans = [-1]*len(queries)
trie = {}
k = 0
for m, x, i in queries:
while k < len(nums) and nums[k] <= m:
node = trie
val = bin(nums[k])[2:].zfill(32)
for c in val: node = node.setdefault(int(c), {})
node["#"] = nums[k]
k += 1
if trie:
node = trie
val = bin(x)[2:].zfill(32)
for c in val: node = node.get(1-int(c)) or node.get(int(c))
ans[i] = x ^ node["#"]
return ans | maximum-xor-with-an-element-from-array | [Python3] trie | ye15 | 17 | 773 | maximum xor with an element from array | 1,707 | 0.442 | Hard | 24,743 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/999230/Python-Simple-solution | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key=lambda x:x[1],reverse=1)
s=0
for i,j in boxTypes:
i=min(i,truckSize)
s+=i*j
truckSize-=i
if truckSize==0:
break
return s | maximum-units-on-a-truck | [Python] Simple solution | lokeshsenthilkumar | 30 | 4,500 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,744 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/1594586/Python(Simple-Solution)-or-Faster-%3A-96.89-or-Time-%3A-O(nlogn) | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes = sorted(boxTypes, key = lambda x : x[1], reverse = True)
output = 0
for no, units in boxTypes:
if truckSize > no:
truckSize -= no
output += (no * units)
else:
output += (truckSize * units)
break
return output | maximum-units-on-a-truck | Python(Simple Solution) | Faster : 96.89 | Time : O(nlogn) | Call-Me-AJ | 7 | 554 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,745 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/1231724/Python3-97-Faster-Solution | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key=lambda x: x[1] , reverse=True)
count = 0
k = 0
for i , j in boxTypes:
if(truckSize < i):
break
count += i * j
truckSize -= i
k += 1
try:
return count + (truckSize * boxTypes[k][1])
except:
return count | maximum-units-on-a-truck | [Python3] 97% Faster Solution | VoidCupboard | 4 | 388 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,746 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2220967/Python-oror-Greedy-oror-Explanation | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
ans=0
i=0 #To traverse array
#Sort according to decreasing values of numberOfBoxes
boxTypes.sort(key=lambda x:(-x[1]))
n=len(boxTypes)
while(truckSize!=0 and i<n):
print(truckSize)
if truckSize > boxTypes[i][0]:
ans += boxTypes[i][0]*boxTypes[i][1]
truckSize -= boxTypes[i][0]
i+=1
elif truckSize <= boxTypes[i][0]:
ans += truckSize*boxTypes[i][1]
return ans
return ans | maximum-units-on-a-truck | Python || Greedy || Explanation | palashbajpai214 | 2 | 38 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,747 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/1300759/Easy-Python-Solution(95.99) | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
c=0
s=0
boxTypes=sorted(boxTypes, key=lambda x : -x[1])
i=0
while truckSize>0 and i<len(boxTypes):
truckSize-=boxTypes[i][0]
if(truckSize>=0):
s+=boxTypes[i][0]*boxTypes[i][1]
else:
c=0-truckSize
s+=(boxTypes[i][0]-c)*boxTypes[i][1]
i+=1
return s | maximum-units-on-a-truck | Easy Python Solution(95.99%) | Sneh17029 | 2 | 807 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,748 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/1045278/Easy-python-solution-using-sorting | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key=lambda x:x[1]) #sort boxtypes based on the number of units per box
result = 0
while truckSize>0:
# check if there are any boxes to load
if len(boxTypes)>0:
num_boxes, units_per_box = boxTypes.pop()
# check if the truck has the capacity to load all the boxes of type i, if yes, then load the boxes
if num_boxes<=truckSize:
result += (num_boxes * units_per_box)
truckSize -= num_boxes
# if the truck doesn't have enough capacity to load all the boxes of type i, then load only the number of boxes the truck can accommodate.
else:
result += (truckSize * units_per_box)
truckSize -= truckSize
# if all the boxes have been loaded and yet there is empty space in the truck, then break the loop.
else:
break
return result | maximum-units-on-a-truck | Easy python solution using sorting | darshan_22 | 2 | 258 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,749 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2653375/trash-solution-hoping-for-coaching | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes = sorted(boxTypes, key = lambda x:x[1],reverse = True)
sum = 0
i = 0
while truckSize:
if i >= len(boxTypes):
break
sum = sum + boxTypes[i][1]
boxTypes[i][0] = boxTypes[i][0]-1
if boxTypes[i][0] == 0:
i = i+1
truckSize = truckSize - 1
return sum | maximum-units-on-a-truck | trash solution hoping for coaching | charlienwq | 1 | 29 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,750 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2338936/Maximum-Units-on-a-Truck | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
n = len(boxTypes)
for i in range(n-1):
swapped = False
for j in range (n-i-1):
if(boxTypes[j][1]>boxTypes[j+1][1]):
x = boxTypes[j]
boxTypes[j]=boxTypes[j+1]
boxTypes[j+1]=x
swapped = True
if not swapped:
break
x = truckSize
out = 0
print(boxTypes)
for i in range(len(boxTypes)-1,-1,-1):
if x == 0 :
break
if boxTypes[i][0]<=x:
out+=(boxTypes[i][0]*boxTypes[i][1])
x-=boxTypes[i][0]
else:
out+=x*boxTypes[i][1]
x=0
return out | maximum-units-on-a-truck | Maximum Units on a Truck | dhananjayaduttmishra | 1 | 31 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,751 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2338936/Maximum-Units-on-a-Truck | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key = lambda x:x[1])
x = truckSize
out = 0
print(boxTypes)
for i in range(len(boxTypes)-1,-1,-1):
if x == 0 :
break
if boxTypes[i][0]<=x:
out+=(boxTypes[i][0]*boxTypes[i][1])
x-=boxTypes[i][0]
else:
out+=x*boxTypes[i][1]
x=0
return out | maximum-units-on-a-truck | Maximum Units on a Truck | dhananjayaduttmishra | 1 | 31 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,752 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2223777/Python-oror-Straight-Forward-Sorting | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
n = len(boxTypes)
for i in range(n):
boxTypes[i][0], boxTypes[i][1] = boxTypes[i][1], boxTypes[i][0]
boxTypes.sort(reverse = True)
unit, i = 0, 0
while i<n and truckSize:
if boxTypes[i][1] > truckSize:
unit += truckSize*boxTypes[i][0]
truckSize = 0
else:
truckSize -= boxTypes[i][1]
unit += boxTypes[i][1]*boxTypes[i][0]
i += 1
return unit | maximum-units-on-a-truck | Python || Straight Forward Sorting | morpheusdurden | 1 | 98 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,753 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2220794/Python3-greedy-approach-faster-than-98 | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
result = 0
for boxes, units in sorted(boxTypes, key = lambda x: x[1], reverse = True):
boxesToAdd = boxes if boxes <= truckSize else truckSize
result += boxesToAdd * units
truckSize -= boxesToAdd
return result | maximum-units-on-a-truck | 📌 Python3 greedy approach faster than 98% | Dark_wolf_jss | 1 | 15 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,754 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2220661/python3-or-easy-to-understand-or-sort | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(reverse=True, key=lambda x: x[1])
total_unit = 0
while boxTypes and truckSize>0:
box = boxTypes.pop(0)
amt_taken = min(box[0], truckSize)
total_unit += amt_taken * box[1]
truckSize -= amt_taken
return total_unit | maximum-units-on-a-truck | python3 | easy to understand | sort | H-R-S | 1 | 105 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,755 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/1930903/python-3-oror-simple-sorting-solution | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key=lambda x: x[1], reverse=True)
res = 0
for n, units in boxTypes:
if truckSize < n:
return res + units*truckSize
res += units * n
truckSize -= n
return res | maximum-units-on-a-truck | python 3 || simple sorting solution | dereky4 | 1 | 138 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,756 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/1549736/Python-easy-to-understand-O-(n-log-n)-solution-or-fractional-knap-sack-approach | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
n = len(boxTypes)
boxTypes = sorted(boxTypes, key = lambda x : x[1], reverse=True)
ans = 0
# initialize the available space as the size of the truck
spaceLeft = truckSize
for numBoxes, unitsPerBox in boxTypes:
if spaceLeft > 0:
# we can only take the num of boxes quivalent to the available space
ans += unitsPerBox * min(numBoxes, spaceLeft)
# update the remaining space in the truck
spaceLeft = spaceLeft - min(numBoxes, spaceLeft)
return ans | maximum-units-on-a-truck | [Python] easy to understand O (n log n) solution | fractional knap-sack approach | yamshara | 1 | 263 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,757 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/1272520/Python-oror-Based-on-hints-provided | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
res = 0
boxTypes.sort(key = lambda x: x[1], reverse = True)
for boxes, units in boxTypes:
if truckSize == 0: return res
if boxes >= truckSize:
res += truckSize * units
return res
else:
truckSize -= boxes
res += units * boxes
return res | maximum-units-on-a-truck | Python || Based on hints provided | airksh | 1 | 39 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,758 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/1184681/Easy-python-solution-beat-99 | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key = lambda x : -x[1])
count = 0
ans = 0
for box,val in boxTypes:
if count + box <= truckSize:
ans += box * val
count += box
else:
ans += (truckSize - count) * val
return ans
return ans | maximum-units-on-a-truck | Easy python solution beat 99% | Ayush87 | 1 | 157 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,759 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/999182/Python3-greedy | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
ans = 0
for boxes, units in sorted(boxTypes, key=lambda x: x[1], reverse=True):
boxes = min(boxes, truckSize)
ans += boxes * units
truckSize -= boxes
return ans | maximum-units-on-a-truck | [Python3] greedy | ye15 | 1 | 93 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,760 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2726277/O(nlogn)-time-or-O(1)-space-or-Easy | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key=lambda x:x[1], reverse = True)
boxes = 0
units = 0
for b, s in boxTypes:
if truckSize > 0:
if b > truckSize:
b = truckSize
units += b*s
truckSize = truckSize - b
else:
break
return units | maximum-units-on-a-truck | O(nlogn) time | O(1) space | Easy | wakadoodle | 0 | 12 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,761 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2661618/Sort-using-Lambda-first | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key= lambda row: row[1], reverse= True)
ans = 0
for i in boxTypes:
if i[0] <= truckSize:
ans += i[0] * i[1]
truckSize -= i[0]
else:
ans += truckSize * i[1]
return ans
return ans | maximum-units-on-a-truck | Sort using Lambda first | zhuoya-li | 0 | 2 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,762 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2640909/Simple-python-code-with-explanation | class Solution:
#Greedy algorithm
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
#sort the boxtypes based on the numberOfUnitsPerBox in desecnding order
boxTypes = sorted(boxTypes , key = lambda x:x[1],reverse = True)
#create a varible total and assign it to 0
#total variable to store the maximum total number of units
#that can put on the truck
total = 0
#iterate of the lists in boxTypes 2Dlist
for i in boxTypes:
#while truck space is left and while no. of boxes of one type left
while truckSize and i[0]:
#add the boxunits to total
total = total + i[1]
#decrese the size of truck by 1
truckSize -=1
#decrese the no. of boxes of one type by 1
i[0] -=1
#if the truckSize is full
#it means that truck is already filled
if truckSize == 0 :
#so break from the loop
break
#return the maximum total number of units that can be put on the truck
return total | maximum-units-on-a-truck | Simple python code with explanation | thomanani | 0 | 47 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,763 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2536716/Python3-solution-using-lambda-sort-and-reverse! | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
max_total_units = 0
boxTypes.sort(key=lambda x: x[1])
boxTypes.reverse()
for box_type in boxTypes:
if truckSize < 0:
return max_total_units
diff = truckSize - box_type[0]
if diff > 0:
max_total_units += (box_type[0] * box_type[1])
else:
max_total_units += (truckSize * box_type[1])
truckSize = diff
return max_total_units | maximum-units-on-a-truck | Python3 solution using lambda, sort, and reverse! | samanehghafouri | 0 | 28 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,764 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2492419/Python-O(n-log-n)-Time-and-O(1)-Space | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes = sorted(boxTypes, key=lambda x: x[1], reverse=True)
result = 0
for count, units in boxTypes:
if count <= truckSize:
truckSize -= count
result += count * units
elif truckSize > 0:
result += truckSize * units
truckSize = 0
elif truckSize == 0:
break
return result | maximum-units-on-a-truck | [Python] O(n log n) Time and O(1) Space | tejeshreddy111 | 0 | 118 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,765 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2378502/Simple-and-Easy-PYTHON-solution | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
lis = list(reversed(sorted(boxTypes,key=lambda item:item[1])))
print(lis)
summ = 0
temp = 0
for i in range(len(lis)):
numberOfBoxes = lis[i][0]
numberOfUnitsPerBox = lis[i][1]
summ += numberOfBoxes
if summ>truckSize:
break
elif summ<=truckSize:
rem = truckSize - summ
temp += numberOfBoxes * numberOfUnitsPerBox
if i==len(lis)-1 and summ < truckSize:
return temp
else:
temp += rem*lis[i][1]
return temp | maximum-units-on-a-truck | Simple & Easy PYTHON solution | BANALA_DEEPTHI | 0 | 103 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,766 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2285652/Python-sort-and-calculate-very-easy | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
dic = sorted(boxTypes, key= lambda kv:kv[1], reverse=True)
ans = 0
while truckSize and dic:
nb, qn = dic.pop(0)
if nb <= truckSize:
ans += nb * qn
truckSize -= nb
elif nb > truckSize:
ans += truckSize * qn
truckSize -= truckSize
return ans | maximum-units-on-a-truck | Python sort and calculate, very easy | G_Venkatesh | 0 | 89 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,767 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2257774/Python3-or-Faster-than-92 | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key = lambda x : x[1], reverse = True)
output = 0
for b in boxTypes:
if not truckSize:
break
if truckSize - b[0] > 0:
output += (b[0] * b[1])
truckSize -= b[0]
else:
output += (truckSize * b[1])
truckSize = 0
return output | maximum-units-on-a-truck | ✅Python3 | Faster than 92% | thesauravs | 0 | 64 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,768 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2257123/265ms-faster-than-50-solutions-or-EASY-or-Python3 | '''class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key=lambda x:x[1],reverse=True)
lst=[]
while truckSize!=0:
for box in boxTypes:
num=0
if truckSize>=box[0]:
num=box[0]
lst.append(num*box[1])
truckSize=truckSize-num
else:
num=truckSize
lst.append(num*box[1])
truckSize=truckSize-num
if len(lst)==len(boxTypes):
break
s=sum(lst)
return s
print(maximumUnits(boxTypes,truckSize))''' | maximum-units-on-a-truck | 265ms faster than 50% solutions | EASY | Python3 | keertika27 | 0 | 51 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,769 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2224633/Faster-than-91.78-Simple-Python-Solution-Sorting-Greedy-Basic-Math | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
units = 0
boxTypes.sort(key=lambda x: x[1], reverse=True)
while truckSize != 0 and len(boxTypes) != 0:
numberOfBoxes = boxTypes[0][0]
numberOfUnits = boxTypes[0][1]
if numberOfBoxes > truckSize:
numberOfBoxes = truckSize
units += numberOfBoxes * numberOfUnits
truckSize -= numberOfBoxes
boxTypes.pop(0)
return units | maximum-units-on-a-truck | Faster than 91.78% - Simple Python Solution - Sorting / Greedy / Basic Math | 7yler | 0 | 31 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,770 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2224521/Simple-Solution-Python | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key=lambda row: row[1], reverse=True)
max_unit = 0
for box in boxTypes:
N_box = box[0]
unit_box = box[1]
if truckSize < N_box:
max_unit += unit_box * truckSize
else:
max_unit += unit_box * N_box
truckSize -= N_box
if truckSize <= 0:
return max_unit
return max_unit | maximum-units-on-a-truck | Simple Solution [Python] | salsabilelgharably | 0 | 11 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,771 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2224330/python-ez-solution-greedy | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key = lambda x:-x[1])
output = 0
index = 0
while index < len(boxTypes):
if truckSize == 0:
break
else:
if boxTypes[index][0] < truckSize:
truckSize -= boxTypes[index][0]
output += boxTypes[index][1]*boxTypes[index][0]
else:
output += boxTypes[index][1]*truckSize
break
index += 1
return output | maximum-units-on-a-truck | python ez solution greedy | yingziqing123 | 0 | 3 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,772 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2223631/Python-oror-Sorting-%2B-Greedy | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key=lambda x:x[1],reverse=True) #Sorting boxTypes in descending order based on 2nd element of the list/array
i = 0
res = 0
n = len(boxTypes)
while truckSize>0 and i<n:
if(truckSize > boxTypes[i][0]):
res += boxTypes[i][0]*boxTypes[i][1]
truckSize -= boxTypes[i][0]
else:
res += truckSize*boxTypes[i][1]
truckSize=0
i+=1
return res | maximum-units-on-a-truck | Python || Sorting + Greedy | Vaishnav19 | 0 | 23 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,773 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2223607/Python-Solution-or-Sorting-and-Greedy-Based-or-98-Faster | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
# sort on basis of units
unitSorted = sorted(boxTypes,key=lambda x: x[1],reverse=True)
currSum = 0
rem = truckSize
# iterate through sorted units and boxes
for boxes, units in unitSorted:
# get min of remaining boxes and available boxes
currBoxes = min(boxes,rem)
currSum += units * currBoxes
rem -= currBoxes
# early stopping
if rem == 0:
break
return currSum | maximum-units-on-a-truck | Python Solution | Sorting and Greedy Based | 98% Faster | Gautam_ProMax | 0 | 17 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,774 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2223360/Slow-but-easy-python-solution | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key=lambda x: x[1], reverse=True)
remainingSize = truckSize
totalUnits = 0
i = 0
for boxes, units in boxTypes:
if remainingSize >= boxes:
remainingSize -= boxes
totalUnits += boxes * units
i += 1
else:
break
if i == len(boxTypes):
return totalUnits
if remainingSize > 0:
totalUnits += remainingSize * boxTypes[i][1]
return totalUnits | maximum-units-on-a-truck | Slow but easy python solution | prameshbajra | 0 | 21 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,775 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2223220/1710.-Maximum-Units-on-a-Truck | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key=lambda x:x[1],reverse=True)
profit=0
for i in range(len(boxTypes)):
if truckSize>=boxTypes[i][0]:
profit+=boxTypes[i][0]*boxTypes[i][1]
truckSize-=boxTypes[i][0]
elif boxTypes[i][0]>truckSize>0:
profit+=truckSize*boxTypes[i][1]
truckSize=0
return profit | maximum-units-on-a-truck | 1710. Maximum Units on a Truck | Revanth_Yanduru | 0 | 9 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,776 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2222961/Easy-Python-Solution-with-explanation | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
maxUnits=0
boxTypes.sort(key=lambda row: (row[1], row[0]), reverse=True)
for array in boxTypes:
if array[0]<truckSize:
maxUnits+=array[1]*array[0]
truckSize-=array[0]
else:
maxUnits+=truckSize*array[1]
break
return maxUnits | maximum-units-on-a-truck | Easy Python Solution with explanation | AmmarAmmar | 0 | 37 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,777 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2222753/Easy-python-solution-or-Maximum-Units-on-a-Truck | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
maximum = 0
boxTypes.sort(reverse=True,key=lambda x:x[1])
for boxType in boxTypes:
if truckSize == 0:
return maximum
if boxType[0] < truckSize:
maximum += boxType[1] * boxType[0]
truckSize -= boxType[0]
else:
maximum += boxType[1] * truckSize
truckSize -= truckSize
return maximum | maximum-units-on-a-truck | Easy python solution | Maximum Units on a Truck | nishanrahman1994 | 0 | 12 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,778 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2222441/Python-Solution | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key=lambda p:(-p[1],p[0]))
count=0
for i in boxTypes:
if i[0]<=truckSize:
count+=(i[0]*i[1])
i[1]=0
truckSize-=i[0]
else:
c=(i[0]/i[0])*truckSize
count+=(c)*i[1]
truckSize-=c
i[1]-=int(c)
return(int(count)) | maximum-units-on-a-truck | Python Solution | SakshiMore22 | 0 | 10 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,779 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2222332/Greedy-O(nlogn)-Python-Solution | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
# Time - O(nlogn) Space - O(n) -> Tim Sort for sorting
boxTypes.sort(key = lambda x: -x[1]) # sort according to no. of units
maxUnits = 0
for n,u in boxTypes:
if truckSize == 0:
break;
n = min(n, truckSize)
maxUnits += (n * u)
truckSize -= n
return maxUnits | maximum-units-on-a-truck | Greedy - O(nlogn) Python Solution | Deepansh_01 | 0 | 8 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,780 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2222134/Faster-than-97.20-of-Python3-oror-O(nlogn)-time-complexity | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key = lambda x: x[1], reverse=True)
size, res = 0, 0
for c, u in boxTypes:
size += c
if size <= truckSize:
res += c * u
else:
res += (truckSize-(size-c)) * u
break
return res | maximum-units-on-a-truck | Faster than 97.20% of Python3 || O(nlogn) time complexity | sagarhasan273 | 0 | 24 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,781 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2221636/Python-3-or-O(nlogn)-or-Easy-Sorting-or-Faster-than-40 | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key=lambda x: x[1], reverse=True)
units, i = 0, 0
while truckSize > 0 and i < len(boxTypes):
units += min(truckSize,boxTypes[i][0]) * boxTypes[i][1]
truckSize -= boxTypes[i][0]
i += 1
return units | maximum-units-on-a-truck | Python 3 | O(nlogn) | Easy Sorting | Faster than 40% | MrShobhit | 0 | 29 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,782 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2221610/Simple-python-sorting-solution-easy-understanding | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes = sorted(boxTypes , key=lambda x:[x[1], x[0]] , reverse=True)
totalunit = 0
box_included =0
for i in range(len(boxTypes)):
totalunit = totalunit + (min((truckSize-box_included) , boxTypes[i][0])* boxTypes[i][1])
box_included = box_included + min((truckSize-box_included) , boxTypes[i][0])
return totalunit | maximum-units-on-a-truck | Simple python sorting solution easy understanding | Afzal543 | 0 | 10 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,783 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2221290/Python-Very-Easy-Solution | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key=lambda x:x[1], reverse=True)
# print(boxTypes)
count = 0
unit = 0
for x in boxTypes:
temp = 0
while temp < x[0] and count < truckSize:
count+=1
unit += x[1]
temp+=1
return unit | maximum-units-on-a-truck | Python Very Easy Solution | vaibhav0077 | 0 | 11 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,784 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2221191/Intuitive-Approach-and-Solution | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes = sorted(boxTypes, key = lambda x : -x[1])
totalBoxes = 0
maximumUnits = 0
for boxes, units in boxTypes:
totalBoxes += boxes
if totalBoxes <= truckSize:
maximumUnits += boxes*units
else:
totalBoxes -= boxes
maximumUnits += (truckSize - totalBoxes)*units
break
return maximumUnits | maximum-units-on-a-truck | Intuitive Approach and Solution | Vaibhav7860 | 0 | 7 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,785 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2220827/Python-short-solution | class Solution:
def maximumUnits(self, box_types: List[List[int]], truck_size: int) -> int:
boxes = sorted(box_types, key=itemgetter(1))
units = 0
while truck_size and boxes:
boxes_of_this_types = min(truck_size, boxes[-1][0])
truck_size -= boxes_of_this_types
units += boxes_of_this_types * boxes.pop()[1]
return units | maximum-units-on-a-truck | Python short solution | meatcodex | 0 | 11 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,786 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2220809/Python3-faster-than-87.09-or-less-than-83.07-or-easy-math-question | class Solution:
def maximumUnits(self, a: List[List[int]], b: int) -> int:
arr = sorted(a, key=lambda s: s[-1], reverse=True)
res = 0
for k, i in arr:
if b-k >= 0:
b-=k
res += k*i
else:
res += b*i
break
return res | maximum-units-on-a-truck | Python3 faster than 87.09% | less than 83.07% | easy math question | khRay13 | 0 | 10 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,787 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2220490/Python-or-Simple-Solution-with-Comments | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
#Initialize result variable
result = 0
#Sort boxes by "box score"
boxTypes.sort(key=lambda x: -x[1])
#Loop over all box types
for num, score in boxTypes:
#Make sure num doesn't go over the truckSize left
num = min(num,truckSize)
#Add box score to result
result += score * num
#Subtrack boxes from truckSize
truckSize -= num
#Break out of loop if there is no more room on the truck
if truckSize <= 0: break
#Return the result
return result | maximum-units-on-a-truck | Python | Simple Solution with Comments | benjaminhalko | 0 | 19 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,788 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2220459/python-3-solution | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(key = lambda k: (k[1]),reverse=True)
maxResult = 0
for i in range(0,len(boxTypes)):
if truckSize <= 0:
break
currBoxes,currUnits = boxTypes[i]
if currBoxes >= truckSize:
maxResult += (truckSize*currUnits)
else:
maxResult += currBoxes*currUnits
truckSize-=currBoxes
return maxResult
* * * | maximum-units-on-a-truck | python 3 solution | gurucharandandyala | 0 | 5 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,789 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2214766/Faster-than-77.56 | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
maxval = 0
boxTypes.sort(key=lambda x:x[1], reverse=True)
for i in range(len(boxTypes)):
if truckSize >= 0:
if boxTypes[i][0] <= truckSize:
maxval += boxTypes[i][0] * boxTypes[i][1]
truckSize -= boxTypes[i][0]
if truckSize == 0 or i == len(boxTypes)-1:
return maxval
else:
boxTypes[i][0] = truckSize
maxval += boxTypes[i][0] * boxTypes[i][1]
truckSize -= boxTypes[i][0]
if truckSize == 0 or i == len(boxTypes)-1:
return maxval | maximum-units-on-a-truck | Faster than 77.56% | psnakhwa | 0 | 25 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,790 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2208018/Python3-Solution-or-Sort-list-boxTypes-using-index-1-val-(numberOfUnitsPerBox)-of-inner-lists | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
boxTypes.sort(reverse = True, key = lambda x: x[1])
noofunits = 0
for box in boxTypes:
if truckSize - box[0] <= 0:
noofunits += truckSize*box[1]
break
truckSize = truckSize - box[0]
noofunits += box[0]*box[1]
return noofunits | maximum-units-on-a-truck | Python3 Solution | Sort list boxTypes using index 1 val (numberOfUnitsPerBox) of inner lists | mediocre-coder | 0 | 23 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,791 |
https://leetcode.com/problems/maximum-units-on-a-truck/discuss/2090943/Greedy-approach-using-priority-queue-(Faster-~97) | class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
res = 0
q = deque(sorted(boxTypes, key=lambda b: b[1], reverse=True))
while q and truckSize:
boxes, units = q.popleft()
while boxes:
if boxes <= truckSize:
res += boxes * units
truckSize -= boxes
boxes = 0
else:
boxes -= 1
return res | maximum-units-on-a-truck | Greedy approach using priority queue (Faster ~97%) | andrewnerdimo | 0 | 46 | maximum units on a truck | 1,710 | 0.739 | Easy | 24,792 |
https://leetcode.com/problems/count-good-meals/discuss/999170/Python3-frequency-table | class Solution:
def countPairs(self, deliciousness: List[int]) -> int:
ans = 0
freq = defaultdict(int)
for x in deliciousness:
for k in range(22): ans += freq[2**k - x]
freq[x] += 1
return ans % 1_000_000_007 | count-good-meals | [Python3] frequency table | ye15 | 43 | 4,100 | count good meals | 1,711 | 0.29 | Medium | 24,793 |
https://leetcode.com/problems/count-good-meals/discuss/999170/Python3-frequency-table | class Solution:
def countPairs(self, deliciousness: List[int]) -> int:
freq = defaultdict(int)
for x in deliciousness: freq[x] += 1
ans = 0
for x in freq:
for k in range(22):
if 2**k - x <= x and 2**k - x in freq:
ans += freq[x]*(freq[x]-1)//2 if 2**k - x == x else freq[x]*freq[2**k-x]
return ans % 1_000_000_007 | count-good-meals | [Python3] frequency table | ye15 | 43 | 4,100 | count good meals | 1,711 | 0.29 | Medium | 24,794 |
https://leetcode.com/problems/count-good-meals/discuss/999197/python3-O(N)-or-100-or-100-or-easy-to-understand | class Solution:
"""
dp -> key: i value: amount of deliciousness == i
for d in 2**0, 2**1, ..., 2**21
why 2**21: max of deliciousness is 2*20, sum of 2 max is 2**21
O(22*N)
"""
def countPairs(self, ds: List[int]) -> int:
from collections import defaultdict
dp = defaultdict(int)
# ds.sort() # no need to sort
res = 0
for d in ds:
for i in range(22):
# if 2**i - d in dp:
res += dp[2**i - d]
dp[d] += 1
return res % (10**9 + 7) | count-good-meals | [python3] O(N) | 100% | 100% | easy to understand | YubaoLiu | 5 | 1,100 | count good meals | 1,711 | 0.29 | Medium | 24,795 |
https://leetcode.com/problems/count-good-meals/discuss/999195/Python-Simplest-Solution-or-Heap-or-Similar-to-Two-Sum | class Solution(object):
def countPairs(self, deliciousness):
hq, res, counts = [], 0, collections.Counter(deliciousness)
for num, times in counts.items():
heapq.heappush(hq, (-num, times))
while hq:
i, sumN = heapq.heappop(hq), 1
while sumN <= 2 * -i[0]:
candi = sumN + i[0]
if candi == -i[0]:
res = res + i[1] * (i[1]-1) // 2 if i[1] >= 2 else res
elif candi in counts:
res += i[1] * counts[candi]
sumN *= 2
return res % (10**9 + 7) | count-good-meals | [Python] Simplest Solution | Heap | Similar to Two Sum | ianliuy | 1 | 431 | count good meals | 1,711 | 0.29 | Medium | 24,796 |
https://leetcode.com/problems/count-good-meals/discuss/2742619/Python3-Easy-Straightforward-Commented-linear-Solution | class Solution:
# get all the powers of two
powers = set([2**exp for exp in range(22)])
def countPairs(self, deliciousness: List[int]) -> int:
# count the number of occurences
cn = collections.Counter(deliciousness)
# iterate over the combinations
result = 0
for item, amount in cn.items():
# get all the self pairs
if item in self.powers:
result += amount*(amount-1)//2
# check for all powers of two
# if our counterpart has values
for power in self.powers:
if power > 2*item:
result += cn[power - item]*amount
return result % 1_000_000_007 | count-good-meals | [Python3] - Easy, Straightforward, Commented, linear Solution | Lucew | 0 | 8 | count good meals | 1,711 | 0.29 | Medium | 24,797 |
https://leetcode.com/problems/count-good-meals/discuss/2517090/Python-runtime-67.34-memory-37.28 | class Solution:
def countPairs(self, deliciousness: List[int]) -> int:
d = {}
for n in deliciousness:
if n not in d:
d[n] = 1
else:
d[n] += 1
ans = 0
for power in range(22):
target = 2**power
for key in d.keys():
diff = target - key
if diff == key:
ans += d[key]*(d[key]-1)/2
elif diff in d:
ans += d[key]*d[diff]/2
return int(ans % (10**9+7)) | count-good-meals | Python, runtime 67.34%, memory 37.28% | tsai00150 | 0 | 62 | count good meals | 1,711 | 0.29 | Medium | 24,798 |
https://leetcode.com/problems/count-good-meals/discuss/2517090/Python-runtime-67.34-memory-37.28 | class Solution:
def countPairs(self, deliciousness: List[int]) -> int:
d = {}
ans = 0
for n in deliciousness:
for power in range(22):
diff = 2**power - n
if diff in d:
ans += d[diff]
if n not in d:
d[n] = 1
else:
d[n] += 1
return int(ans % (10**9+7)) | count-good-meals | Python, runtime 67.34%, memory 37.28% | tsai00150 | 0 | 62 | count good meals | 1,711 | 0.29 | Medium | 24,799 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.