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/length-of-longest-fibonacci-subsequence/discuss/942291/Python3-dp-O(N2)
class Solution: def lenLongestFibSubseq(self, A: List[int]) -> int: ss = set(A) seen = {} for i in range(len(A)): for j in range(i): if A[i] - A[j] < A[j] and A[i] - A[j] in ss: seen[A[i], A[j]] = 1 + seen.get((A[j], A[i] - A[j]), 2) return max(seen.values(), default=0)
length-of-longest-fibonacci-subsequence
[Python3] dp O(N^2)
ye15
0
140
length of longest fibonacci subsequence
873
0.486
Medium
14,200
https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/discuss/352955/Solution-in-Python-3
class Solution: def lenLongestFibSubseq(self, A: List[int]) -> int: L, M, AA = len(A), 0, {i for i in A} for i in range(L-1): for j in range(i+1,L): a, b, s = A[i], A[j], 0 while a in AA: a, b, s = b, a + b, s + 1 if s > M: M = s if a > A[-1]: if j == i + 1: return 0 if M == 2 else M break - Junaid Mansuri (LeetCode ID)@hotmail.com
length-of-longest-fibonacci-subsequence
Solution in Python 3
junaidmansuri
0
443
length of longest fibonacci subsequence
873
0.486
Medium
14,201
https://leetcode.com/problems/walking-robot-simulation/discuss/381840/Solution-in-Python-3
class Solution: def robotSim(self, c: List[int], b: List[List[int]]) -> int: x, y, d, b, M = 0, 0, 0, set([tuple(i) for i in b]), 0 for i in c: if i < 0: d = (d + 2*i + 3)%4 else: if d in [1,3]: for x in range(x, x+(i+1)*(2-d), 2-d): if (x+(2-d), y) in b: break else: for y in range(y, y+(i+1)*(1-d), 1-d): if (x, y+(1-d)) in b: break M = max(M, x**2 + y**2) return M - Junaid Mansuri (LeetCode ID)@hotmail.com
walking-robot-simulation
Solution in Python 3
junaidmansuri
3
513
walking robot simulation
874
0.384
Medium
14,202
https://leetcode.com/problems/walking-robot-simulation/discuss/2782108/Python-logic-step-breakdown
class Solution: def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int: directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] facing = best = 0 distance = lambda x, y: x**2 + y**2 current = (0, 0) obstacles = {(p[0], p[1]) for p in obstacles} for c in commands: if c == -1: facing = (facing + 1) % 4 elif c == -2: facing = (facing + 3) % 4 elif 1 <= c <= 9: for i in range(c): newx = current[0] + directions[facing][0] newy = current[1] + directions[facing][1] if (newx, newy) not in obstacles: current = (newx, newy) best = max(best, distance(current[0], current[1])) else: break else: raise ValueError return best
walking-robot-simulation
Python logic step breakdown
modusV
0
8
walking robot simulation
874
0.384
Medium
14,203
https://leetcode.com/problems/walking-robot-simulation/discuss/1511730/Python-very-clear-simple-solution
class Solution: def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int: maxd = 0 left = {'N':'W', 'W':'S', 'S':'E', 'E':'N'} right = {'N':'E', 'E':'S', 'S':'W', 'W':'N'} step = {'N':[0,1], 'W':[-1, 0], 'E':[1,0], 'S':[0,-1]} obstacle = set() for o in obstacles: obstacle.add((o[0], o[1])) x, y = 0, 0 curr_dir = 'N' for com in commands: if com == -2: curr_dir = left[curr_dir] elif com == -1: curr_dir = right[curr_dir] else: # com > 0, we should go forward cnt = 0 d = step[curr_dir] while cnt < com and (x+d[0], y+d[1]) not in obstacle: x += d[0] y += d[1] maxd = max(maxd, x**2+y**2) cnt += 1 return maxd
walking-robot-simulation
Python very clear, simple solution
byuns9334
0
133
walking robot simulation
874
0.384
Medium
14,204
https://leetcode.com/problems/walking-robot-simulation/discuss/1425765/Put-obstacles-into-a-set-of-tuples-93-speed
class Solution: def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int: # direction: 0-north, 1-east, 2, south, 3-west direction = x = y = 0 max_distance = 0 obstacles = set((x, y) for x, y in obstacles) for command in commands: if command == -2: direction = (direction - 1) % 4 continue elif command == -1: direction = (direction + 1) % 4 continue elif 0 < command < 10: if direction == 0: for _ in range(command): if (x, y + 1) in obstacles: break else: y += 1 elif direction == 1: for _ in range(command): if (x + 1, y) in obstacles: break else: x += 1 elif direction == 2: for _ in range(command): if (x, y - 1) in obstacles: break else: y -= 1 elif direction == 3: for _ in range(command): if (x - 1, y) in obstacles: break else: x -= 1 max_distance = max(max_distance, x * x + y * y) return max_distance
walking-robot-simulation
Put obstacles into a set of tuples, 93% speed
EvgenySH
0
107
walking robot simulation
874
0.384
Medium
14,205
https://leetcode.com/problems/walking-robot-simulation/discuss/1346995/Python3%3A-Intuitively-broken-up-with-functions
class Solution: def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int: # Initialize self.obsticles_dict = {f"{x},{y}": 1 for [x,y] in obstacles} self.cur_position = {'x':0, 'y':0} self.cur_direction = 0 self.max_distance = 0 # Run through each command for command in commands: if command < 0: self.rotate(command) else: self.move(command) self.updateMaxDistance() return self.max_distance def rotate(self, command: int) -> None: rotation = +1 if command == -1 else -1 self.cur_direction = (self.cur_direction + rotation) % 4 def move(self, command: int) -> None: cur_position = self.cur_position.copy() for step in range(command): if self.cur_direction == 0: cur_position['y'] += 1 # North elif self.cur_direction == 1: cur_position['x'] += 1 # East elif self.cur_direction == 2: cur_position['y'] -= 1 # South elif self.cur_direction == 3: cur_position['x'] -= 1 # West if f"{cur_position['x']},{cur_position['y']}" in self.obsticles_dict: return None else: self.cur_position = cur_position.copy() def updateMaxDistance(self) -> None: self.max_distance = max( self.cur_position['x']**2 + self.cur_position['y']**2, self.max_distance )
walking-robot-simulation
Python3: Intuitively broken up with functions
jdouitsis
0
145
walking robot simulation
874
0.384
Medium
14,206
https://leetcode.com/problems/walking-robot-simulation/discuss/1240309/Time-limit-exceeded-when-I-click-%22Submit%22-not-when-I-click-%22Run-Code%22-for-same-input
class Solution: def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int: # A utility function to move robot east def go_east(num, obstacles, curr): new = curr for i in range(1,num): if [curr[0]+i, curr[1]] in obstacles: return new else: new = [curr[0]+i, curr[1]] return new # A utility function to move robot south def go_south(num, obstacles, curr): new = curr for i in range(1,num): if [curr[0], curr[1]-i] in obstacles: return new else: new = [curr[0], curr[1]-i] return new # A utility function to move robot west def go_west(num, obstacles, curr): new = curr for i in range(1,num): if [curr[0]-i, curr[1]] in obstacles: return new else: new = [curr[0]-i, curr[1]] return new # A utility function to move robot north def go_north(num, obstacles, curr): new = curr for i in range(1,num): # print("new:", [curr[0], curr[1]+i]) if [curr[0], curr[1]+i] in obstacles: # print("new:", new) return new else: new = [curr[0], curr[1]+i] return new # Get the next direction that the robot must now turn to def get_geographic_direction(curr_dir, turn_command): def get_next_direction(turn): if turn==-1: return "right" else: return "left" # D = {curr_direction:{"..change-type..":new_direction, ...}} D = {go_north:{"left":go_west, "right":go_east }, go_south:{"left":go_east, "right":go_west }, go_east: {"left":go_north, "right":go_south}, go_west: {"left":go_south, "right":go_north}} # Get the next grographical direction to turn to next_turn = get_next_direction(turn_command) return D[curr_dir][next_turn] # Keeping a track of maximum distance till now max_distance = 0 # Start Position curr = [0,0] # Start Direction move_in_curr_dir = go_north # Extra flags, useful in the case of [0,0] is in obstacles first_step = True has_origin = False # Iterating through all commands for i in range(len(commands)): # Changing direction if commands[i]<0: move_in_curr_dir = get_geographic_direction(move_in_curr_dir, commands[i]) # No action elif commands[i]==0: pass # Moving else: curr = move_in_curr_dir(commands[i]+1, obstacles, curr) first_Step = False curr_distance = curr[0]**2+curr[1]**2 if curr_distance>max_distance: max_distance = curr_distance return max_distance
walking-robot-simulation
Time limit exceeded when I click "Submit", not when I click "Run Code" for same input
shuklaeshita0209
0
80
walking robot simulation
874
0.384
Medium
14,207
https://leetcode.com/problems/walking-robot-simulation/discuss/695625/Python3-beats-99.5.-Movement-simulation
class Solution: def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int: obstacles = set(tuple(x) for x in obstacles) i = 0 x,y = 0,0 max_dist = float('-inf') direction = "N" while(i<len(commands)): if(commands[i]==-1): if(direction=='N'): direction = 'E' elif(direction=='S'): direction = 'W' elif(direction=='W'): direction = 'N' else: direction = 'S' elif(commands[i]==-2): if(direction=='N'): direction = 'W' elif(direction=='S'): direction = 'E' elif(direction=='W'): direction = 'S' else: direction = 'N' else: if(direction=='N'): while(commands[i]!=0): commands[i] -= 1 y += 1 if((x,y) in obstacles): y -= 1 break elif(direction=='E'): while(commands[i]!=0): commands[i] -= 1 x += 1 if((x,y) in obstacles): x -= 1 break elif(direction=='W'): while(commands[i]!=0): commands[i] -= 1 x -= 1 if((x,y) in obstacles): x += 1 break else: while(commands[i]!=0): commands[i] -= 1 y -= 1 if((x,y) in obstacles): y += 1 break if(max_dist<x*x + y*y): max_dist = pow(x,2) + pow(y,2) i += 1 return(max_dist)
walking-robot-simulation
Python3 - beats 99.5%. - Movement simulation
vs152
0
257
walking robot simulation
874
0.384
Medium
14,208
https://leetcode.com/problems/walking-robot-simulation/discuss/638677/Intuitive-and-cumbersome-approach-with-comment-as-explanation
class Solution: def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int: # 0) Keep obstacke in set for future reference obstacle_set = set() for o in obstacles: obstacle_set.add((o[0], o[1])) # 1) Define movement functions and way to turn direction up = lambda pos: (pos[0], pos[1]+1) down = lambda pos: (pos[0], pos[1]-1) left = lambda pos: (pos[0]-1, pos[1]) right = lambda pos: ((pos[0]+1, pos[1])) moves = [up, right, down, left] cpos = (0, 0) mi = 0 def turn(mi, v): return (mi + 1) % 4 if v == -1 else (mi - 1 + 4) % 4 move = lambda pos: moves[mi](cpos) # 2) Execute the command(s) max_dist = 0 for cmd in commands: if cmd < 0: mi = turn(mi, cmd) else: for _ in range(cmd): next_pos = move(cpos) if next_pos in obstacle_set: break cpos = next_pos max_dist = max(max_dist, pow(cpos[0], 2) + pow(cpos[1], 2)) # 3) Return the result return max_dist
walking-robot-simulation
Intuitive and cumbersome approach with comment as explanation
puremonkey2001
0
111
walking robot simulation
874
0.384
Medium
14,209
https://leetcode.com/problems/koko-eating-bananas/discuss/1705145/Python-BinarySearch-%2B-Optimizations-or-Explained
class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: k = 1 while True: total_time = 0 for i in piles: total_time += ceil(i / k) if total_time > h: k += 1 else: return k
koko-eating-bananas
[Python] BinarySearch + Optimizations | Explained
anCoderr
20
814
koko eating bananas
875
0.521
Medium
14,210
https://leetcode.com/problems/koko-eating-bananas/discuss/1705145/Python-BinarySearch-%2B-Optimizations-or-Explained
class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: k = ceil(sum(piles)/h) while True: total_time = 0 for i in piles: total_time += ceil(i/k) if total_time > h: break # as time exceeds H if total_time <= h: return k # answer found as time is in the given limits. k += 1
koko-eating-bananas
[Python] BinarySearch + Optimizations | Explained
anCoderr
20
814
koko eating bananas
875
0.521
Medium
14,211
https://leetcode.com/problems/koko-eating-bananas/discuss/1705145/Python-BinarySearch-%2B-Optimizations-or-Explained
class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: left = ceil(sum(piles) / h) # lower bound of Binary Search right = max(piles) # upper bound of Binary Search while left < right: mid = (left + right) // 2 # we check for k=mid total_time = 0 for i in piles: total_time += ceil(i / mid) if total_time > h: break if total_time <= h: right = mid # answer must lie to the left half (inclusive of current value ie mid) else: left = mid + 1 # answer must lie to the right half (exclusive of current value ie mid) return right
koko-eating-bananas
[Python] BinarySearch + Optimizations | Explained
anCoderr
20
814
koko eating bananas
875
0.521
Medium
14,212
https://leetcode.com/problems/koko-eating-bananas/discuss/1484486/Binary-search-solution
class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: def feasible(speed): return sum((pile-1) //speed+1 for pile in piles) <= h # faster #hour=1 #s=0 #for pile in piles: #s+=pile #if s>speed: #s=pile #if hour>h: #return False #return True left, right = 1, max(piles) while left < right: mid = left + (right - left) // 2 if feasible(mid): right = mid else: left = mid + 1 return left
koko-eating-bananas
Binary search solution
Qyum
3
131
koko eating bananas
875
0.521
Medium
14,213
https://leetcode.com/problems/koko-eating-bananas/discuss/1537814/Python3-From-Linear-Search-to-Binary-Search
class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: """ 3 6 7 11 , h =8 speed = 1 3 6 7 11 = 28h > 8h speed = 2 3 3 4 6 = 16h > 8h speed = 3 1 2 3 4 = 10h > 8h minimum ----> speed = 4 1 2 2 3 = 8h = 8h <------- speed = 5 1 2 2 3 = 8h = 8h speed = 6 1 1 2 2 = 8h = 8h speed = 7 1 1 1 2 = 5h < 8h speed = 8 1 1 1 2 = 5h < 8h speed = 9 1 1 1 2 = 5h < 8h speed =10 1 1 1 2 = 5h < 8h speed =11 1 1 1 1 = 4h < 8h ^ | we are searching the first 8 on this column. """ self.piles = piles #print(self.piles) #ans1 = self.linearSearch(h) # time limit exceeded ans2 = self.binarySearch(h) return ans2 def linearSearch(self,h): l,r = 1,max(self.piles) for i in range(l,r+1): if self.eatingTime(i) <= h: return i def binarySearch(self,h): l, r = 1, max(self.piles) while l < r: m = l + (r-l) // 2 time = self.eatingTime(m) if time > h: l = m + 1 else: r = m return l def eatingTime(self,k): # return at current speed k, how much time needed to eat all the piles in the list time = 0 for i in self.piles: curTime = ceil(i / k) time += curTime return time
koko-eating-bananas
[Python3] From Linear Search to Binary Search
zhanweiting
2
263
koko eating bananas
875
0.521
Medium
14,214
https://leetcode.com/problems/koko-eating-bananas/discuss/1705284/Easy-to-understand-oror-Binary-Search-oror-faster-than-80-oror-python3
class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: def canfinsh(k): h_needed = 0 for p in piles: h_needed += ceil(p/k) return h_needed <= h left = 1 right = max(piles) while left < right: mid = left + (right - left)//2 if canfinsh(mid): right = mid else: left = mid+1 return right
koko-eating-bananas
Easy to understand || Binary Search || faster than 80% || python3
code_Shinobi
1
114
koko eating bananas
875
0.521
Medium
14,215
https://leetcode.com/problems/koko-eating-bananas/discuss/1704253/Python-Solution
class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: low, high = 1, max(piles) while low <= high: mid = low + (high - low) // 2 total_hours = 0 for pile in piles: total_hours += ceil(pile / mid) if total_hours > h: low = mid + 1 else: k = mid high = mid - 1 return k
koko-eating-bananas
Python Solution
mariandanaila01
1
116
koko eating bananas
875
0.521
Medium
14,216
https://leetcode.com/problems/koko-eating-bananas/discuss/1703516/Python3-Binary-Search-Simple-and-Logic-Explained
class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: l,r = 1,max(piles) # declare boundaries while l<r: # loop performing BS m = l+(r-l)//2 # calculate medium hours = sum([ceil(p/m) for p in piles]) # calculate hours take if hours > h: # if eat too slow -> improve speed l = m + 1 else: # if eat too fast -> narrow r and converge to result r = m return l
koko-eating-bananas
[Python3] Binary Search Simple and Logic Explained
Rainyforest
1
181
koko eating bananas
875
0.521
Medium
14,217
https://leetcode.com/problems/koko-eating-bananas/discuss/2826568/Python%3A-Optimal-and-Clean-with-explanation-O(nlog(max(piles)))-time-and-O(1)-space
class Solution: # Hint: try binary searching over the solution space. Given a fixed speed k, it is easy to check if Koko can eat all the bananas within h hours. If it works for k, we recurse by setting right = k. Otherwise, we recurse by setting left = k+1. # O(nlog(max(piles))) time : O(1) space def minEatingSpeed(self, piles: List[int], h: int) -> int: def check(mid): return sum(ceil(p / mid) for p in piles) <= h left, right = 1, max(piles) while left < right: mid = left + (right-left)//2 if check(mid): right = mid else: left = mid + 1 return left
koko-eating-bananas
Python: Optimal and Clean with explanation - O(nlog(max(piles))) time and O(1) space
topswe
0
4
koko eating bananas
875
0.521
Medium
14,218
https://leetcode.com/problems/koko-eating-bananas/discuss/2794593/Python-binary-search
class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: l, r = 1, max(piles) k = max(piles) while l <= r: mid = (l + r) // 2 hours = 0 for p in piles: hours += math.ceil(p / mid) if hours <= h: r = mid-1 k = min(k, mid) else: l = mid + 1 return k
koko-eating-bananas
Python binary search
zananpech9
0
3
koko eating bananas
875
0.521
Medium
14,219
https://leetcode.com/problems/koko-eating-bananas/discuss/2747725/Python3-Binary-Search
class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: if h == len(piles): return max(piles) l, r = 1, max(piles) res = r while l < r: k = (l+r)//2 hours = sum([ceil(pile/k) for pile in piles]) if hours <= h: res = min(res, k) r = k else: l = k+1 return res
koko-eating-bananas
Python3 Binary Search
jonathanbrophy47
0
1
koko eating bananas
875
0.521
Medium
14,220
https://leetcode.com/problems/koko-eating-bananas/discuss/2695269/python3or-easy-orsame-as-Minimum-Limit-of-Balls-in-a-Bag
class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: def check(nums,m,hr): for i in nums: if i//m == 0: hr-=1 else: hr-=(i//m)+1 if i%m == 0: hr+=1 return hr>=0 ans = 0 s = 1 e = max(piles) while s<=e: m = s+(e-s)//2 if check(piles,m,h): ans = m e = m-1 else: s = m+1 return ans
koko-eating-bananas
python3| easy |same as Minimum Limit of Balls in a Bag
rohannayar8
0
4
koko eating bananas
875
0.521
Medium
14,221
https://leetcode.com/problems/koko-eating-bananas/discuss/2599249/Python-Binary-Search-Solution
class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: # instead of doing brute force, when we find a solution we will look for a smaller k if possible # time complexity: O(log(max(p)) * p) l,r = 1,max(piles) res = r while l <= r: mid = (l + r) // 2 count = 0 for p in piles: count += math.ceil(p / mid) if count <= h: res = min(res,mid) r = mid - 1 else: l = mid + 1 return res
koko-eating-bananas
Python Binary Search Solution
al5861
0
24
koko eating bananas
875
0.521
Medium
14,222
https://leetcode.com/problems/koko-eating-bananas/discuss/2181981/Python-99.8-solution.-Superfast
class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: def can_eat(speed): return sum((pile - 1) // speed + 1 for pile in piles) <= h nPiles = len(piles) sumBanana = sum(piles) left = math.ceil(sumBanana/h) right = math.ceil((sumBanana - (nPiles - 1))/(h-(nPiles-1))) + 1 while left < right: mid = left + (right - left) // 2 if can_eat(mid): right = mid else: left = mid + 1 return left
koko-eating-bananas
Python 99.8% solution. Superfast
arnavjaiswal149
0
20
koko eating bananas
875
0.521
Medium
14,223
https://leetcode.com/problems/koko-eating-bananas/discuss/2090460/Python-or-Binary-Search-Simple-Solution
class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: l,r = 1, max(piles) res = r while l <= r: k = (l+r) // 2 hours = 0 for p in piles: hours += math.ceil(p/k) if hours <= h: res = min(res,k) r = k - 1 else: l = k + 1 return res
koko-eating-bananas
Python | Binary Search Simple Solution
__Asrar
0
62
koko eating bananas
875
0.521
Medium
14,224
https://leetcode.com/problems/koko-eating-bananas/discuss/2012336/Python-3-Interview-Answer-w-DETAILED-Comments
class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: left, right = 1, max(piles) while left < right: # 1. left = 1, right = 11 | 1 + 11 = 12 | 12 / 2 = 6 | mid = 6 # 2. left = 1, right = 6 | 1 + 6 = 7 | 7 / 2 = 3 | mid = 3 # 3. left = 4, right = 6 | 4 + 6 = 10 | 10 / 2 = 5 | mid = 5 # 4. left = 4, right = 5 | 4 + 5 = 9 | 9 / 2 = 4 | mid = 4 mid = (left + right) // 2 # ceil takes a float number then return it to the next int() # e.g math.ceil(14.01 is 15) | ceil(23.30 is 24) # 1. ceil(3 / 6) = 1 | ceil(6 / 6 = 1) | ceil(7 / 6 = 2) | ceil(11 / 6 = 2) | time = 6 # 2. ceil(3 / 3) = 1 | ceil(6 / 3) = 2 | ceil(7 / 3) = 3 | ceil(11 / 3) = 4 | time = 10 # 3. ceil(3 / 5) = 1 | ceil(6 / 5) = 2 | ceil(7 / 5) = 2 | ceil(11 / 5) = 3 | time = 8 # 4. ceil(3 / 4) = 1 | ceil(6 / 4) = 2 | ceil (7 / 4) = 2 | ceil(11 / 4) = 3 | time = 8 time = sum(math.ceil(i / mid) for i in piles) # 2. 10 is greater than 8(h), so left is now mid(3) + 1 = 4 if time > h: left = mid + 1 # 1. 6 is less than h so, right is now the mid, which is 6 # 3. 8 is not greater than 8(h) so right is now 5 # 4. 8 is not greater than 8(h) again, so right is now 4 else: right = mid # 4. left is 4 and right is 4, so the loop will stop | return left -- which is 4 return left
koko-eating-bananas
[Python 3] Interview Answer w/ DETAILED Comments
Cut
0
57
koko eating bananas
875
0.521
Medium
14,225
https://leetcode.com/problems/koko-eating-bananas/discuss/1932602/6-Lines-Python-Solution-oror-97-Faster-oror-Memory-less-than-80
class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: lo=1 ; hi=max(piles) while lo<hi: mid=(lo+hi)//2 if sum(ceil(pile/mid) for pile in piles)<=h: hi=mid else: lo=mid+1 return hi
koko-eating-bananas
6-Lines Python Solution || 97% Faster || Memory less than 80%
Taha-C
0
35
koko eating bananas
875
0.521
Medium
14,226
https://leetcode.com/problems/koko-eating-bananas/discuss/1914619/Python-Easy-reverse-engineering
class Solution: def minEatingSpeed(self, h: List[int], l: int) -> int: def helper(x): count = 0 for i in range(len(h)): count+=((h[i]-1)//x)+1 # print(((h[i]-1)//x)+1) return count<=l low = 1 heigh = max(h) while low<heigh: mid = (low+heigh)//2 if helper(mid): heigh = mid else: low = mid+1 return low
koko-eating-bananas
Python Easy reverse engineering
Brillianttyagi
0
17
koko eating bananas
875
0.521
Medium
14,227
https://leetcode.com/problems/koko-eating-bananas/discuss/1704378/Python-3-or-O(n-logn)-or-Binary-Search
class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: def OK(key): ans = 0 for pile in piles: ans += pile // key + (pile % key > 0) return ans <= h start, end = 1, 10 ** 9 while start < end: mid = start + end >> 1 if OK(mid): end = mid else: start = mid + 1 return start
koko-eating-bananas
[Python 3] | O(n logn) | Binary Search
BrijGwala
0
37
koko eating bananas
875
0.521
Medium
14,228
https://leetcode.com/problems/koko-eating-bananas/discuss/1704335/python3-and-golang-binary-search-easy-to-understand
class Solution: from math import ceil def minEatingSpeed(self, piles: List[int], h: int) -> int: if len(piles) == h: return max(piles) piles.sort() result = 1 # final result start, end = 1, piles[-1] # the `result` must be greater than or equal to the `start` and less than or equal to the `end` while start <= end: mid = (start + end) // 2 # binary-search min_h, max_h = self.get_h(piles, mid) if min_h <= h <= max_h: result = mid end = mid - 1 # keep looping elif min_h < h: end = mid - 1 elif min_h > h: start = mid + 1 else: break return result def get_h(self, piles: List[int], speed: int): return sum(map(lambda x: ceil(x/speed), piles)), sum(piles)-speed+1
koko-eating-bananas
python3 & golang binary-search, easy to understand
yangfan9702
0
33
koko eating bananas
875
0.521
Medium
14,229
https://leetcode.com/problems/koko-eating-bananas/discuss/1704121/Python-Simple-Solution-Using-Binary-Search-!!-Clear-Code
class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: def FindKValue(mid,piles,h): length = len(piles) total = 0 for i in range(length): div = piles[i] // mid rem = piles[i] % mid if rem==0: total = total + div else: total = total + div + 1 if total<=h: return True else: return False left = 1 right = (10**9)+1 while left<right: mid= (left+right)//2 if FindKValue(mid,piles,h)==True: right=mid else: left=mid+1 return left
koko-eating-bananas
[ Python ] Simple Solution Using Binary Search !! Clear Code
ASHOK_KUMAR_MEGHVANSHI
0
40
koko eating bananas
875
0.521
Medium
14,230
https://leetcode.com/problems/koko-eating-bananas/discuss/1282180/Python-Almost-perfect-space-and-time
class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: def check(mid): time = 0 for x in range(len(piles)): time += -(-piles[x] // mid) if time > h: return False if time > h: return False return True left, right = 1, (sum(piles) // h) * 2 while left < right: mid = left + (right - left) // 2 if check(mid): if mid < 2: return 1 right = mid else: left = mid + 1 return left
koko-eating-bananas
[Python] Almost perfect space and time
Fizzybepis
0
114
koko eating bananas
875
0.521
Medium
14,231
https://leetcode.com/problems/koko-eating-bananas/discuss/1273172/python-or-binary-search
class Solution: def minEatingSpeed(self, piles: List[int], hour: int) -> int: l=1 h=max(piles) def fun(speed): ans=0 for i in piles: ans+=ceil(i/speed) #print(ans) if ans>hour: return False return True ans=h while(l<=h): mid=(l+h)//2 if fun(mid): ans=min(ans,mid) h=mid-1 else: l=mid+1 return ans
koko-eating-bananas
python | binary search
heisenbarg
0
68
koko eating bananas
875
0.521
Medium
14,232
https://leetcode.com/problems/middle-of-the-linked-list/discuss/526372/PythonJSJavaGoC%2B%2B-O(n)-by-two-pointers-90%2B-w-Diagram
class Solution: def middleNode(self, head: ListNode) -> ListNode: slow, fast = head, head while fast: fast = fast.next if fast: fast = fast.next else: # fast has reached the end of linked list # slow is on the middle point now break slow = slow.next return slow
middle-of-the-linked-list
Python/JS/Java/Go/C++ O(n) by two-pointers 90%+ [w/ Diagram]
brianchiang_tw
45
2,800
middle of the linked list
876
0.739
Easy
14,233
https://leetcode.com/problems/middle-of-the-linked-list/discuss/2688781/Python-2-Easy-Way-To-Find-Middle-of-the-Linked-List-or-93-Faster-or-Fast-and-Simple-Solution
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: count = 0 ** tmp = head while tmp: count+=1 tmp = tmp.next middle = count//2 l = 0 while l < middle: head = head.next l+=1 return head
middle-of-the-linked-list
✔️ Python 2 Easy Way To Find Middle of the Linked List | 93% Faster | Fast and Simple Solution
pniraj657
16
1,500
middle of the linked list
876
0.739
Easy
14,234
https://leetcode.com/problems/middle-of-the-linked-list/discuss/2688781/Python-2-Easy-Way-To-Find-Middle-of-the-Linked-List-or-93-Faster-or-Fast-and-Simple-Solution
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow
middle-of-the-linked-list
✔️ Python 2 Easy Way To Find Middle of the Linked List | 93% Faster | Fast and Simple Solution
pniraj657
16
1,500
middle of the linked list
876
0.739
Easy
14,235
https://leetcode.com/problems/middle-of-the-linked-list/discuss/2240481/Python-Floyd's-Tortoise-and-Hare-Algorithm-Time-O(N)-or-Space-O(1)
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: slow = head fast = head while fast and fast.next: slow = slow.next # Move by one node ahead fast = fast.next.next # Move by two nodes ahead return slow
middle-of-the-linked-list
[Python] Floyd's Tortoise & Hare Algorithm - Time O(N) | Space O(1)
Symbolistic
11
318
middle of the linked list
876
0.739
Easy
14,236
https://leetcode.com/problems/middle-of-the-linked-list/discuss/2216680/Python-oror-2-pointer-oror-explanation-oror-analysis
class Solution: def middleNode(self, head: ListNode) -> ListNode: fast=slow=head while(fast and fast.next): fast=fast.next.next slow=slow.next return slow
middle-of-the-linked-list
Python || 2-pointer || explanation || analysis
palashbajpai214
5
96
middle of the linked list
876
0.739
Easy
14,237
https://leetcode.com/problems/middle-of-the-linked-list/discuss/1856260/2-Python-Solutions
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: ans=[] while head: ans.append(head) ; head=head.next return ans[len(ans)//2]
middle-of-the-linked-list
2 Python Solutions
Taha-C
4
134
middle of the linked list
876
0.739
Easy
14,238
https://leetcode.com/problems/middle-of-the-linked-list/discuss/1856260/2-Python-Solutions
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: slow=fast=head while fast and fast.next: slow=slow.next ; fast=fast.next.next return slow
middle-of-the-linked-list
2 Python Solutions
Taha-C
4
134
middle of the linked list
876
0.739
Easy
14,239
https://leetcode.com/problems/middle-of-the-linked-list/discuss/1561140/Python-easy-fast-solution-with-explanation-(one-pass)-Memory-Usage-less-than-96.79
class Solution(object): def middleNode(self, head): slow = head fast = head while fast != None and fast.next != None: #if fast.next is not None yet, then fast.next.next would only be none the worst case scinario, it wouldn't throw it doesn't exist error slow = slow.next fast = fast.next.next return slow
middle-of-the-linked-list
Python easy fast solution with explanation (one pass) Memory Usage less than 96.79%
Abeni
4
234
middle of the linked list
876
0.739
Easy
14,240
https://leetcode.com/problems/middle-of-the-linked-list/discuss/1767217/Python-3-(20ms)-or-Slow-and-Fast-Pointers-or-3-Lines-One-Pass-Solution
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: s=head while head and head.next: s,head=s.next,head.next.next return s
middle-of-the-linked-list
Python 3 (20ms) | Slow and Fast Pointers | 3 Lines One Pass Solution
MrShobhit
2
212
middle of the linked list
876
0.739
Easy
14,241
https://leetcode.com/problems/middle-of-the-linked-list/discuss/1651972/Python3-SLOW-AND-FAST-Explained
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow
middle-of-the-linked-list
✔️ [Python3] SLOW AND FAST, Explained
artod
2
96
middle of the linked list
876
0.739
Easy
14,242
https://leetcode.com/problems/middle-of-the-linked-list/discuss/2088422/Python-solution-using-slow-and-fast-pointers
class Solution(object): def middleNode(self, head): fast_pointer=slow_pointer=head #fastP moves two steps at a time faster and slowP moves one step at a time # 1 2 3 4 5 # f/s --> initially # s f --> first move # s f -->second move #return s {return slow pointer which return 3,4,5 for above input} while fast_pointer and fast_pointer.next is not None: fast_pointer=fast_pointer.next.next slow_pointer=slow_pointer.next return slow_pointer
middle-of-the-linked-list
Python solution using slow and fast pointers
varudinesh225
1
111
middle of the linked list
876
0.739
Easy
14,243
https://leetcode.com/problems/middle-of-the-linked-list/discuss/2010166/Python-Solution-greater-99
class Solution(object): def middleNode(self, head): res = [] oldHead = head counter = 0 secondCount = 0 #first find the middle while(head != None): head = head.next counter += 1 # return the head once you reached the middle while(oldHead != None): if(secondCount>=(counter//2)): return oldHead oldHead = oldHead.next secondCount += 1
middle-of-the-linked-list
Python Solution > 99%
felixplease
1
147
middle of the linked list
876
0.739
Easy
14,244
https://leetcode.com/problems/middle-of-the-linked-list/discuss/1881754/Python-3-or-two-solution-(1)-1-and-half-pass-(2)-one-pass
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: ct=0 curr=head while curr: curr=curr.next ct+=1 ct=ct//2 while ct: head=head.next ct-=1 return head
middle-of-the-linked-list
Python 3 | two solution (1) 1 and half pass (2) one pass
Anilchouhan181
1
85
middle of the linked list
876
0.739
Easy
14,245
https://leetcode.com/problems/middle-of-the-linked-list/discuss/1881754/Python-3-or-two-solution-(1)-1-and-half-pass-(2)-one-pass
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: single,double=head,head while double and double.next: single=single.next double=double.next.next return single
middle-of-the-linked-list
Python 3 | two solution (1) 1 and half pass (2) one pass
Anilchouhan181
1
85
middle of the linked list
876
0.739
Easy
14,246
https://leetcode.com/problems/middle-of-the-linked-list/discuss/1714884/Python-Simple-approach-(calculating-mid-)-O(n)-Time
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: """Approach: First count total no of nodes, then decide the mid node. Then move head till it reaches mid node.""" curr = head count = 1 headPosition = 1 mid = 0 """Counting nodes""" while curr.next: curr = curr.next count+=1 """Finding mid node""" if count % 2 == 0: mid = (count/2) + 1 else: mid = (count+1)/2 """moving head till mid""" while headPosition != mid: head = head.next headPosition += 1 return head
middle-of-the-linked-list
Python Simple approach (calculating mid ), O(n) Time
abhisheksharma5023
1
64
middle of the linked list
876
0.739
Easy
14,247
https://leetcode.com/problems/middle-of-the-linked-list/discuss/1602927/3-methods-explained-oror-O(n)-Faster-than-96
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: mid = head count = 0 while(head!=None): if count&amp;1: mid = mid.next count+=1 head = head.next return mid
middle-of-the-linked-list
3 methods - explained || O(n) Faster than 96%
ana_2kacer
1
164
middle of the linked list
876
0.739
Easy
14,248
https://leetcode.com/problems/middle-of-the-linked-list/discuss/1602927/3-methods-explained-oror-O(n)-Faster-than-96
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow
middle-of-the-linked-list
3 methods - explained || O(n) Faster than 96%
ana_2kacer
1
164
middle of the linked list
876
0.739
Easy
14,249
https://leetcode.com/problems/middle-of-the-linked-list/discuss/1602927/3-methods-explained-oror-O(n)-Faster-than-96
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: ptr = head n = 0 while(ptr!=None): n+=1 ptr = ptr.next ptr = head # print(n) i = 0 while i!=n//2 and ptr!=None: # print(i) # print(ptr) if i==n//2: return ptr ptr = ptr.next i+=1 return ptr
middle-of-the-linked-list
3 methods - explained || O(n) Faster than 96%
ana_2kacer
1
164
middle of the linked list
876
0.739
Easy
14,250
https://leetcode.com/problems/middle-of-the-linked-list/discuss/1586696/python3-two-pointers-soln-96-faster
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: p = head pf = head while pf and pf.next: pf = pf.next.next p = p.next return p
middle-of-the-linked-list
python3 two pointers soln 96% faster
msugamsingh
1
152
middle of the linked list
876
0.739
Easy
14,251
https://leetcode.com/problems/middle-of-the-linked-list/discuss/1483447/Python3-2-pointers
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: slow = fast = head while fast and fast.next: fast = fast.next.next slow = slow.next return slow
middle-of-the-linked-list
[Python3] 2 pointers
ye15
1
36
middle of the linked list
876
0.739
Easy
14,252
https://leetcode.com/problems/middle-of-the-linked-list/discuss/1386950/Python3-Fast-Pointer-Slow-Pointer-99-90
class Solution: def middleNode(self, head: ListNode) -> ListNode: slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow
middle-of-the-linked-list
[Python3] Fast Pointer Slow Pointer 99%, 90%
whitehatbuds
1
139
middle of the linked list
876
0.739
Easy
14,253
https://leetcode.com/problems/middle-of-the-linked-list/discuss/1340306/Python3-faster-than-99.16
class Solution: def middleNode(self, head: ListNode) -> ListNode: fast=head slow=head length=0 curr=head while(curr): curr=curr.next length+=1 while(fast.next and fast.next.next): fast=fast.next.next slow=slow.next return slow if length%2!=0 else slow.next
middle-of-the-linked-list
Python3 faster than 99.16%
samarthnehe
1
118
middle of the linked list
876
0.739
Easy
14,254
https://leetcode.com/problems/middle-of-the-linked-list/discuss/468329/Python-3-(four-lines)-(beats-~100)
class Solution: def middleNode(self, H: ListNode) -> ListNode: N, L = H, 0 while N != None: L, N = L + 1, N.next for i in range(L//2): H = H.next return H - Junaid Mansuri - Chicago, IL
middle-of-the-linked-list
Python 3 (four lines) (beats ~100%)
junaidmansuri
1
353
middle of the linked list
876
0.739
Easy
14,255
https://leetcode.com/problems/middle-of-the-linked-list/discuss/461860/Tortoise-and-Hare-Algorithm-in-Python.
class Solution: def middleNode(self, head: ListNode) -> ListNode: temp=head temp1=head while temp1!=None and temp1.next!=None: temp=temp.next temp1=temp1.next.next return temp
middle-of-the-linked-list
Tortoise and Hare Algorithm in Python.
atriraha
1
49
middle of the linked list
876
0.739
Easy
14,256
https://leetcode.com/problems/middle-of-the-linked-list/discuss/2828001/Skipping-The-Best
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: first, second = head, head.next while second: first = first.next second = second.next.next if second.next else None return first
middle-of-the-linked-list
Skipping, The Best
Triquetra
0
1
middle of the linked list
876
0.739
Easy
14,257
https://leetcode.com/problems/middle-of-the-linked-list/discuss/2817857/Easy
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: counter = 0 temp = head while temp is not None: counter += 1 temp = temp.next index = math.ceil(counter / 2) counter = 1 if counter % 2 != 0 else 0 while head is not None: if counter == index: return head counter += 1 head = head.next
middle-of-the-linked-list
Easy
pkozhem
0
4
middle of the linked list
876
0.739
Easy
14,258
https://leetcode.com/problems/middle-of-the-linked-list/discuss/2755935/876.-Middle-of-the-Linked-List-or-Python-Solution
class Solution(object): def middleNode(self, head): temp = head count = 0 while temp: temp = temp.next count+=1 mid = (count // 2) temp = head for i in range(mid): temp = temp.next return temp ``` Please upvote if helpful!
middle-of-the-linked-list
876. Middle of the Linked List | Python Solution
ygygupta0
0
5
middle of the linked list
876
0.739
Easy
14,259
https://leetcode.com/problems/middle-of-the-linked-list/discuss/2730634/O(n2)-and-O(n)-two-python-solutions-(faster-than-99.94)
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: mid = l1 = head while l1: if l1.next: if l1.next.next: mid = mid.next l1 = l1.next.next continue return mid.next else: return mid
middle-of-the-linked-list
O(n/2) and O(n) two python solutions (faster than 99.94%)
naseemh119
0
7
middle of the linked list
876
0.739
Easy
14,260
https://leetcode.com/problems/middle-of-the-linked-list/discuss/2730634/O(n2)-and-O(n)-two-python-solutions-(faster-than-99.94)
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: mid = l1 = head c = 1 m = 1 while l1: t = m m = int(c/2) + 1 if t != m: mid = mid.next c += 1 l1 = l1.next return mid
middle-of-the-linked-list
O(n/2) and O(n) two python solutions (faster than 99.94%)
naseemh119
0
7
middle of the linked list
876
0.739
Easy
14,261
https://leetcode.com/problems/middle-of-the-linked-list/discuss/2724160/Easy-Python3-Solution
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: pos=0 curr=head while(curr!=None): pos+=1 curr=curr.next curr=head for i in range(pos//2): curr=curr.next return curr
middle-of-the-linked-list
Easy Python3 Solution
ankitr8055
0
5
middle of the linked list
876
0.739
Easy
14,262
https://leetcode.com/problems/stone-game/discuss/643412/Python-O(-n2-)-by-top-down-DP-w-Comment
class Solution: def stoneGame(self, piles: List[int]) -> bool: # Alex always win finally, no matter which step he takes first. return True
stone-game
Python O( n^2 ) by top-down DP [w/ Comment]
brianchiang_tw
4
642
stone game
877
0.697
Medium
14,263
https://leetcode.com/problems/stone-game/discuss/2765540/One-word-solution-oror-return-True
class Solution: def stoneGame(self, piles: List[int]) -> bool: return True
stone-game
One word solution || return True
Sneh713
1
165
stone game
877
0.697
Medium
14,264
https://leetcode.com/problems/stone-game/discuss/1709156/O(1)-solution-for-CC%2B%2BCJavaJavaScriptPythonPython3Ruby
class Solution(object): def stoneGame(self, piles): """ :type piles: List[int] :rtype: bool """ return True
stone-game
✔O(1) solution for C/C++/C#/Java/JavaScript/Python/Python3/Ruby
milochen
1
376
stone game
877
0.697
Medium
14,265
https://leetcode.com/problems/stone-game/discuss/1709156/O(1)-solution-for-CC%2B%2BCJavaJavaScriptPythonPython3Ruby
class Solution: def stoneGame(self, piles: List[int]) -> bool: return True
stone-game
✔O(1) solution for C/C++/C#/Java/JavaScript/Python/Python3/Ruby
milochen
1
376
stone game
877
0.697
Medium
14,266
https://leetcode.com/problems/stone-game/discuss/876027/Python-One-line-oror-Always-True
class Solution: def stoneGame(self, piles: List[int]) -> bool: return True
stone-game
Python One line || Always True
airksh
1
59
stone game
877
0.697
Medium
14,267
https://leetcode.com/problems/stone-game/discuss/520725/Python3-dp-O(N2)
class Solution: def stoneGame(self, piles: List[int]) -> bool: return True
stone-game
[Python3] dp O(N^2)
ye15
1
169
stone game
877
0.697
Medium
14,268
https://leetcode.com/problems/stone-game/discuss/2814843/Optimal-and-Clean-with-explanation-O(1)-time-and-O(1)-space
class Solution: # sum(piles) is odd. => NO TIES... # len(piles) is even => each takes len(piles)//2 piles # since Alice goes first, she will always pick the greater size piles and WIN # O(1) time : O(1) space def stoneGame(self, piles: List[int]) -> bool: return True
stone-game
Optimal and Clean with explanation - O(1) time and O(1) space
topswe
0
2
stone game
877
0.697
Medium
14,269
https://leetcode.com/problems/stone-game/discuss/2811211/Simple-Logic-in-python
class Solution: def stoneGame(self, piles: List[int]) -> bool: a = [] b = [] c = len(piles) for i in range(c): a.append(max(piles)) piles.remove(max(piles)) if sum(a) > sum(b): return 1 else: return 0
stone-game
Simple Logic in python
Himakar_C
0
1
stone game
877
0.697
Medium
14,270
https://leetcode.com/problems/stone-game/discuss/2779791/Python-Easy-Solution-or-Faster-Than-85-or-Easy-To-Understand
class Solution: def stoneGame(self, piles: List[int]) -> bool: if len(piles)%2 == 0: return True else: return False
stone-game
Python Easy Solution | Faster Than 85% | Easy To Understand
beingdillig
0
3
stone game
877
0.697
Medium
14,271
https://leetcode.com/problems/stone-game/discuss/2677380/East-python-solution-with-DP-and-memo
class Solution: def stoneGame(self, piles: List[int]) -> bool: n = len(piles) memo = [[0] * n for i in range(n)] def dp(i, j): if (i > j): return 0 if (memo[i][j] != 0): return memo[i][j] player_turn = (n - (j - i)) % 2 if (player_turn == 1): # increasing player1's score when player1 picks a max pile memo[i][j] = max(piles[i] + dp(i+1, j), piles[j] + dp(i, j-1)) else: # decreasing player1's score when player2 picks a pile and player2 is assumed to pick the larger pile leading to a min score for player1 memo[i][j] = min(-piles[i] + dp(i+1, j), -piles[j] + dp(i, j-1)) return memo[i][j] return dp(0, n-1) > 0
stone-game
East python solution with DP and memo
leqinancy
0
10
stone game
877
0.697
Medium
14,272
https://leetcode.com/problems/stone-game/discuss/2653032/Easy-Understandable-Python-Solution-Beats-99-or-O(N)
class Solution: def stoneGame(self, piles: List[int]) -> bool: alicePile = 0 bobPile = 0 length = len(piles) for i in range(length): currentValue = 0 if piles[0] > piles[-1]: currentValue = piles.pop(0) else: currentValue = piles.pop(-1) if i%1 ==0: alicePile+= currentValue else: bobPile+=currentValue return alicePile>bobPile
stone-game
Easy Understandable Python Solution Beats 99% | O(N)
perabjoth
0
5
stone game
877
0.697
Medium
14,273
https://leetcode.com/problems/stone-game/discuss/2562806/python3or-easy
class Solution: def stoneGame(self, piles: List[int]) -> bool: a =0 b = 0 while piles: if piles[0]>=piles[-1]: a+=piles.pop(0) else: a+=piles.pop() if piles[0]>=piles[-1]: a+=piles.pop(0) else: a+=piles.pop() return a>b
stone-game
python3| easy
rohannayar8
0
27
stone game
877
0.697
Medium
14,274
https://leetcode.com/problems/stone-game/discuss/1544957/VERY-SIMPLE-AND-EASY-SOLN-(faster-than-94)
class Solution: def stoneGame(self, piles: List[int]) -> bool: Alice = Bob = idx = 0 piles.sort() piles.reverse() while idx != len(piles): Alice += piles[idx] idx += 1 Bob += piles[idx] idx += 1 return True if Alice>Bob else False
stone-game
VERY SIMPLE AND EASY SOLN (faster than 94%)
anandanshul001
0
204
stone game
877
0.697
Medium
14,275
https://leetcode.com/problems/stone-game/discuss/1388120/Simple-Python-Solution
class Solution: def stoneGame(self, piles: List[int]) -> bool: alexs_turn = True alex_score = lee_score = 0 while piles: if alexs_turn: if piles[0] > piles[-1]: alex_score += piles.pop(0) else: alex_score += piles.pop(-1) else: if piles[0] > piles[-1]: lee_score += piles.pop(0) else: lee_score += piles.pop(-1) alexs_turn = ~alexs_turn return alex_score > lee_score
stone-game
Simple Python Solution
anandudit
0
81
stone game
877
0.697
Medium
14,276
https://leetcode.com/problems/stone-game/discuss/1386037/Python-2-pointer-approach
class Solution: def stoneGame(self, piles: List[int]) -> bool: alexsTurn = True alex = lee = left = 0 right = len(piles) - 1 while left <= right: if piles[left] > piles[right]: if alexsTurn: alex += piles[left] else: lee += piles[left] left += 1 else: if alexsTurn: alex += piles[right] else: lee += piles[right] right -= 1 alexsTurn = ~alexsTurn return alex > lee
stone-game
[Python] 2 pointer approach
genefever
0
75
stone game
877
0.697
Medium
14,277
https://leetcode.com/problems/stone-game/discuss/1385971/Python-Solution-Faster-than-96-with-Sorting.
class Solution(object): def stoneGame(self, piles): s= [] piles.sort(reverse=True) for i in range(len(piles)): s.append(i) if sum(piles)>sum(s): return True
stone-game
[Python] Solution; Faster than 96%, with Sorting.
balajimj2824
0
89
stone game
877
0.697
Medium
14,278
https://leetcode.com/problems/stone-game/discuss/1331561/Simple-DFS-DP-returning-difference-with-which-current-player-wins-(caller-of-function)
class Solution: def stoneGame(self, piles: List[int]) -> bool: @functools.cache def doIWin(l,r): if l > r: return 0 left = piles[l] - doIWin(l+1,r) # `-` because my opponent! right= piles[r] - doIWin(l,r-1) return max(left, right) return (doIWin(0,len(piles)-1) + sum(piles) )//2
stone-game
Simple DFS DP, returning difference with which current player wins (caller of function)
yozaam
0
151
stone game
877
0.697
Medium
14,279
https://leetcode.com/problems/nth-magical-number/discuss/1545825/Python3-binary-search
class Solution: def nthMagicalNumber(self, n: int, a: int, b: int) -> int: # inclusion-exclusion principle ab = lcm(a,b) lo, hi = 0, n*min(a, b) while lo < hi: mid = lo + hi >> 1 if mid//a + mid//b - mid//ab < n: lo = mid + 1 else: hi = mid return lo % 1_000_000_007
nth-magical-number
[Python3] binary search
ye15
1
106
nth magical number
878
0.357
Hard
14,280
https://leetcode.com/problems/nth-magical-number/discuss/1049740/A-pattern-based-solution-using-lcm-in-Python3
class Solution: def nthMagicalNumber(self, n: int, a: int, b: int) -> int: def gcd(x,y): if(x==0): return y return gcd(y%x,x) lcm=(a*b)//gcd(a,b) s=set() x=a while(x<=lcm): s.add(x) x+=a x=b while(x<=lcm): s.add(x) x+=b le=0 l=[] for i in s: l.append(i) le+=1 l.sort() #sort all multiples of a and b which are less than their lcm. #below approach is based on pattern observation. Try to take some example and observer the pattern(e.g n=4,8,9,16,18,41 #a=3, b=7) r=n%le q=n//(le+1) if(q==0): return l[n-1] else: q=n//le res= ((q*l[-1])%1000000007) if(r>0): res=(res+ l[r-1]) %1000000007 return res
nth-magical-number
A pattern based solution using lcm in Python3
_Rehan12
0
75
nth magical number
878
0.357
Hard
14,281
https://leetcode.com/problems/profitable-schemes/discuss/2661178/Python3-DP
class Solution: def profitableSchemes(self, n: int, minProfit: int, group: List[int], profit: List[int]) -> int: # A[i][j][k] = # schemes using subset of first i crimes, using <= j people, with total profit >= k A = [[[0 for k in range(minProfit + 1)] for j in range(n + 1)] for i in range(len(profit) + 1)] # if using first 0 crimes, only one way, and that if minProfit <= 0 for j in range(n + 1): A[0][j][0] = 1 for i in range(1, len(profit) + 1): for j in range(n + 1): for k in range(minProfit + 1): # we are here calculating A[j][j][k] # two cases, either we use i'th crime or not. # but if i'th crime requires more than j people, we con't use it if group[i-1] > j: A[i][j][k] = A[i-1][j][k] else: # if i'th crime gets profit greater than k, then we have no restriction # on the rest of the groups if profit[i-1] > k: A[i][j][k] = (A[i-1][j][k] + A[i-1][j-group[i-1]][0]) % (10**9 + 7) else: A[i][j][k] = (A[i-1][j][k] + A[i-1][j-group[i-1]][k-profit[i-1]]) % (10**9 + 7) return A[len(profit)][n][minProfit]
profitable-schemes
Python3 DP
jbradleyglenn
0
11
profitable schemes
879
0.404
Hard
14,282
https://leetcode.com/problems/profitable-schemes/discuss/1516885/Python3-dp
class Solution: def profitableSchemes(self, n: int, minProfit: int, group: List[int], profit: List[int]) -> int: m = len(group) dp = [[[0] * (minProfit+1) for _ in range(n+1)] for _ in range(m+1)] for j in range(n+1): dp[m][j][0] = 1 for i in range(m-1, -1, -1): for j in range(n+1): for k in range(minProfit+1): dp[i][j][k] = dp[i+1][j][k] if group[i] <= j: dp[i][j][k] += dp[i+1][j-group[i]][max(0, k-profit[i])] dp[i][j][k] %= 1_000_000_007 return dp[0][n][minProfit]
profitable-schemes
[Python3] dp
ye15
0
73
profitable schemes
879
0.404
Hard
14,283
https://leetcode.com/problems/profitable-schemes/discuss/1516885/Python3-dp
class Solution: def profitableSchemes(self, n: int, minProfit: int, group: List[int], profit: List[int]) -> int: dp = [[0]*(1 + n) for _ in range(1 + minProfit)] dp[0][0] = 1 for p, g in zip(profit, group): for i in range(minProfit, -1, -1): for j in range(n - g, -1, -1): dp[min(i+p, minProfit)][j + g] += dp[i][j] return sum(dp[minProfit]) % 1_000_000_007
profitable-schemes
[Python3] dp
ye15
0
73
profitable schemes
879
0.404
Hard
14,284
https://leetcode.com/problems/profitable-schemes/discuss/1516885/Python3-dp
class Solution: def profitableSchemes(self, n: int, minProfit: int, group: List[int], profit: List[int]) -> int: MOD = 1_000_000_007 @cache def fn(i, n, p): """Return count at i with n people remaining and p profit to make.""" if n < 0: return 0 if i == len(group): return p <= 0 return (fn(i+1, n, p) + fn(i+1, n-group[i], p-profit[i])) % MOD return fn(0, n, minProfit)
profitable-schemes
[Python3] dp
ye15
0
73
profitable schemes
879
0.404
Hard
14,285
https://leetcode.com/problems/decoded-string-at-index/discuss/1585059/Python3-Solution-with-using-stack
class Solution: def decodeAtIndex(self, s: str, k: int) -> str: lens = [0] for c in s: if c.isalpha(): lens.append(lens[-1] + 1) else: lens.append(lens[-1] * int(c)) for idx in range(len(s), 0, -1): k %= lens[idx] if k == 0 and s[idx - 1].isalpha(): return s[idx - 1] return
decoded-string-at-index
[Python3] Solution with using stack
maosipov11
2
217
decoded string at index
880
0.283
Medium
14,286
https://leetcode.com/problems/decoded-string-at-index/discuss/980937/Python3-stack-O(N)
class Solution: def decodeAtIndex(self, S: str, K: int) -> str: K -= 1 # 0-indexed stack = [] i = 0 for c in S: if c.isdigit(): i *= int(c) else: stack.append((i, c)) if K <= i: break i += 1 while K != i: if K < i: i, ans = stack.pop() else: K %= i+1 return ans
decoded-string-at-index
[Python3] stack O(N)
ye15
1
162
decoded string at index
880
0.283
Medium
14,287
https://leetcode.com/problems/decoded-string-at-index/discuss/980937/Python3-stack-O(N)
class Solution: def decodeAtIndex(self, S: str, K: int) -> str: k = 0 for i, c in enumerate(S): k = k+1 if c.isalpha() else k*int(c) if K <= k: break for ii in reversed(range(i+1)): if S[ii].isalpha(): if K in (k, 0): return S[ii] k -= 1 else: k /= int(S[ii]) K %= k
decoded-string-at-index
[Python3] stack O(N)
ye15
1
162
decoded string at index
880
0.283
Medium
14,288
https://leetcode.com/problems/decoded-string-at-index/discuss/979627/Beats-89-in-time-time-complexity-O(n)
class Solution: def decodeAtIndex(self, S: str, K: int) -> str: # e.g. S == 'ab2c3d' # ls_len: list of lengths of new patterns [2, 5] (ab, ababc) # ls_total_len: list of lengths of times * new pattern [4, 15] (abab, ababcababcababc) # ls_pattern: list of new additional pattern ['ab', 'c'] ls_len = [] ls_total_len = [] ls_pattern = [] tmp = '' length = 0 # flag for string without integer prev_num = -1 for i in range(len(S)): value = S[i] if i == 0: # first char is letter only tmp = value length = 1 continue if 50 <= ord(value) <= 57: if tmp: # if not more than one integer appearing together ls_pattern.append(tmp) ls_len.append(length) ls_total_len.append(length * int(value)) else: # e.g. S = 'a23', here ls_total_len will change from [2] (aa) to [6] (aaaaaa). # The other two lists unchanged. ls_total_len[-1] = length * int(value) length = length * int(value) tmp = '' prev_num = i else: tmp += value length += 1 # residual is the last part left with no multiplier, e.g. S = 'ab2c3d', then the last 'd' is the residual residual = tmp if prev_num < 0: # if no integer is in S, return the (K - 1)th element. return S[K - 1] if K > ls_total_len[-1]: # if K is within the first pattern return residual[K - ls_total_len[-1] - 1] if K <= ls_total_len[0]: # if K is in the residual ptn = ls_pattern[0] len_ptn = ls_len[0] return ptn[(K - 1) % len_ptn] def bs(k, lb, ub, ls): # binary search of K's location in the two lists: ls_len &amp; ls_total_len if k <= ls[lb]: return lb - 1 if k > ls[ub]: return ub if ub == lb + 1: return lb mid = (lb + ub) // 2 if k == ls[mid]: return mid - 1 elif k < ls[mid]: return bs(k, lb, mid, ls) else: return bs(k, mid + 1, ub, ls) # due to the nature of the two lists, idx1 >= idx2 idx1 = bs(K, 0, len(ls_pattern) - 1, ls_len) idx2 = bs(K, 0, len(ls_pattern) - 1, ls_total_len) while idx1 != idx2 and idx2 != -1: # if idx1 == idx2, (K - 1)th element is in the new additional pattern # if idx2 == -1, (K - 1)th element is in the first pattern K %= ls_len[idx1] if not K: K = ls_len[idx1] idx1 = bs(K, 0, idx1, ls_len) idx2 = bs(K, 0, idx2, ls_total_len) if idx2 == -1: return ls_pattern[0][K % ls_len[0] - 1] if idx1 == idx2: return ls_pattern[idx1 + 1][K - ls_total_len[idx1] - 1]
decoded-string-at-index
Beats 89% in time, time complexity O(n)
leonine9
0
71
decoded string at index
880
0.283
Medium
14,289
https://leetcode.com/problems/boats-to-save-people/discuss/1878155/Explained-Python-2-Pointers-Solution
class Solution: def numRescueBoats(self, people: List[int], limit: int) -> int: people.sort() lo = 0 hi = len(people)-1 boats = 0 while lo <= hi: if people[lo] + people[hi] <= limit: lo += 1 hi -= 1 else: hi -= 1 boats += 1 return boats
boats-to-save-people
⭐Explained Python 2 Pointers Solution
anCoderr
26
3,400
boats to save people
881
0.527
Medium
14,290
https://leetcode.com/problems/boats-to-save-people/discuss/1879381/Python-Easy-Solution
class Solution: def numRescueBoats(self, people: List[int], limit: int) -> int: people.sort() lo, hi, ans = 0, len(people) - 1, 0 while lo <= hi: if people[hi] + people[lo] <= limit: lo += 1 hi -= 1; ans += 1 return ans
boats-to-save-people
✅ Python Easy Solution
dhananjay79
3
147
boats to save people
881
0.527
Medium
14,291
https://leetcode.com/problems/boats-to-save-people/discuss/1015671/Easy-and-Clear-Solution-Python-3
class Solution: def numRescueBoats(self, people: List[int], limit: int) -> int: i,j,res=0,len(people)-1,0 people.sort(reverse=True) while i<j: if people[i]+people[j]<=limit: j-=1 res+=1 i+=1 if i==j: res+=1 return res
boats-to-save-people
Easy & Clear Solution Python 3
moazmar
2
201
boats to save people
881
0.527
Medium
14,292
https://leetcode.com/problems/boats-to-save-people/discuss/1880035/Easy-Python-Solution
class Solution: def numRescueBoats(self, people: List[int], limit: int) -> int: people.sort() res = 0 while(len(people)): res += 1 if(len(people) == 1): break if(people[0] + people[-1] <= limit): people.pop(0) people.pop() return(res)
boats-to-save-people
Easy Python Solution
demonKing_253
1
23
boats to save people
881
0.527
Medium
14,293
https://leetcode.com/problems/boats-to-save-people/discuss/2841802/Two-pointers-solution
class Solution: def numRescueBoats(self, people: List[int], limit: int) -> int: res = 0 people.sort() left = 0 right = len(people) - 1 while left <= right: weight = people[left] + people[right] if weight <= limit: left += 1 right -= 1 else: right -= 1 res += 1 return res
boats-to-save-people
Two pointers solution
khaled_achech
0
1
boats to save people
881
0.527
Medium
14,294
https://leetcode.com/problems/boats-to-save-people/discuss/2795074/Two-pointer-approach-or-Easy-Python-Solution
class Solution: def numRescueBoats(self, people: List[int], limit: int) -> int: people.sort() p1, p2,res = 0, len(people) - 1, 0 while p1 <= p2: if people[p1] + people[p2] <= limit: p1 += 1 res += 1 p2 -= 1 return res
boats-to-save-people
Two pointer approach | Easy Python Solution
mrpranavr
0
1
boats to save people
881
0.527
Medium
14,295
https://leetcode.com/problems/boats-to-save-people/discuss/2749034/two-pointers!
class Solution(object): def numRescueBoats(self, people, limit): people.sort() left, right = 0, len(people) - 1 boats_num = 0 while left <= right: if(left==right): boats_num += 1 break if people[left] + people[right] <= limit: left += 1 right -= 1 boats_num += 1 return boats_num
boats-to-save-people
two pointers!
sanjeevpathak
0
2
boats to save people
881
0.527
Medium
14,296
https://leetcode.com/problems/boats-to-save-people/discuss/2749018/Easy-Solution!!!
class Solution(object): def numRescueBoats(self, people, limit): people.sort() i, j = 0, len(people) - 1 ans = 0 while i <= j: ans += 1 if people[i] + people[j] <= limit: i += 1 j -= 1 return ans
boats-to-save-people
Easy Solution!!!
sanjeevpathak
0
1
boats to save people
881
0.527
Medium
14,297
https://leetcode.com/problems/boats-to-save-people/discuss/2728477/python-working-solution
class Solution: def numRescueBoats(self, people: List[int], limit: int) -> int: people.sort() l = 0 r = len(people)-1 boats = 0 while l<=r: if people[l] + people[r] > limit: boats+=1 r-=1 elif people[l] + people[r] <= limit: boats+=1 l+=1 r-=1 return boats
boats-to-save-people
python working solution
Sayyad-Abdul-Latif
0
2
boats to save people
881
0.527
Medium
14,298
https://leetcode.com/problems/boats-to-save-people/discuss/2714231/Python-3-Solution
class Solution: def numRescueBoats(self, people: List[int], limit: int) -> int: people.sort() l, r = 0, len(people)-1 boats = 0 while l<=r: if people[l] + people[r] <= limit: l += 1 boats += 1 r -= 1 return boats
boats-to-save-people
Python 3 Solution
mati44
0
1
boats to save people
881
0.527
Medium
14,299