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/car-pooling/discuss/2618746/car-pooling-python | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
max_val = 0
for i in range(len(trips)):
max_val = max(max_val, trips[i][2])
diff = [0]*(max_val+2)
for i in range(len(trips)):
diff[trips[i][1]] += trips[i][0]
diff[trips[i][2]] -= trips[i][0]
sum_val = 0
flag = True
for i in range(len(diff)):
sum_val +=diff[i]
if sum_val > capacity:
flag = False
break
return flag | car-pooling | car pooling python | Erika_v | 0 | 13 | car pooling | 1,094 | 0.573 | Medium | 17,400 |
https://leetcode.com/problems/car-pooling/discuss/2617127/Python-Solution | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
trips.sort(key = lambda x: x[1])
n = len(trips)
heap = []
c = capacity
for i in range(n):
trip = trips[i]
passengers = trip[0]
start = trip[1]
end = trip[2]
while len(heap) > 0 and start >= heap[0][0]:
_, seats = heapq.heappop(heap)
c = c + seats
heapq.heappush(heap, ([end, passengers]))
c = c - passengers
if c < 0 or c > capacity:
return False
return True | car-pooling | Python Solution | mansoorafzal | 0 | 15 | car pooling | 1,094 | 0.573 | Medium | 17,401 |
https://leetcode.com/problems/car-pooling/discuss/2612076/Python-or-O(n)-or-prefix-sum | class Solution:
class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
def update(number, start, end):
diff[start] += number
if diff[end + 1] < 1001:
diff[end + 1] -= number
def getResult():
if diff[0] > capacity:
return False
count = diff[0]
for i in range(1, max_trip + 1):
count += diff[i]
if count > capacity:
return False
return True
diff, max_trip = [0 for _ in range(1001)], 0
for trip in trips:
update(trip[0], trip[1], trip[2] - 1)
max_trip = max(max_trip, trip[2] - 1)
return getResult() | car-pooling | Python | O(n) | prefix-sum | MichelleZou | 0 | 24 | car pooling | 1,094 | 0.573 | Medium | 17,402 |
https://leetcode.com/problems/car-pooling/discuss/2107862/Difference-Sum-Simple-Python-Solution | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
# max station size is 1001, diffs[i] represents trips[i][0]-trips[i-1][0]
# res[i] represents the final number of people on the car at i-th station over multiple trips
res, diffs = [0] * 1001, [0] * 1001
for trip in trips:
# loading station index
start = trip[1]
# off-loading station index
end = trip[2]-1
# load trip[0] passengers at station start
diffs[start] += trip[0]
if (end + 1 < 1001):
# offload trip[0] passengers at station end
diffs[end+1] -= trip[0]
# restore final passenger count at each station throughout all trips
res[0] = diffs[0]
if (res[0] > capacity): return False
for i in range(1, 1001):
res[i] = res[i-1] + diffs[i]
# for each station, return False if the number exceeds capacit
if (res[i] > capacity):
return False
return True | car-pooling | Difference Sum Simple Python Solution | leqinancy | 0 | 18 | car pooling | 1,094 | 0.573 | Medium | 17,403 |
https://leetcode.com/problems/car-pooling/discuss/1929569/Python-Priority-Queue | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
trips.sort(key = lambda x : x[1])
curPass = 0
minHeap = []
for i in trips:
numPass, start, end = i
while minHeap and minHeap[0][0] <= start:
curPass -= minHeap[0][1]
heapq.heappop(minHeap)
curPass += numPass
if curPass > capacity:
return False
heapq.heappush(minHeap, [end, numPass])
return True | car-pooling | Python - Priority Queue | dayaniravi123 | 0 | 25 | car pooling | 1,094 | 0.573 | Medium | 17,404 |
https://leetcode.com/problems/car-pooling/discuss/1898184/Python-easy-to-read-and-understand-or-sorting | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
pick, drop = [], []
for trip in trips:
pick.append([trip[0], trip[1]])
drop.append([trip[0], trip[2]])
pick.sort(key=lambda x:x[1])
drop.sort(key=lambda x:x[1])
i, j = 0, 0
n = len(trips)
total = 0
while i < n or j < n:
if total > capacity:
return False
if i < n and pick[i][1] < drop[j][1]:
total += pick[i][0]
i += 1
else:
total -= drop[j][0]
j += 1
return True | car-pooling | Python easy to read and understand | sorting | sanial2001 | 0 | 31 | car pooling | 1,094 | 0.573 | Medium | 17,405 |
https://leetcode.com/problems/car-pooling/discuss/1866545/100-less-memory-50-faster-or-minHeap-or-easy-to-understand | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
drop = {} # passengers drop location list
nxt = trips[0][2] # next/earliest drop point
# swap-> numPassengersi and fromi in the trips, then
# sort(asc) trips as per pickup location
for p in trips:
p[0], p[1] = p[1], p[0]
heapq.heapify(trips)
seats = capacity #available seats
while trips:
# current stop, num of passenger, dest/to
(curr, psg, dest) = heapq.heappop(trips)
# drop passengers
while nxt <= curr:
if drop:
seats += drop[nxt]
del drop[nxt]
if drop:
nxt = min(drop)
else:
nxt = dest
# pick passengers/psg
seats -= psg
if seats < 0:
return False
#number of passengers to drop at location dest
if dest in drop:
drop[dest] += psg
else:
drop[dest] = psg
nxt = min(nxt, dest)
return True | car-pooling | 100% less memory, 50% faster | minHeap | easy to understand | aamir1412 | 0 | 22 | car pooling | 1,094 | 0.573 | Medium | 17,406 |
https://leetcode.com/problems/car-pooling/discuss/1768207/sum-of-diff | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
diff = [0 for i in range(1001)]
for trip in trips:
diff[trip[1]] += trip[0]
diff[trip[2]] -= trip[0]
accu_sum = 0
for num in diff:
accu_sum+=num
if accu_sum>capacity:
return False
return True | car-pooling | sum of diff | ngokchaoho | 0 | 13 | car pooling | 1,094 | 0.573 | Medium | 17,407 |
https://leetcode.com/problems/car-pooling/discuss/1764133/Python-or-Using-difference-approach | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
max_dist = 0 # can also set it 1001, reason see below
for trip in trips: # and remove this for loop
if trip[2] > max_dist:
max_dist = trip[2]
diff = [0] * max_dist
for trip in trips:
diff[trip[1]] += trip[0]
if trip[2] < max_dist:
diff[trip[2]] -= trip[0]
def increment(diff:List[int]):
res = diff
for i in range(1, len(diff)):
res[i] = res[i-1] + diff[i]
return res
capacity_l = increment(diff)
return max(capacity_l)<=capacity | car-pooling | Python | Using difference approach | Fayeyf | 0 | 35 | car pooling | 1,094 | 0.573 | Medium | 17,408 |
https://leetcode.com/problems/car-pooling/discuss/1672057/Python-Solution | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
location = {}
# Create a dictionary with location as key and required seats at that location as value
for trip in trips:
if trip[1] in location.keys():
location[trip[1]] += trip[0]
else:
location[trip[1]] = trip[0]
if trip[2] in location.keys():
location[trip[2]] -= trip[0]
else:
location[trip[2]] = -trip[0]
# Check occupied_seats is more than capacity at a given location
occupied_seats = 0
for k in sorted(location.keys()):
occupied_seats += location[k]
if occupied_seats > capacity:
return False
return True | car-pooling | Python Solution | pradeep288 | 0 | 67 | car pooling | 1,094 | 0.573 | Medium | 17,409 |
https://leetcode.com/problems/car-pooling/discuss/1671666/Car-Pooling-via-Prefix | class Solution:
def carPooling(self, trips, capacity):
n = 0
for _, _, to_i in trips:
if to_i > n:
n = to_i ### calculate total stations
stations = [0] * (n + 1) ### since station index starts from 0
for num_i, from_i, to_i in trips:
stations[from_i] += num_i
if to_i <= n: ### (to_i - 1) + 1 <= (n + 1) - 1:
stations[to_i] -= num_i
for i in range(n + 1):
stations[i] += stations[i - 1] if i else 0
if stations[i] > capacity:
return False
return True | car-pooling | Car Pooling via Prefix | zwang198 | 0 | 32 | car pooling | 1,094 | 0.573 | Medium | 17,410 |
https://leetcode.com/problems/car-pooling/discuss/1671085/simple-memozisation-method-in-Python-O(N) | class Solution:
def carPooling(self, l: List[List[int]], cap: int) -> bool:
dp=[0]*1001
for i in l:
pas,start,end=i[0],i[1],i[2]
dp[start]+=pas
dp[end]-=pas
total = 0
for i in dp:
total +=i
if total > cap:
return False
return True | car-pooling | simple memozisation method in Python O(N) | gamitejpratapsingh998 | 0 | 19 | car pooling | 1,094 | 0.573 | Medium | 17,411 |
https://leetcode.com/problems/car-pooling/discuss/1670840/Easy-Python3-solution-using-array-or-Very-simple-trick-to-beat-99-with-56ms | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
pas = [0]*1001
first, last = 1000, 0
for a, s, e in trips:
first = min(first, s)
last = max(last, s)
pas[s] += a
pas[e] -= a
res = 0
for n in range(first, last+1):
res += pas[n]
if res > capacity:
return False
return True
``` | car-pooling | Easy Python3 solution using array | Very simple trick to beat 99% with 56ms | nandhakiran366 | 0 | 16 | car pooling | 1,094 | 0.573 | Medium | 17,412 |
https://leetcode.com/problems/car-pooling/discuss/1669810/Python3-easy-understanding-solution | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
# sort trips according to "to i"
trips = sorted(trips, key=lambda x: x[2])
# store the number of current passengers in each location
total_dis = trips[-1][2]
num_passenger = [0]*(total_dis+1)
for i in trips:
for j in range(i[1], i[2]):
num_passenger[j] += i[0]
if num_passenger[j] > capacity:
return False
return True | car-pooling | Python3 easy-understanding solution | Janetcxy | 0 | 17 | car pooling | 1,094 | 0.573 | Medium | 17,413 |
https://leetcode.com/problems/car-pooling/discuss/1669591/Python-or-Easy-understanding-but-not-the-most-efficient-solution | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
dic = collections.defaultdict(int)
for numPass, begin, end in trips:
dic[begin] += numPass
dic[end] -= numPass
keys = sorted(dic.keys())
passenger = 0
for key in keys:
passenger += dic[key]
if passenger > capacity:
return False
return True | car-pooling | Python | Easy understanding but not the most efficient solution | CPeng818 | 0 | 28 | car pooling | 1,094 | 0.573 | Medium | 17,414 |
https://leetcode.com/problems/car-pooling/discuss/1440901/Python3-solution | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
l = []
r = []
p = []
for i,j in enumerate(trips):
l.append((j[1],i))
r.append((j[2],i))
p.append(j[0])
l.sort(key = lambda x:x[0])
r.sort(key = lambda x:x[0])
curr = 0
for i in range(l[0][0],r[-1][0]+1):
# print(curr,l,r,i)
while r and i == r[0][0]:
curr -= p[r[0][1]]
r.pop(0)
while l and i == l[0][0]:
curr += p[l[0][1]]
l.pop(0)
if curr > capacity:
return False
return True | car-pooling | Python3 solution | EklavyaJoshi | 0 | 57 | car pooling | 1,094 | 0.573 | Medium | 17,415 |
https://leetcode.com/problems/car-pooling/discuss/875984/Python3-straightforward-solution | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
ind = 0
for a,b,c in trips:
ind = max(ind, b, c)
res = [0] * (ind+1)
for a, b, c in trips:
for i in range(b, c):
res[i] += a
return not any([x > capacity for x in res]) | car-pooling | Python3 straightforward solution | ermolushka2 | 0 | 54 | car pooling | 1,094 | 0.573 | Medium | 17,416 |
https://leetcode.com/problems/car-pooling/discuss/862964/Python-O(nlogn)-sweep-line | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
time = [0 for _ in range(1001)]
for num, start, end in trips:
time[start] += num
time[end] -= num
for i in range(len(time)):
capacity -= time[i]
if capacity < 0:
return False
return True | car-pooling | Python O(nlogn) sweep line | ethuoaiesec | 0 | 51 | car pooling | 1,094 | 0.573 | Medium | 17,417 |
https://leetcode.com/problems/car-pooling/discuss/858408/Python3-change-of-passengers | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
chg = [0]*1001 # change of passenger at i
for n, i, j in trips:
chg[i] += n # n more passengers
chg[j] -= n # n less passengers
for i in range(1, 1001):
chg[i] += chg[i-1] # passengers in car at i
if chg[i] > capacity: return False
return True | car-pooling | [Python3] change of passengers | ye15 | 0 | 27 | car pooling | 1,094 | 0.573 | Medium | 17,418 |
https://leetcode.com/problems/car-pooling/discuss/858408/Python3-change-of-passengers | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
chg = []
for n, i, j in trips: chg.extend([(i, +n), (j, -n)]) # change in passengers
for _, x in sorted(chg):
if (capacity := capacity - x) < 0: return False
return True | car-pooling | [Python3] change of passengers | ye15 | 0 | 27 | car pooling | 1,094 | 0.573 | Medium | 17,419 |
https://leetcode.com/problems/car-pooling/discuss/712901/Using-Hashmap | class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
trips = sorted(trips, key = lambda a: a[1])
# print(trips)
i = 0
j = trips[0][1]
se = collections.defaultdict(int)
while i< len(trips):
capacity+=se[j]
del se[j]
if j == trips[i][1]:
se[trips[i][2]] += trips[i][0]
capacity-= trips[i][0]
i+=1
if capacity<0:
return False
else:
j+=1
return True | car-pooling | Using Hashmap | arjunmnn | 0 | 57 | car pooling | 1,094 | 0.573 | Medium | 17,420 |
https://leetcode.com/problems/find-in-mountain-array/discuss/1290875/Python3-binary-search | class Solution:
def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int:
def fn(lo, hi, mult):
"""Return index of target between lo (inclusive) and hi (exlusive)."""
while lo < hi:
mid = lo + hi >> 1
if mountain_arr.get(mid) == target: return mid
elif mountain_arr.get(mid)*mult < target*mult: lo = mid + 1
else: hi = mid
return -1
lo, hi = 0, mountain_arr.length()
while lo < hi:
mid = lo + hi >> 1
if mid and mountain_arr.get(mid-1) < mountain_arr.get(mid): lo = mid + 1
else: hi = mid
if (x := fn(0, lo, 1)) != -1: return x
if (x := fn(lo, mountain_arr.length(), -1)) != -1: return x
return -1 | find-in-mountain-array | [Python3] binary search | ye15 | 1 | 48 | find in mountain array | 1,095 | 0.357 | Hard | 17,421 |
https://leetcode.com/problems/find-in-mountain-array/discuss/2805137/2-Pass-Binary-Search-or-Python | class Solution:
def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int:
length = mountain_arr.length() - 1
if mountain_arr.get(0) == target:
return 0
min_idx = sys.maxsize
if mountain_arr.get(length) == target:
min_idx = length
//check left of peak first
l,r = 0, length
while l <= r:
middle = (l + r) // 2
val = mountain_arr.get(middle)
if middle < length:
if val == target:
min_idx = min(min_idx,middle)
plus1 = mountain_arr.get(middle+1)
if val < plus1:
if val < target:
l = middle + 1
else:
r = middle - 1
else:
r = middle - 1
else:
break
//check right of peak next
l, r = 0, length
while l <= r:
middle = (l + r) // 2
val = mountain_arr.get(middle)
if middle < length:
if val == target:
min_idx = min(min_idx,middle)
plus1 = mountain_arr.get(middle+1)
if val > plus1:
if val > target:
l = middle + 1
else:
r = middle - 1
else:
l = middle + 1
else:
break
// if we have not found the element, its time to just
// return -1
return min_idx if min_idx != sys.maxsize else -1 | find-in-mountain-array | 2-Pass Binary Search | Python | MutableStringz | 0 | 5 | find in mountain array | 1,095 | 0.357 | Hard | 17,422 |
https://leetcode.com/problems/find-in-mountain-array/discuss/2598928/Python-or-3-Binary-Searches | class Solution:
def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int:
n = mountain_arr.length()
s, e = 0, n - 1
# special 0 case
if target == 0:
if mountain_arr.get(s) == 0:
return 0
elif mountain_arr.get(e) == 0:
return n - 1
else:
return -1
# find peak of mountain first
peak = -1
while s <= e:
if e - s < 2:
peak = s if mountain_arr.get(s) > mountain_arr.get(e) else e
break
m = (s + e) // 2
l, val, r = mountain_arr.get(m - 1), mountain_arr.get(m), mountain_arr.get(m + 1)
if l < val > r:
peak = m
break
if l < val:
s = m + 1
else:
e = m - 1
# use negatives if the search space is decreasing
def search(s, e, tar):
while s <= e:
m = (s + e) // 2
val = mountain_arr.get(m)
if tar < 0:
val *= -1
if val == tar:
return m
if val < tar:
s = m + 1
else:
e = m - 1
return -1
# once we have the peak, search left first then right
l = search(0, peak, target)
if l > -1:
return l
return search(peak, n - 1, -target) | find-in-mountain-array | Python | 3 Binary Searches | ryangrayson | 0 | 9 | find in mountain array | 1,095 | 0.357 | Hard | 17,423 |
https://leetcode.com/problems/find-in-mountain-array/discuss/2191728/python-3-or-3-binary-searches | class Solution:
def findInMountainArray(self, target: int, arr: 'MountainArray') -> int:
# find mountain index
low, high = 1, arr.length() - 2
while True:
mid = (low + high) // 2
midLeftVal, midVal = arr.get(mid - 1), arr.get(mid)
if midLeftVal < midVal > arr.get(mid + 1):
i = mid
break
elif midLeftVal < midVal:
low = mid + 1
else:
high = mid - 1
# look for target before mountain index
low, high = 0, i
while low <= high:
mid = (low + high) // 2
midVal = arr.get(mid)
if midVal == target:
return mid
elif midVal < target:
low = mid + 1
else:
high = mid - 1
# look for target after mountain index
low, high = i + 1, arr.length() - 1
while low <= high:
mid = (low + high) // 2
midVal = arr.get(mid)
if midVal == target:
return mid
elif midVal < target:
high = mid - 1
else:
low = mid + 1
return -1 | find-in-mountain-array | python 3 | 3 binary searches | dereky4 | 0 | 53 | find in mountain array | 1,095 | 0.357 | Hard | 17,424 |
https://leetcode.com/problems/find-in-mountain-array/discuss/1642529/Python-Simple-Solution-(20ms)-Beats-99 | class Solution:
def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int:
try:
return mountain_arr._MountainArray__secret.index(target)
except ValueError:
return -1 | find-in-mountain-array | Python Simple Solution (20ms) - Beats 99% | migash | 0 | 65 | find in mountain array | 1,095 | 0.357 | Hard | 17,425 |
https://leetcode.com/problems/find-in-mountain-array/discuss/907559/Python3Java-Triple-Binary-Search | class Solution:
def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int:
low = 0
high = mountain_arr.length()
peak = -1
while (low < high - 1):
mid = (low + high) // 2
midVal = mountain_arr.get(mid)
leftMid = mountain_arr.get(mid - 1)
rightMid = mountain_arr.get(mid + 1)
if (midVal > leftMid and midVal > rightMid):
peak = mid
break
elif (midVal > leftMid and midVal < rightMid):
low = mid
else:
high = mid
low = 0
high = peak
while (low <= high):
mid = (low + high) // 2
midVal = mountain_arr.get(mid)
if midVal == target:
return mid
elif midVal < target:
low = mid + 1
else:
high = mid - 1
low = peak
high = mountain_arr.length() - 1
while (low <= high):
mid = (low + high) // 2
print(low, mid, high)
midVal = mountain_arr.get(mid)
if midVal == target:
return mid
elif midVal < target:
high = mid - 1
else:
low = mid + 1
return -1 | find-in-mountain-array | Python3/Java Triple Binary Search | algorithm_buddy | 0 | 61 | find in mountain array | 1,095 | 0.357 | Hard | 17,426 |
https://leetcode.com/problems/brace-expansion-ii/discuss/322002/Python3-Concise-iterative-solution-using-stack | class Solution:
def braceExpansionII(self, expression: str) -> List[str]:
stack,res,cur=[],[],[]
for i in range(len(expression)):
v=expression[i]
if v.isalpha():
cur=[c+v for c in cur or ['']]
elif v=='{':
stack.append(res)
stack.append(cur)
res,cur=[],[]
elif v=='}':
pre=stack.pop()
preRes=stack.pop()
cur=[p+c for c in res+cur for p in pre or ['']]
res=preRes
elif v==',':
res+=cur
cur=[]
return sorted(set(res+cur)) | brace-expansion-ii | [Python3] Concise iterative solution using stack | yuanzhi247012 | 102 | 4,800 | brace expansion ii | 1,096 | 0.635 | Hard | 17,427 |
https://leetcode.com/problems/brace-expansion-ii/discuss/1257748/Python3-recursive-solution | class Solution:
def braceExpansionII(self, expression: str) -> List[str]:
mp, stack = {}, []
for i, x in enumerate(expression):
if x == "{": stack.append(i)
elif x == "}": mp[stack.pop()] = i
def fn(lo, hi):
"""Return expanded outcome of expression[lo:hi]."""
ans = [[""]]
if lo+1 < hi:
i = lo
while i < hi:
if expression[i] == ",": ans.append([""])
else:
if expression[i] == "{":
y = fn(i+1, mp[i])
i = mp[i]
else: y = expression[i]
ans.append([xx+yy for xx in ans.pop() for yy in y])
i += 1
return sorted({xx for x in ans for xx in x})
return fn(0, len(expression)) | brace-expansion-ii | [Python3] recursive solution | ye15 | 1 | 197 | brace expansion ii | 1,096 | 0.635 | Hard | 17,428 |
https://leetcode.com/problems/brace-expansion-ii/discuss/2569745/Beat100-PythonPython3-super-clear-and-easy-solution-using-recursiondfs | class Solution:
def braceExpansionII(self, s: str) -> List[str]:
def getWord():
nonlocal i
word = ""
while i < len(s) and s[i].isalpha():
word += s[i]
i += 1
return word
def dfs():
nonlocal i
res = set()
if s[i] == '{':
i += 1
res.update(dfs())
while i < len(s) and s[i] == ',':
i += 1
res.update(dfs())
i += 1
elif s[i].isalpha():
res.add(getWord())
while i < len(s) and (s[i] == '{' or s[i].isalpha()):
res = {w + a for a in dfs() for w in res}
return res
i = 0
return sorted(dfs()) | brace-expansion-ii | [Beat100%] Python/Python3 super clear and easy solution using recursion/dfs | happycoaster | 0 | 31 | brace expansion ii | 1,096 | 0.635 | Hard | 17,429 |
https://leetcode.com/problems/distribute-candies-to-people/discuss/797848/Solution-or-Python | class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
# create an array of size num_people and initialize it with 0
list_people = [0] * num_people
# starting value
index = 1
# iterate until the number of candies are more than 0
while candies > 0:
# if candies are more than index value, add the index value to the location
if candies > index:
# we are using mod operation by the num_people to locate the index of the array
# we are subtracting by 1 because the array index starts at 0
list_people[(index - 1) % num_people] += index
else:
# if candies are less than index value, add all remaining candies to location
list_people[(index - 1) % num_people] += candies
# subtract the candies with index values
candies -= index
# increment the index values
index += 1
# return the resultant array
return(list_people) | distribute-candies-to-people | Solution | Python | rushirg | 11 | 439 | distribute candies to people | 1,103 | 0.639 | Easy | 17,430 |
https://leetcode.com/problems/distribute-candies-to-people/discuss/1088053/Python.-Easy-understanding-solution. | class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
res = [0] * num_people
index = 0
while candies > 0:
res[index % num_people] += min(index + 1, candies)
index += 1
candies -= index
return res | distribute-candies-to-people | Python. Easy-understanding solution. | m-d-f | 3 | 155 | distribute candies to people | 1,103 | 0.639 | Easy | 17,431 |
https://leetcode.com/problems/distribute-candies-to-people/discuss/1896445/Python-easy-solution-beginner-friendly | class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
res = [0] * num_people
dist = 1
pos = 0
while candies > 0:
if pos == num_people:
pos = 0
if candies < dist:
res[pos] += candies
return res
res[pos] += dist
candies -= dist
dist += 1
pos += 1
return res | distribute-candies-to-people | Python easy solution, beginner friendly | alishak1999 | 1 | 114 | distribute candies to people | 1,103 | 0.639 | Easy | 17,432 |
https://leetcode.com/problems/distribute-candies-to-people/discuss/1264310/Python-3-or-100-Fast-or-used-math | class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
distribution = 0
iteration = 0
past_distribution = 0
while distribution <= candies:
past_distribution = distribution
iteration += 1
distribution = ((num_people*iteration)*(num_people * iteration + 1))//2
candies -= past_distribution
ans = []
for i in range(num_people):
x = iteration-1
ith_candies = (i+1)*(x) + (num_people*x*(x-1))//2
if candies > 0:
new_candy = (i+1) + ((iteration-1)*num_people)
new_candies = min(candies, new_candy)
ith_candies += new_candies
candies -= new_candies
ans.append(ith_candies)
return ans | distribute-candies-to-people | Python 3 | 100% Fast | used math | Sanjaychandak95 | 1 | 80 | distribute candies to people | 1,103 | 0.639 | Easy | 17,433 |
https://leetcode.com/problems/distribute-candies-to-people/discuss/529674/python3-easy-to-understand-time%3A81-memory%3A100 | class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
res = [0] * num_people
n = 1
while candies:
for i in range(num_people):
res[i] += n
candies -= n
if candies < 0:
res[i] -= n
res[i] += n + candies
return res
n += 1
return res | distribute-candies-to-people | python3 easy to understand time:81% memory:100 % | wudishiduomeduomojimo | 1 | 142 | distribute candies to people | 1,103 | 0.639 | Easy | 17,434 |
https://leetcode.com/problems/distribute-candies-to-people/discuss/2722065/python3-oror-simple-to-understand | class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
current = 1
index = 0
result = [0] * num_people
while candies > 0:
result[index] += min(current,candies)
candies -= current
index = (index + 1) % num_people
current += 1
return result | distribute-candies-to-people | python3 || simple to understand | KateIV | 0 | 9 | distribute candies to people | 1,103 | 0.639 | Easy | 17,435 |
https://leetcode.com/problems/distribute-candies-to-people/discuss/2441366/python | class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
ans = [0]*num_people
index = 0
extra = 0
times = 1
while candies > 0:
if candies - (index + 1 + extra) >= 0:
ans[index] += index + 1 + extra
candies -= (index + 1 + extra)
else:
ans[index] += candies
break
index += 1
if index == num_people:
extra = times*num_people
index = 0
times += 1
return ans | distribute-candies-to-people | python | akashp2001 | 0 | 51 | distribute candies to people | 1,103 | 0.639 | Easy | 17,436 |
https://leetcode.com/problems/distribute-candies-to-people/discuss/2371881/easy-python-solution | class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
candy_dict = {}
for i in range(num_people) :
candy_dict[i] = 0
candy, i, totalCandy = 1, 0, 0
while totalCandy < candies :
if i >= num_people :
i = 0
if candies - totalCandy >= candy :
candy_dict[i] += candy
totalCandy += candy
else :
candy_dict[i] += candies - totalCandy
totalCandy += candies - totalCandy
i += 1
candy += 1
return candy_dict.values() | distribute-candies-to-people | easy python solution | sghorai | 0 | 146 | distribute candies to people | 1,103 | 0.639 | Easy | 17,437 |
https://leetcode.com/problems/distribute-candies-to-people/discuss/2313955/Python-3-solution-(MATH-BASED) | class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
import math
a=math.floor((-1+math.sqrt(1+4*2*candies))/2)
diff=candies-(a*(a+1)//2)
res=[0]*num_people
res[a%num_people]+=diff
for i in range(num_people):
if i<a%num_people:
res[i]+=(i+1)*(a//num_people+1)+num_people*((a//num_people)*(a//num_people+1)//2)
else:
res[i]+=(i+1)*(a//num_people)+num_people*(((a//num_people)*(a//num_people-1)//2))
return res | distribute-candies-to-people | Python 3 solution (MATH BASED) | Kunalbmd | 0 | 40 | distribute candies to people | 1,103 | 0.639 | Easy | 17,438 |
https://leetcode.com/problems/distribute-candies-to-people/discuss/1895876/Python-3-oror-mathematical-solution-explained-oror-O(n)-time | class Solution:
def distributeCandies(self, c: int, n: int) -> List[int]:
k = int((-1 + math.sqrt(1 + 8*c)) / (2 * n))
res = [k*i + k*n*(k - 1) // 2 for i in range(1, n + 1)]
c -= k*n*(k*n + 1) // 2
i = 0
candy = k*n + 1
while c:
amount = min(c, candy + i)
c -= amount
res[i] += amount
i += 1
return res | distribute-candies-to-people | Python 3 || mathematical solution explained || O(n) time | dereky4 | 0 | 115 | distribute candies to people | 1,103 | 0.639 | Easy | 17,439 |
https://leetcode.com/problems/distribute-candies-to-people/discuss/1850003/3-Lines-Python-Solution-oror-70-Faster-oror-Memory-less-than-70 | class Solution:
def distributeCandies(self, C: int, N: int) -> List[int]:
ans=[0]*N ; i=0
while C>0: ans[(i-1)%N]+=min(i,C) ; C-=i ; i+=1
return ans | distribute-candies-to-people | 3-Lines Python Solution || 70% Faster || Memory less than 70% | Taha-C | 0 | 73 | distribute candies to people | 1,103 | 0.639 | Easy | 17,440 |
https://leetcode.com/problems/distribute-candies-to-people/discuss/1819104/Python-Solution | class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
n = 1
arr = [0] * num_people
n = 1 #n is the number of candies given to a person
i = -1
while candies != 0:
i += 1
if i > num_people -1:
i = 0
if candies - n < 0:
arr[i] += candies
candies = 0
else:
arr[i] += n
candies -= n
n += 1
return arr | distribute-candies-to-people | Python Solution | MS1301 | 0 | 44 | distribute candies to people | 1,103 | 0.639 | Easy | 17,441 |
https://leetcode.com/problems/distribute-candies-to-people/discuss/1409791/Python3-Simulation-Faster-Than-81.98-Memory-Less-Than-79.70 | class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
d, c = [0] * num_people, 1
while candies > 0:
for i in range(num_people):
if c <= candies:
d[i] += c
candies -= c
c += 1
if candies == 0:
return d
else:
d[i] += candies
return d | distribute-candies-to-people | Python3 Simulation Faster Than 81.98%, Memory Less Than 79.70% | Hejita | 0 | 99 | distribute candies to people | 1,103 | 0.639 | Easy | 17,442 |
https://leetcode.com/problems/distribute-candies-to-people/discuss/1278815/Python-simple-and-easy-solution | class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
c=0
o=[0]*num_people
while(candies!=0):
c+=1
if candies-c<0:
o[(c-1)%num_people]+=candies
break
else:
candies-=c
o[(c-1)%num_people]+=c
return o | distribute-candies-to-people | Python simple and easy solution | coderash1998 | 0 | 105 | distribute candies to people | 1,103 | 0.639 | Easy | 17,443 |
https://leetcode.com/problems/distribute-candies-to-people/discuss/1072277/Python3-simple-solution | class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
res = [0]*num_people
c = 1
i = 0
while c <= candies:
res[i % num_people] += c
i += 1
candies -= c
c += 1
res[i % num_people] += candies
return res | distribute-candies-to-people | Python3 simple solution | EklavyaJoshi | 0 | 63 | distribute candies to people | 1,103 | 0.639 | Easy | 17,444 |
https://leetcode.com/problems/distribute-candies-to-people/discuss/797699/O(n)-solution.-99-time | class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
def gauss_sum(n):
return n*(n+1)//2
def binaryFind():
start, end = 0, 10**9
ans = -1
while start <= end:
mid = (start+end)//2
#n*(n+1)/2+k*n*n
target = sum_one_row*(mid+1)+gauss_sum(mid)*(num_people**2)
if target == candies:
return mid
elif target < candies:
ans = mid
start = mid+1
else:
end = mid-1
return ans
sum_one_row = gauss_sum(num_people)
# find largest k s.t. k+1 rows
# can be filled with candy in full
k = binaryFind()
ans = [0]*num_people
if k >= 0:
# cal candies distribution until k+1th row
# for 1st column, it is (k+1)+n*(1+k)*k/2
ans[0] = num_people*gauss_sum(k)+k+1
for i in range(1, num_people):
ans[i] = ans[i-1]+k+1
# remaining candies for the last row
candies -= (k+1)*sum_one_row+gauss_sum(k)*(num_people**2)
i = 0
base = (k+1)*num_people
while candies > i+1+base:
ans[i] += i+1+base
candies -= i+1+base
i += 1
ans[i] += candies
return ans | distribute-candies-to-people | O(n) solution. 99% time | ytb_algorithm | 0 | 40 | distribute candies to people | 1,103 | 0.639 | Easy | 17,445 |
https://leetcode.com/problems/distribute-candies-to-people/discuss/797194/Python-3-Distribute-Candies-or-96-Faster-or-Easy | class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
distribution = [0]*num_people
i = 1
while candies > 0:
index = (i%num_people)-1
if candies < i:
distribution[index] += candies
break
else:
distribution[index] += i
candies -= i
i += 1
return distribution | distribute-candies-to-people | [Python 3 ] Distribute Candies | 96% Faster | Easy | tnitave | 0 | 69 | distribute candies to people | 1,103 | 0.639 | Easy | 17,446 |
https://leetcode.com/problems/distribute-candies-to-people/discuss/477268/Python3-99.56-(20-ms)100.00-(12.7-MB)-using-maths-formula | class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
cycle_offset = num_people * (num_people + 1) // 2
cycles = 0
n_2 = num_people ** 2
required_candies = cycle_offset
ret = []
while (candies >= required_candies):
cycles += 1
candies -= required_candies
required_candies = cycles * n_2 + cycle_offset
if (cycles > 0):
fixed_candy_size = cycles * (cycles - 1) // 2 * num_people
for person in range(1, num_people + 1):
ret.append(fixed_candy_size + cycles * person)
fixed_candy_size = cycles * num_people
for person in range(num_people):
person_candies = fixed_candy_size + person + 1
if (person_candies > candies):
ret[person] += candies
return ret
else:
ret[person] += person_candies
candies -= person_candies
else:
skip = False
for person in range(1, num_people + 1):
if (skip):
ret.append(0)
elif (candies < person):
ret.append(candies)
skip = True
else:
ret.append(person)
candies -= person
return ret | distribute-candies-to-people | Python3 99.56% (20 ms)/100.00% (12.7 MB) -- using maths formula | numiek_p | 0 | 50 | distribute candies to people | 1,103 | 0.639 | Easy | 17,447 |
https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/discuss/323382/Python-3-easy-explained | class Solution:
def pathInZigZagTree(self, label: int) -> List[int]:
rows = [(1, 0)] #row represented by tuple (min_element_in_row, is_neg_order)
while rows[-1][0]*2 <= label:
rows.append((rows[-1][0]*2, 1 - rows[-1][1]))
power, negOrder = rows.pop()
res = []
while label > 1:
res.append(label)
if negOrder:
# adjust label position and find parent with division by 2
# a, b - range of current row
a, b = power, power*2 -1
label = (a + (b - label))//2
else:
# divide label by 2 and adjust parent position
# a, b - range of previous row
a, b = power//2, power - 1
label = b - (label//2 - a)
power, negOrder = rows.pop()
res.append(1)
return res[::-1] | path-in-zigzag-labelled-binary-tree | Python 3 easy explained | vilchinsky | 3 | 207 | path in zigzag labelled binary tree | 1,104 | 0.75 | Medium | 17,448 |
https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/discuss/2683563/Python3-XOR-Solution | class Solution:
def pathInZigZagTree(self, label: int) -> List[int]:
x = label
mask = 0
while x > 1:
x >>= 1
mask <<= 1
mask |= 1
x = label
res = deque()
while x:
res.appendleft(x)
x >>= 1
mask >>= 1
x ^= mask
return res | path-in-zigzag-labelled-binary-tree | [Python3] XOR Solution | rt500 | 2 | 58 | path in zigzag labelled binary tree | 1,104 | 0.75 | Medium | 17,449 |
https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/discuss/1176846/Python3-move-along-the-tree | class Solution:
def pathInZigZagTree(self, label: int) -> List[int]:
level = int(log2(label))
compl = 3*2**level - 1 - label # complement
ans = []
while label:
ans.append(label)
label //= 2
compl //= 2
label, compl = compl, label
return ans[::-1] | path-in-zigzag-labelled-binary-tree | [Python3] move along the tree | ye15 | 1 | 62 | path in zigzag labelled binary tree | 1,104 | 0.75 | Medium | 17,450 |
https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/discuss/461146/Fastest-Solution-O(logn)-time | class Solution:
def pathInZigZagTree(self, label: int) -> List[int]:
ret = [label]
height = int(math.log(label,2))
prev = 1<<height
while height:
right = prev-1 # 2^height-1
left = prev = prev//2 # 2^(height-1)
label = left+right-label//2
ret.append(label)
height -= 1
return ret[::-1] | path-in-zigzag-labelled-binary-tree | Fastest Solution O(logn) time | fallenranger | 1 | 131 | path in zigzag labelled binary tree | 1,104 | 0.75 | Medium | 17,451 |
https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/discuss/2210523/python-3-or-efficient-solution | class Solution:
def pathInZigZagTree(self, label: int) -> List[int]:
res = []
bits = math.floor(math.log2(label)) + 1
allOnes = (1 << bits)
if not bits % 2:
label = allOnes + (allOnes >> 1) - label - 1
for i in range(bits, 0, -1):
if i % 2:
res.append(label)
else:
res.append(allOnes + (allOnes >> 1) - label - 1)
allOnes >>= 1
label >>= 1
res.reverse()
return res | path-in-zigzag-labelled-binary-tree | python 3 | efficient solution | dereky4 | 0 | 50 | path in zigzag labelled binary tree | 1,104 | 0.75 | Medium | 17,452 |
https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/discuss/2166137/PYTHON-SOL-orINTUITIVE-or-EXPLAINED-or-EASY-TO-UNDERSTAND-or | class Solution:
def pathInZigZagTree(self, label: int) -> List[int]:
if label == 1: return [1]
start,end = 1,1
data =[(start,end)]
row = 1
to_add = 2
while True:
start = end + 1
end = start + to_add -1
to_add *= 2
row += 1
if row %2 == 0:
data.append((end,start))
else:
data.append((start,end))
if end >= label : break
ans = []
if row % 2 == 0:
# we need to change the actual for now
ans.append(label)
pos = start + 1 - label
label = end - 1 + pos
row -= 1
else:
ans.append(label)
row -= 1
while True:
label = label // 2
start,end = data[row-1]
if row % 2 == 0:
pos = label - start + 1
actual = end + 1 - pos
ans.append(actual)
else:
ans.append(label)
row -= 1
if label == 1:
break
return ans[::-1] | path-in-zigzag-labelled-binary-tree | PYTHON SOL |INTUITIVE | EXPLAINED | EASY TO UNDERSTAND | | reaper_27 | 0 | 51 | path in zigzag labelled binary tree | 1,104 | 0.75 | Medium | 17,453 |
https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/discuss/1011557/The-easiest-solution-for-this-question-Python | class Solution:
def pathInZigZagTree(self, label: int) -> List[int]:
k = []
while True:
if label ==1:
k.append(1)
break
for i in range(21):
if 2**i <= label and 2**(i+1) > label:
k.append(label)
start = 2**(i-1)
end = (2**i) -1
label = label//2
label = end - (label - start)
return k[::-1] | path-in-zigzag-labelled-binary-tree | The easiest solution for this question Python | yashagrawal300 | 0 | 111 | path in zigzag labelled binary tree | 1,104 | 0.75 | Medium | 17,454 |
https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/discuss/459393/Python-3-math | class Solution:
def pathInZigZagTree(self, label: int) -> List[int]:
def caculate_next(num):
if num == 1:
return 0
level = math.floor(math.log(num, 2))
return 2**(level-1) + 2**(level)- num//2 - 1
ans = []
while label > 0:
ans.append(label)
label = caculate_next(label)
ans.reverse()
return ans | path-in-zigzag-labelled-binary-tree | Python 3 math | Christian_dudu | 0 | 73 | path in zigzag labelled binary tree | 1,104 | 0.75 | Medium | 17,455 |
https://leetcode.com/problems/filling-bookcase-shelves/discuss/1517001/Python-3-or-DP-or-Explanation | class Solution:
def minHeightShelves(self, books: List[List[int]], shelfWidth: int) -> int:
n = len(books)
dp = [sys.maxsize] * n
dp[0] = books[0][1] # first book will always on it's own row
for i in range(1, n): # for each book
cur_w, height_max = books[i][0], books[i][1]
dp[i] = dp[i-1] + height_max # initialize result for current book `dp[i]`
for j in range(i-1, -1, -1): # for each previou `book[j]`, verify if it can be placed in the same row as `book[i]`
if cur_w + books[j][0] > shelfWidth: break
cur_w += books[j][0]
height_max = max(height_max, books[j][1]) # update current max height
dp[i] = min(dp[i], (dp[j-1] + height_max) if j-1 >= 0 else height_max) # always take the maximum heigh on current row
return dp[n-1] | filling-bookcase-shelves | Python 3 | DP | Explanation | idontknoooo | 5 | 518 | filling bookcase shelves | 1,105 | 0.592 | Medium | 17,456 |
https://leetcode.com/problems/filling-bookcase-shelves/discuss/2174413/PYTHON-SOL-or-EXPLAINED-WITH-PICTURE-or-RECURSION-%2B-MEMO-or | class Solution:
def recursion(self, idx , n , height , width):
if idx == n:return height
if (idx,height,width) in self.dp: return self.dp[(idx,height,width)]
choice1 = self.recursion(idx+1,n,max(self.books[idx][1],height), width - self.books[idx][0])\
if width >= self.books[idx][0] else float('inf')
choice2 = self.recursion(idx+1,n,self.books[idx][1], self.shelfWidth - self.books[idx][0]) + height
ans = min(choice1,choice2)
self.dp[(idx,height,width)] = ans
return ans
def minHeightShelves(self, books: List[List[int]], shelfWidth: int) -> int:
self.books = books
self.shelfWidth = shelfWidth
self.dp = {}
return self.recursion(0,len(books),0,shelfWidth) | filling-bookcase-shelves | PYTHON SOL | EXPLAINED WITH PICTURE | RECURSION + MEMO | | reaper_27 | 3 | 315 | filling bookcase shelves | 1,105 | 0.592 | Medium | 17,457 |
https://leetcode.com/problems/filling-bookcase-shelves/discuss/1705780/1d-DP-easy-solution-python3-C%2B%2B | class Solution:
def minHeightShelves(self, books: List[List[int]], shelfWidth: int) -> int:
books = [[0,0]] + books
dp = [float("inf")] * len(books)
dp[0] = 0
for i in range(1,len(books)):
width, height = books[i]
j = i
while width <= shelfWidth and j>0:
dp[i] = min(dp[i], dp[j-1]+height)
j -= 1
width += books[j][0]
height = max(height, books[j][1])
#print(dp)
return dp[-1] | filling-bookcase-shelves | 1d DP easy solution python3 C++ | albertnew2018 | 3 | 243 | filling bookcase shelves | 1,105 | 0.592 | Medium | 17,458 |
https://leetcode.com/problems/filling-bookcase-shelves/discuss/323347/Python3-DP-solution | class Solution:
def minHeightShelves(self, books: List[List[int]], shelf_width: int) -> int:
dp = [float('inf')] * (len(books)+1)
dp[0] = 0
for i in range(len(books)):
w, h = 0, 0
for j in range(i, len(books)):
w += books[j][0]
h = max(h, books[j][1])
if w <= shelf_width:
dp[j+1] = min(dp[j+1], dp[i] + h)
else:
break
return dp[len(books)] | filling-bookcase-shelves | Python3 DP solution | aj_to_rescue | 1 | 251 | filling bookcase shelves | 1,105 | 0.592 | Medium | 17,459 |
https://leetcode.com/problems/filling-bookcase-shelves/discuss/2785017/Python-(Simple-DP) | class Solution:
def minHeightShelves(self, books, shelfWidth):
@lru_cache(None)
def dp(idx,cur_height,cur_width):
if cur_width < 0:
return float("inf")
if idx == len(books):
return cur_height
thickness, height = books[idx]
same_shelf = dp(idx+1,max(height,cur_height),cur_width-thickness)
change_shelf = cur_height + dp(idx+1,height,shelfWidth-thickness)
return min(same_shelf,change_shelf)
return dp(0,0,shelfWidth) | filling-bookcase-shelves | Python (Simple DP) | rnotappl | 0 | 11 | filling bookcase shelves | 1,105 | 0.592 | Medium | 17,460 |
https://leetcode.com/problems/filling-bookcase-shelves/discuss/2781710/0-1-knapsack-DP-python-solution | class Solution:
def minHeightShelves(self, books: List[List[int]], shelfWidth: int) -> int:
N = len(books)
dp = [0] * (N + 1)
for i in range(1, N + 1):
width = books[i - 1][0]
height = books[i - 1][1]
dp[i] = dp[i - 1] + height
for j in range(i - 1, 0, -1):
if books[j - 1][0] + width <= shelfWidth:
dp[i] = min(dp[i], dp[j - 1] + max(height, books[j - 1][1]))
else:
break
width += books[j - 1][0]
height = max(height, books[j - 1][1])
return dp[N] | filling-bookcase-shelves | 0-1 knapsack DP / python solution | Lara_Craft | 0 | 16 | filling bookcase shelves | 1,105 | 0.592 | Medium | 17,461 |
https://leetcode.com/problems/filling-bookcase-shelves/discuss/2772247/Python3-or-DP-or-Memoization | class Solution:
def minHeightShelves(self, books: List[List[int]], shelf_width: int) -> int:
n = len(books)
@cache
def res(pos = 0):
if pos == n:
return 0
else:
w = shelf_width - books[pos][0]
h = books[pos][1]
ret = h + res(pos + 1)
i = pos + 1
while i < n and w - books[i][0] >= 0:
w -= books[i][0]
h = max(h, books[i][1])
ret = min(ret, h + res(i + 1))
i += 1
return ret
return res() | filling-bookcase-shelves | Python3 | DP | Memoization | DheerajGadwala | 0 | 8 | filling bookcase shelves | 1,105 | 0.592 | Medium | 17,462 |
https://leetcode.com/problems/filling-bookcase-shelves/discuss/1398580/Simple-commented-DP-for-dummies-like-me-O(n2) | class Solution:
def minHeightShelves(self, books: List[List[int]], shelfWidth: int) -> int:
# let dp[i] denote the minimum possible height to place
# the first i books on the shelve.
dp = [0]+[float("inf")]*len(books)
for i in range(1, len(dp)):
# which books do I want to place on the last row
# along with book i so that the total height is
# minimized?
last_row_height = last_row_width = 0
for j in range(i-1, -1, -1):
last_row_width += books[j][0]
if last_row_width > shelfWidth: break
last_row_height = max(last_row_height, books[j][1])
dp[i] = min(dp[i], dp[j]+last_row_height)
return dp[-1] | filling-bookcase-shelves | Simple commented DP for dummies like me O(n^2) | Charlesl0129 | 0 | 244 | filling bookcase shelves | 1,105 | 0.592 | Medium | 17,463 |
https://leetcode.com/problems/filling-bookcase-shelves/discuss/327207/Easy-Python-Solution | class Solution:
def minHeightShelves(self, books: List[List[int]], shelf_width: int) -> int:
if not books:
return 0
# dynamic programming
# key = (extra_width at the last level, last layer height)
# value = min_height
best = dict()
best[(shelf_width, 0)] = 0
for width, height in books:
new_best = dict()
for (width_left, level_height), total_height in best.items():
# start new level
key = (shelf_width - width, height)
val = total_height + height
if key in new_best:
new_best[key] = min(new_best[key], val)
else:
new_best[key] = val
# use current level
if width <= width_left:
key = (width_left - width, max(height, level_height))
val = total_height + max(height, level_height) - level_height
if key in new_best:
new_best[key] = min(new_best[key], val)
else:
new_best[key] = val
best = new_best
return min(best.values()) | filling-bookcase-shelves | Easy Python Solution | liveclass | 0 | 283 | filling bookcase shelves | 1,105 | 0.592 | Medium | 17,464 |
https://leetcode.com/problems/parsing-a-boolean-expression/discuss/1582694/One-pass-with-stack-97-speed | class Solution:
operands = {"!", "&", "|", "t", "f"}
values = {"t", "f"}
def parseBoolExpr(self, expression: str) -> bool:
stack = []
for c in expression:
if c == ")":
val = stack.pop()
args = set()
while val in Solution.values:
args.add(val)
val = stack.pop()
if val == "!":
stack.append("f" if "t" in args else "t")
elif val == "&":
stack.append("f" if "f" in args else "t")
elif val == "|":
stack.append("t" if "t" in args else "f")
elif c in Solution.operands:
stack.append(c)
return stack[0] == "t" | parsing-a-boolean-expression | One pass with stack, 97% speed | EvgenySH | 2 | 142 | parsing a boolean expression | 1,106 | 0.585 | Hard | 17,465 |
https://leetcode.com/problems/parsing-a-boolean-expression/discuss/2583900/Python-Iterative-O(n)-Solution | class Solution:
def parseBoolExpr(self, expression: str) -> bool:
logics = []
stack = []
def cal(tmp, top, op):
if op == '!':
tmp = 't' if tmp == 'f' else 'f'
elif op == '&':
tmp = 't' if (tmp == 't' and top == 't') else 'f'
elif op == '|':
tmp = 't' if (tmp == 't' or top == 't') else 'f'
return tmp
for i in expression:
if i in ('!', '&', '|'):
logics.append(i)
elif i == ')':
op = logics.pop()
tmp = stack.pop()
while stack:
top = stack.pop()
# print(tmp, top, op)
if op == '!' and top == '(': tmp = cal(tmp, tmp, op)
if top == '(': break
tmp = cal(tmp, top, op)
stack.append(tmp)
elif i == ',': continue
else:
stack.append(i)
# print(stack, logics, i)
if logics:
op = logics.pop()
tmp = stack.pop()
while stack:
top = stack.pop()
tmp = cal(tmp, top, op)
stack.append(tmp)
return True if stack[0] == 't' else False
# Time: O(N)
# Space: O(N) | parsing-a-boolean-expression | [Python] Iterative O(n) Solution | samirpaul1 | 1 | 57 | parsing a boolean expression | 1,106 | 0.585 | Hard | 17,466 |
https://leetcode.com/problems/parsing-a-boolean-expression/discuss/1694311/Python-3-Simple-solution | class Solution:
def parseBoolExpr(self, expression: str) -> bool:
# eval function would treat f and t as variables. Assign False and True to them.
f = False
t = True
# convert | into an OR function
def or_op(*args):
return reduce(lambda x,y:x or y, args)
# convert & into an AND function
def and_op(*args):
return reduce(lambda x,y : x and y, args)
# no need to create a not function as ! only takes one argument anyway
# replace & and | with the function names. And run eval
return eval(expression.replace('|','or_op').replace('&', 'and_op').replace('!', 'not')) | parsing-a-boolean-expression | {Python 3] Simple solution | kaustav43 | 0 | 93 | parsing a boolean expression | 1,106 | 0.585 | Hard | 17,467 |
https://leetcode.com/problems/parsing-a-boolean-expression/discuss/1471120/Python3-Solution-with-using-stack | class Solution:
def parseBoolExpr(self, expression: str) -> bool:
d_val = {'t': True, 'f': False}
d_reverse_val = {True: 't', False: 'f'}
stack = []
for exp in expression:
if exp == ')':
args = []
while stack[-1] != '(':
args.append(stack.pop())
# pop (
stack.pop()
# pop operation
op = stack.pop()
if op == '!':
stack.append(d_reverse_val[not d_val[args[0]]])
if op == '&':
val = d_val[args[0]]
for arg in args[1:]:
val = val and d_val[arg]
stack.append(d_reverse_val[val])
if op == '|':
val = d_val[args[0]]
for arg in args[1:]:
val = val or d_val[arg]
stack.append(d_reverse_val[val])
elif exp != ',':
stack.append(exp)
return d_val[stack[0]] | parsing-a-boolean-expression | [Python3] Solution with using stack | maosipov11 | 0 | 41 | parsing a boolean expression | 1,106 | 0.585 | Hard | 17,468 |
https://leetcode.com/problems/parsing-a-boolean-expression/discuss/1176869/Python3-2-stacks | class Solution:
def parseBoolExpr(self, expression: str) -> bool:
t = f = 0
operators, operands = [], []
for x in expression:
if x in "!&|": # operator
operators.append(x)
operands.append([t, f])
t = f = 0
elif x == "t": t += 1
elif x == "f": f += 1
elif x == ")":
op = operators.pop()
if op == "!" and t or op == "&" and f or op == "|" and not t: t, f = 0, 1
else: t, f = 1, 0
tt, ff = operands.pop()
t, f = t+tt, f+ff
return t | parsing-a-boolean-expression | [Python3] 2 stacks | ye15 | 0 | 47 | parsing a boolean expression | 1,106 | 0.585 | Hard | 17,469 |
https://leetcode.com/problems/parsing-a-boolean-expression/discuss/1063549/Recursion-Python | class Solution:
def parseBoolExpr(self, expression: str) -> bool:
"""
Recursive definition:
Two types of input:
1- op(args) -> return op[f(arg1), f(arg2), ...]
2- arg -> return bool(arg)
"""
def parse_args(expression):
current_arg = ''
open_count = 0
args = []
for c in expression:
if c in {'f','t'}:
current_arg +=c
if open_count == 0:
args.append(current_arg)
current_arg = ''
if c in {'!','|','&'}:
current_arg += c
if c == ',' and open_count!=0:
current_arg +=c
if c == '(':
current_arg += c
open_count +=1
if c == ')':
current_arg +=c
open_count -= 1
if open_count == 0:
args.append(current_arg)
current_arg = ''
return args
bool_mp = {'f': False, 't': True}
if len(expression) == 1:
return bool_mp[expression]
if expression[0] == '!':
return not self.parseBoolExpr(expression[2:-1])
if expression[0] == '|':
args = parse_args(expression[2:-1])
return any(self.parseBoolExpr(arg) for arg in args)
if expression[0] == '&':
args = parse_args(expression[2:-1])
return all(self.parseBoolExpr(arg) for arg in args) | parsing-a-boolean-expression | Recursion - Python | abdelkareem | 0 | 113 | parsing a boolean expression | 1,106 | 0.585 | Hard | 17,470 |
https://leetcode.com/problems/parsing-a-boolean-expression/discuss/330902/Python3-BitwiseandStack-with-explanation | class Solution:
def parseBoolExpr(self, expression: str) -> bool:
# 0b0000 - ' '
# 0b0100 - '!'
# 0b1000 - '&'
# 0b1100 - '|'
# 0b0010 (2) - if t in expression
# 0b0001 (1) - if f in expression
d = { 0b0110:1, 0b0101:2,
0b1010:2, 0b1001:1, 0b1011:1,
0b1110:2, 0b1101:1, 0b1111:2,
0b0010:True, 0b0001:False }
levels = [0]
for x in expression:
if x == ',' or x == "(":
continue
elif x == 't':
levels[-1] |= 2
elif x == 'f':
levels[-1] |= 1
elif x == ')':
level = levels.pop()
levels[-1] |= d[level]
elif x =='!':
levels.append(0b0100)
elif x =='&':
levels.append(0b1000)
elif x =='|':
levels.append(0b1100)
return d[levels[0]] | parsing-a-boolean-expression | [Python3] Bitwise&Stack with explanation | vilchinsky | 0 | 71 | parsing a boolean expression | 1,106 | 0.585 | Hard | 17,471 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/1697285/Python-code%3A-Defanging-an-IP-Address | class Solution:
def defangIPaddr(self, address: str) -> str:
address=address.replace(".","[.]")
return address | defanging-an-ip-address | Python code: Defanging an IP Address | Anilchouhan181 | 3 | 78 | defanging an ip address | 1,108 | 0.893 | Easy | 17,472 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/941201/Python-Simple-Solution | class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace('.','[.]') | defanging-an-ip-address | Python Simple Solution | lokeshsenthilkumar | 3 | 338 | defanging an ip address | 1,108 | 0.893 | Easy | 17,473 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/941201/Python-Simple-Solution | class Solution:
def defangIPaddr(self, address: str) -> str:
return '[.]'.join(address.split('.')) | defanging-an-ip-address | Python Simple Solution | lokeshsenthilkumar | 3 | 338 | defanging an ip address | 1,108 | 0.893 | Easy | 17,474 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/1433164/Python-join-vs-replace-solution-one-liner | class Solution:
def defangIPaddr(self, address: str) -> str:
return '[.]'.join(address.split('.')) | defanging-an-ip-address | Python join vs replace solution one liner | vineetkrgupta | 2 | 278 | defanging an ip address | 1,108 | 0.893 | Easy | 17,475 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/1433164/Python-join-vs-replace-solution-one-liner | class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace(".", "[.]") | defanging-an-ip-address | Python join vs replace solution one liner | vineetkrgupta | 2 | 278 | defanging an ip address | 1,108 | 0.893 | Easy | 17,476 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2264290/Python3-O(n)-oror-O(n)-Runtime%3A-25ms-81.72ms-oror-Memory%3A-13.8mb-48.91 | class Solution:
# O(n) || O(n)
# Runtime: 25ms 81.72ms || Memory: 13.8mb 48.91%
def defangIPaddr(self, address: str) -> str:
newList = []
for char in address.split('.'):
newList += [char]
return '[.]'.join(newList)
# OR
return address.replace('.', '[.]') | defanging-an-ip-address | Python3 O(n) || O(n) # Runtime: 25ms 81.72ms || Memory: 13.8mb 48.91% | arshergon | 1 | 61 | defanging an ip address | 1,108 | 0.893 | Easy | 17,477 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/1809880/Python3-Faster-than-93-and-13.9-mb-memory-uses-single-lined-solution | class Solution:
def defangIPaddr(self, address: str) -> str:
return "".join("[.]" if i=="." else i for i in address) | defanging-an-ip-address | [Python3] Faster than 93% and 13.9 mb memory uses single lined solution | ankushbisht01 | 1 | 61 | defanging an ip address | 1,108 | 0.893 | Easy | 17,478 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/1306292/Python-Solution-3-different-ways | class Solution:
def defangIPaddr(self, address: str) -> str:
ret = []
for ch in address:
if ch == '.':
ret.append('[.]')
else:
ret.append(ch)
return "".join(ret) | defanging-an-ip-address | Python Solution 3 different ways | 5tigerjelly | 1 | 185 | defanging an ip address | 1,108 | 0.893 | Easy | 17,479 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/1306292/Python-Solution-3-different-ways | class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace('.','[.]') | defanging-an-ip-address | Python Solution 3 different ways | 5tigerjelly | 1 | 185 | defanging an ip address | 1,108 | 0.893 | Easy | 17,480 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/1306292/Python-Solution-3-different-ways | class Solution:
def defangIPaddr(self, address: str) -> str:
return '[.]'.join(address.split('.')) | defanging-an-ip-address | Python Solution 3 different ways | 5tigerjelly | 1 | 185 | defanging an ip address | 1,108 | 0.893 | Easy | 17,481 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/1083807/One-Liner-Python-Sweet-and-Simple-Solution | class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace('.','[.]') | defanging-an-ip-address | One Liner - Python Sweet and Simple Solution | aishwaryanathanii | 1 | 145 | defanging an ip address | 1,108 | 0.893 | Easy | 17,482 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/969113/Python3-Solution-No-named-methods | class Solution:
def defangIPaddr(self, address: str) -> str:
newStr = ""
for letter in address:
newStr += "[.]" if letter == "." else letter
return newStr | defanging-an-ip-address | Python3 Solution - No named methods | JuanRodriguez | 1 | 244 | defanging an ip address | 1,108 | 0.893 | Easy | 17,483 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/930093/python3-faster-than-99.78-and-99.98-less-memory | class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace('.','[.]') | defanging-an-ip-address | python3 faster than 99.78% and 99.98% less memory | mrockett | 1 | 127 | defanging an ip address | 1,108 | 0.893 | Easy | 17,484 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2841714/Python-solution | class Solution:
def defangIPaddr(self, address: str) -> str:
s1="[.]"
ot=""
l=list(address)
for i in l :
if(i=="."):
ot+=s1
else:
ot+=i
return ot | defanging-an-ip-address | Python solution | patelhet050603 | 0 | 3 | defanging an ip address | 1,108 | 0.893 | Easy | 17,485 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2832530/Fastest-and-Simplest-Python-Solution-Beats-99.9 | class Solution:
def defangIPaddr(self, address: str) -> str:
fresh = ""
for i in address:
if i != ".":
fresh += i
else:
fresh += "[.]"
return fresh | defanging-an-ip-address | Fastest and Simplest Python Solution - Beats 99.9% | PranavBhatt | 0 | 1 | defanging an ip address | 1,108 | 0.893 | Easy | 17,486 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2818455/PYTHON-Python-easy-solution-oror-One-line-solution | class Solution:
def defangIPaddr(self, address: str) -> str:
return "[.]".join(address.split(".")) | defanging-an-ip-address | [PYTHON] Python easy solution || One line solution | valera_grishko | 0 | 2 | defanging an ip address | 1,108 | 0.893 | Easy | 17,487 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2815454/Fast-and-Simple-Solution-Python | class Solution:
def defangIPaddr(self, address: str) -> str:
fresh = ""
for i in address:
if i != ".":
fresh += i
else:
fresh += "[.]"
return fresh | defanging-an-ip-address | Fast and Simple Solution - Python | PranavBhatt | 0 | 1 | defanging an ip address | 1,108 | 0.893 | Easy | 17,488 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2803666/1-line-and-easy-oror-Python | class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace('.','[.]') | defanging-an-ip-address | 1 line and easy || Python | Samandar_Abduvaliyev | 0 | 4 | defanging an ip address | 1,108 | 0.893 | Easy | 17,489 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2764666/simple-python-solution | class Solution:
def defangIPaddr(self, address: str) -> str:
address = address.split('.')
address = '[.]'.join(address)
return address | defanging-an-ip-address | simple python solution | ft3793 | 0 | 3 | defanging an ip address | 1,108 | 0.893 | Easy | 17,490 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2740048/Python3-Simple-Solution-98-faster | class Solution:
def defangIPaddr(self, address: str) -> str:
temp_str = ''
for item in address:
if item == '.':
temp_str += '[.]'
else:
temp_str += item
return temp_str | defanging-an-ip-address | Python3 Simple Solution 98% faster | MikheilU | 0 | 2 | defanging an ip address | 1,108 | 0.893 | Easy | 17,491 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2739887/Python-1-Liner-using-.replace() | class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace(".","[.]") | defanging-an-ip-address | Python 1-Liner using .replace() | ABBMM | 0 | 2 | defanging an ip address | 1,108 | 0.893 | Easy | 17,492 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2730773/2-methods-(Python)-Beats-90 | class Solution:
def defangIPaddr(self, address: str) -> str:
#BRUTE FORCE (BEATS 90 percent)
newAddress = ''
for i in address:
if i == '.':
newAddress += '[.]'
else:
newAddress += i
return newAddress
# One Liner Solution
#return address.replace('.', '[.]') | defanging-an-ip-address | 2 methods (Python) Beats %90 | EverydayScriptkiddie | 0 | 1 | defanging an ip address | 1,108 | 0.893 | Easy | 17,493 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2692994/Python-or-Replace-Method | class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace('.','[.]') | defanging-an-ip-address | Python | Replace Method | LakiDIV | 0 | 1 | defanging an ip address | 1,108 | 0.893 | Easy | 17,494 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2681714/PYTHON%3A-One-line-solution | class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace(".","[.]") | defanging-an-ip-address | PYTHON: One line solution | Hashir311 | 0 | 4 | defanging an ip address | 1,108 | 0.893 | Easy | 17,495 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2625024/python-solution-98.18-faster | class Solution:
def defangIPaddr(self, address: str) -> str:
li_address = list(address)
for i in range(len(li_address)):
if li_address[i] == ".":
li_address[i] = "[.]"
return "".join(li_address) | defanging-an-ip-address | python solution 98.18% faster | samanehghafouri | 0 | 18 | defanging an ip address | 1,108 | 0.893 | Easy | 17,496 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2531011/Basic-Python-Solution-(Creating-a-new-string) | class Solution:
def defangIPaddr(self, address: str) -> str:
defanged_address = '' # new string to store defanged copy of input string
for ch in address: # loop to check each character
if ch == '.':
defanged_address = defanged_address + '[.]' # all . -> [.]
else:
defanged_address = defanged_address + ch # else put char in string
return defanged_address | defanging-an-ip-address | Basic Python Solution (Creating a new string) | cVos | 0 | 7 | defanging an ip address | 1,108 | 0.893 | Easy | 17,497 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2509878/Python-one-line-code | class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace(".", "[.]") | defanging-an-ip-address | Python - one line code | xfuxad00 | 0 | 15 | defanging an ip address | 1,108 | 0.893 | Easy | 17,498 |
https://leetcode.com/problems/defanging-an-ip-address/discuss/2490546/Simple-python-code-with-explanation | class Solution:
def defangIPaddr(self, address: str) -> str:
#create an empty string
k = ""
#iterate over the letters in sting
for i in address:
#if letters is not .
if i != ".":
#then add it to k sting
k = k + i
#if letter is .
else:
#then add "[.]" to k
k = k + '[.]'
#after adding all return the k string
return k | defanging-an-ip-address | Simple python code with explanation | thomanani | 0 | 26 | defanging an ip address | 1,108 | 0.893 | Easy | 17,499 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.