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/complement-of-base-10-integer/discuss/1665639/Python-Intuitive-solution | class Solution:
def bitwiseComplement(self, n: int) -> int:
res = 0
complement = []
# handle corner case
if n == 0:
return 1
# update complement list with complement of each digit in reverse order
while n > 0:
if n & 1 == 0:
complement.append(1)
else:
complement.append(0)
n >>= 1
# obtain the result in decimal format
for i, c in enumerate(complement):
res += pow(2, i) * c
return res | complement-of-base-10-integer | Python Intuitive solution | pradeep288 | 0 | 57 | complement of base 10 integer | 1,009 | 0.619 | Easy | 16,500 |
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1665488/fast-simple-solution | class Solution:
def bitwiseComplement(self, n: int) -> int:
n_binary = []
if n==0: return 1
while n>0:
n_binary.append(n%2)
n= n//2
complement=[]
for i in n_binary[::-1]:
if i==0: complement.append(1)
else: complement.append(0)
res = 0
for i in complement:
res = res * 2 + int(i)
return res | complement-of-base-10-integer | fast simple solution | sc618445 | 0 | 21 | complement of base 10 integer | 1,009 | 0.619 | Easy | 16,501 |
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1665262/Python3-SHIFT-AND-XOR-(-)-Explained | class Solution:
def bitwiseComplement(self, n: int) -> int:
if not n: return 1
mask = 1
while n >= mask:
mask <<= 1
return (mask - 1) ^ n | complement-of-base-10-integer | ✔️ [Python3] SHIFT AND XOR (ᕗ ͠° ਊ ͠° )ᕗ, Explained | artod | 0 | 234 | complement of base 10 integer | 1,009 | 0.619 | Easy | 16,502 |
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1563395/Python3-dollarolution-(Faster-than-87) | class Solution:
def bitwiseComplement(self, n: int) -> int:
n = bin(n)[2:]
s = 0
for i in range(1,len(n)+1):
if n[-i] == '0':
s += 2 ** (i-1)
return s | complement-of-base-10-integer | Python3 $olution (Faster than 87%) | AakRay | 0 | 137 | complement of base 10 integer | 1,009 | 0.619 | Easy | 16,503 |
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1357624/python-3-solution | class Solution:
def bitwiseComplement(self, n: int) -> int:
if n==0:
return 1
no=bin(n)
ans=""
for i in range(2,len(no)):
if no[i]=='1':
ans+="0"
else:
ans+="1"
return int(ans,2) | complement-of-base-10-integer | python 3 solution | minato_namikaze | 0 | 43 | complement of base 10 integer | 1,009 | 0.619 | Easy | 16,504 |
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1084578/Python3-simple-%22one-liner%22-solution | class Solution:
def bitwiseComplement(self, N: int) -> int:
return int('1'*len(bin(N).replace('0b','')),2) - N | complement-of-base-10-integer | Python3 simple "one-liner" solution | EklavyaJoshi | 0 | 41 | complement of base 10 integer | 1,009 | 0.619 | Easy | 16,505 |
https://leetcode.com/problems/complement-of-base-10-integer/discuss/1057913/Python-Solution-XOR-or-Time-96-faster-or-Space-76-lesser | class Solution:
def bitwiseComplement(self, num: int) -> int:
bit_count = 0
temp_num = num
sum_of_bits = 0
while temp_num > 0:
temp_num = temp_num // 2
sum_of_bits += 2 ** bit_count
bit_count += 1
if sum_of_bits == 0:
sum_of_bits = 1
return num ^ sum_of_bits | complement-of-base-10-integer | Python Solution XOR | Time 96% faster | Space 76% lesser | sudonitin | 0 | 87 | complement of base 10 integer | 1,009 | 0.619 | Easy | 16,506 |
https://leetcode.com/problems/complement-of-base-10-integer/discuss/879964/Python-solution-with-bit-by-bit-check | class Solution:
def bitwiseComplement(self, N: int) -> int:
if not N:
return 1
curr, i, rslt = N, 0, 0
while curr:
rslt += ((curr & 1) ^ 1) << i
i += 1
curr >>= 1
return rslt | complement-of-base-10-integer | Python solution with bit by bit check | eroneko | 0 | 53 | complement of base 10 integer | 1,009 | 0.619 | Easy | 16,507 |
https://leetcode.com/problems/complement-of-base-10-integer/discuss/779272/Simple-Python-Faster-than-90 | class Solution:
def bitwiseComplement(self, N: int) -> int:
binum = bin(N)[2:]
rbin = ''
for i in binum:
if i == '1':
rbin += '0'
else:
rbin += '1'
return int(rbin,2) | complement-of-base-10-integer | Simple Python Faster than 90% | Venezsia1573 | 0 | 37 | complement of base 10 integer | 1,009 | 0.619 | Easy | 16,508 |
https://leetcode.com/problems/complement-of-base-10-integer/discuss/477274/Python3-96.99-(20-ms)100.00-(12.7-MB)-O(log-(n))-time-O(1)-space | class Solution:
def bitwiseComplement(self, N: int) -> int:
position_value = 1
ret = 0
if (N == 0):
return 1
while (N > 0):
if (not N & 1):
ret += position_value
N //= 2
position_value *= 2
return ret | complement-of-base-10-integer | Python3 96.99% (20 ms)/100.00% (12.7 MB) -- O(log (n)) time / O(1) space | numiek_p | 0 | 61 | complement of base 10 integer | 1,009 | 0.619 | Easy | 16,509 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/422213/Python-O(n)-6-Lines-beats-86-time | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
res , count = 0, [0] * 60
for one in range(len(time)):
index = time[one] % 60
res += count[(60 - index)%60] # %60 is for index==0
count[index] += 1
return res | pairs-of-songs-with-total-durations-divisible-by-60 | Python O(n) 6 Lines beats 86% time | macqueen | 26 | 1,900 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,510 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/1662512/Python-%3A-HashMapDictionary-or-Complexity-O(n) | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
HashMap = {}
pairs = 0
for t in time:
numMod = t % 60
if numMod == 0:
if 0 in HashMap:
pairs += HashMap[0]
elif (60 - numMod) in HashMap:
pairs += HashMap[60 - numMod]
if numMod in HashMap:
HashMap[numMod] += 1
else:
HashMap[numMod] = 1
return pairs | pairs-of-songs-with-total-durations-divisible-by-60 | Python : HashMap/Dictionary | Complexity O(n) | yashitanamdeo | 17 | 1,400 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,511 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/1660754/Python3-HASHMAP-Explained | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
hashmap = defaultdict(int)
for t in time:
hashmap[t%60] += 1
res = 0
for t in time:
reminder = t%60
hashmap[reminder] -= 1
res += hashmap[0 if reminder == 0 else 60 - reminder]
return res | pairs-of-songs-with-total-durations-divisible-by-60 | ✔️[Python3] HASHMAP, °‿‿° Explained | artod | 5 | 710 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,512 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/1945160/Most-efficient-python-solution-that-beats-95-solutions. | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
ans=0
cnt={}
for t in time:
if t%60 in cnt:
cnt[t%60]+=1
else:
cnt[t%60]=1
ans+=(cnt.get(0,0)*(cnt.get(0,0)-1)//2)+(cnt.get(30,0)*(cnt.get(30,0)-1)//2)
for i in range(1,30):
ans+=cnt.get(i,0)*cnt.get(60-i,0)
return ans | pairs-of-songs-with-total-durations-divisible-by-60 | Most efficient python solution that beats 95% solutions. | tkdhimanshusingh | 3 | 384 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,513 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/2004218/PYTHON-SOL-oror-HASHMAP-%2B-MOD-oror-INTUTION-EXPLAINED-oror-APPROACH-EXPLAINED-oror | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
map = defaultdict(int)
ans = 0
for t in time:
if t % 60 == 0:
t = 60
ans += map[60]
else:
t = t % 60
ans += map[60-t]
map[t] += 1
return ans | pairs-of-songs-with-total-durations-divisible-by-60 | PYTHON SOL || HASHMAP + MOD || INTUTION EXPLAINED || APPROACH EXPLAINED || | reaper_27 | 2 | 234 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,514 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/2519609/Python-Solution | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
arr=[0]*60
count=0
for i in range(len(time)):
temp=time[i]%60
count+=arr[-temp%60]
arr[temp]+=1
return count | pairs-of-songs-with-total-durations-divisible-by-60 | Python Solution | Siddharth_singh | 1 | 545 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,515 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/2114620/Efficient-solution-O(N)-Time-and-O(1)-Space | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
d = defaultdict(int)
for i in range(len(time)):
time[i]%=60
d[time[i]]+=1
ans = 0
for i in set(time):
val = 60 - i
if val == i or val == 60:
ans += ((d[i]*(d[i]-1))//2)
else:
ans += (d[val]*d[i])
d[val] = d[i] = 0
return ans | pairs-of-songs-with-total-durations-divisible-by-60 | Efficient solution O(N) Time & O(1) Space | divyamohan123 | 1 | 216 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,516 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/1846048/Python3-easy-to-understand-solution | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
cnt = 0
rem2count = defaultdict(int)
for i in range(len(time)):
rem = time[i] % 60
if rem == 0:
cnt += rem2count[0]
else:
cnt += rem2count[60 - rem]
rem2count[rem] += 1
return cnt | pairs-of-songs-with-total-durations-divisible-by-60 | Python3 easy to understand solution | aaron17 | 1 | 141 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,517 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/1082465/Python-Map-and-Counter-beats-99 | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
d = map(mod, time, [60]*len(time))
c = Counter(d)
count = 0
for i in range(1, 30):
count += c[i] * c[60-i]
count += c[30] * (c[30]-1) // 2
count += c[0] * (c[0]-1) // 2
return count | pairs-of-songs-with-total-durations-divisible-by-60 | Python, Map and Counter, beats 99% | waltersm1 | 1 | 260 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,518 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/919019/Python-easy-solution-with-counter | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
time = [t % 60 for t in time] # (t1 + t2) % 60 == 0 iff (t1 % 60 + t2 % 60) == 0
c = Counter(time)
output = 0
for t in time:
if t == 0 or t == 30:
output += (c[t] - 1) # We don't want to count t itself
else:
output += c[60 - t]
return output // 2 # The question asks for only pairs where i < j, here output is double counting the pairs | pairs-of-songs-with-total-durations-divisible-by-60 | Python easy solution with counter | zimba12 | 1 | 209 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,519 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/2818558/Dictionary-solution-easy-understanding | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
lookup = defaultdict(int)
count = 0
for i in range(len(time)):
current = time[i] % 60
target = (60 - time[i] % 60) % 60
if target in lookup:
count = count + lookup[target]
lookup[current] = lookup[current] + 1
return count | pairs-of-songs-with-total-durations-divisible-by-60 | Dictionary solution - easy understanding | lanran8258 | 0 | 9 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,520 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/2812419/Python-clean-solution | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
ref = {}
c = 0
for i in time:
val = i % 60
if i % 60 ==0:
c += ref.get(0, 0)
else:
c += ref.get(60-i%60, 0)
if val in ref:
ref[val] += 1
else:
ref[val] = 1
return c | pairs-of-songs-with-total-durations-divisible-by-60 | Python clean solution | champ- | 0 | 7 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,521 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/2763796/Easy | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
d = collections.defaultdict(int)
c = 0
for t in time:
if t%60 == 0:
c += d[0]
else:
c += d[60-t%60]
d[t%60] += 1
return c | pairs-of-songs-with-total-durations-divisible-by-60 | Easy | wakadoodle | 0 | 9 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,522 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/2707316/Simple-Python-o(n)-with-explanation. | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
# when dividing with 60 the possible remainders are 0 to 59
# since we need to find all x + y s.t (x+y) % 60 == 0
# if we find that y % 60 = 3 (say)
# then if we can find x s.t x % 60 = 60 - 3
# then we found a pair, since this would mean y had a portion that was divisible
# by 60 plus 3 and so we need some other value that is made up of a portion
# that is divisible by 60 plus 57 to match with the portion of x that wasn't divisble
# by 60 i.e 3
# however, if y % 60 == 0, then we need to find x s.t x % 60 is also 0
track = [0] * 60
res = 0
for t in time:
r = t % 60
if r:
res += track[60 - r]
else:
res += track[0]
track[r] += 1
return res | pairs-of-songs-with-total-durations-divisible-by-60 | Simple Python o(n) with explanation. | rasnouk | 0 | 35 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,523 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/2427030/pair-of-songs-divisible-by-60-oror-Python3-oror-hashmap | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
hm = {}
ans = 0
for i in range(len(time)):
rem = time[i]%60
target_rem = 60 - rem
if(target_rem == 60):
target_rem = 0
if(target_rem in hm):
ans += hm[target_rem]
if rem in hm:
hm[rem] += 1
else:
hm[rem] = 1
return ans | pairs-of-songs-with-total-durations-divisible-by-60 | pair of songs divisible by 60 || Python3 || hashmap | vanshika_2507 | 0 | 148 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,524 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/2313728/Python-beats-%2B-easy-to-understand | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
count, d = 0, defaultdict(int)
for t in time:
tail = t % 60
count += d[0 if tail == 0 else 60 - tail]
d[tail] += 1
return count | pairs-of-songs-with-total-durations-divisible-by-60 | Python beats 𝟵𝟵 % + easy to understand | amaargiru | 0 | 284 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,525 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/2197815/pthon3-or-O(N) | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
dic={}
result=0
for i in range(len(time)):
ans=time[i]%60
if dic.__contains__(ans):
dic[ans].append(i)
else:
dic[ans]=[i]
for i,j in dic.items():
if i==0:
temp=0
else:
temp=60-i
if dic.__contains__(temp):
a=j
b=dic[temp]
if a==b:
n=len(a)
ans=int((((n-1)*(n-1))+(n-1))/2)
result+=ans
else:
ans=len(a)*len(b)
result+=ans
dic[i]=[]
dic[temp]=[]
return(result) | pairs-of-songs-with-total-durations-divisible-by-60 | pthon3 | O(N) | shahv74 | 0 | 137 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,526 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/2185710/python-3-or-two-lines-or-O(n)O(1) | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
modCount = collections.Counter(duration % 60 for duration in time)
return (math.comb(modCount[0], 2) + math.comb(modCount[30], 2) +
sum(modCount[i] * modCount[60 - i] for i in range(1, 30))) | pairs-of-songs-with-total-durations-divisible-by-60 | python 3 | two lines | O(n)/O(1) | dereky4 | 0 | 254 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,527 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/2132702/Python3-Very-simple-O(N)-solution-using-hash-map | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
## RC ##
## APPROACH : HASHMAP ##
hmap = collections.defaultdict(int)
ans = 0
for t in time:
# when remainder is 0
if t % 60 == 0:
ans += hmap[0]
if (60 - (t % 60)) in hmap:
ans += hmap[(60 - (t % 60))]
hmap[t % 60] += 1
return ans | pairs-of-songs-with-total-durations-divisible-by-60 | [Python3] Very simple O(N) solution using hash map | 101leetcode | 0 | 122 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,528 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/1767774/Easy-to-understand-module-solution | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
r = [0] * 60
out = 0
for ct in time:
m = ct % 60
if m == 0:
out += r[0]
r[0] += 1
else:
t = 60 - m
out += r[t]
r[m] += 1
return out | pairs-of-songs-with-total-durations-divisible-by-60 | Easy to understand module solution | faang_aspirant | 0 | 87 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,529 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/1662696/Python-dictionary-or-Time-O(n)-Space-O(1)-or-faster-than-92.03-of-Python3-online-submissions | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
d = {}
for t in time:
t = t%60
if t in d:
d[t] += 1
else:
d[t] = 1
res = 0
if 0 in d:
x = d[0] - 1
res += (x*(x+1))//2
del d[0]
keys = list(d.keys())
for k in keys:
if k in d:
x = d[k]
del d[k]
rk = 60 - k
y = 0
if rk in d:
y = d[rk]
del d[rk]
if x and y:
res += x*y
elif k == rk:
x -= 1
res += (x*(x+1))//2
return res | pairs-of-songs-with-total-durations-divisible-by-60 | Python dictionary | Time O(n), Space O(1) | faster than 92.03% of Python3 online submissions | belal_bh | 0 | 105 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,530 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/1661845/Python-C%2B%2B-O(n)-solution-w-explanation-greater-beats-85.71-time-88.22-memory | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
needed_dict = dict()
count = 0
for i in time:
remainder = i % 60
if remainder in needed_dict:
count += needed_dict[remainder]
needed = (60 - remainder) % 60
if needed in needed_dict:
needed_dict[needed] += 1
else:
needed_dict[needed] = 1
return count
# O(n) time, O(r) -> r being unique remainders we find
# beats 85.71% time, 88.22% memory
# Mateo Ruiz
# 2 January 2022 | pairs-of-songs-with-total-durations-divisible-by-60 | [Python, C++] O(n) solution w explanation -> beats 85.71% time, 88.22% memory | mateoruiz5171 | 0 | 80 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,531 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/1661809/Python-3-Solution-Linear-Time | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
ans=0
lookup={}
for i in time:
if i%60 in lookup:
lookup[i%60]+=1
else:
lookup[i%60]=1
for i in lookup:
if i==30 or i==0:
if lookup[i]>1:
p=(lookup[i]*(lookup[i]-1))//2
ans+=p
lookup[i]=0
elif 60-i in lookup and lookup[60-i]>0:
ans+=lookup[i]*lookup[60-i]
lookup[i]=0
lookup[60-i]=0
return ans | pairs-of-songs-with-total-durations-divisible-by-60 | Python 3 Solution Linear Time | aryanagrawal2310 | 0 | 90 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,532 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/1660752/python3-dict-ez-solution-on | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
cache = dict()
for t in time:
if t%60 not in cache:
cache[t%60] = 1
else:
cache[t%60] += 1
output = 0
for i in range(1,30):
if i in cache and 60-i in cache:
output += cache[60-i]*cache[i]
if 30 in cache:
output += cache[30] * (cache[30] - 1) // 2
if 0 in cache:
output += cache[0] * (cache[0] - 1) // 2
return int(output) | pairs-of-songs-with-total-durations-divisible-by-60 | python3 dict ez solution on | yingziqing123 | 0 | 47 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,533 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/1499735/Runtime-faster-than-91.92-Memory-Usage-less-than-97.64 | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
for i in range(len(time)):
time[i]=time[i]%60
res={}
for t in time:
if t not in res:
res[t]=1
else:
res[t]+=1
ans=0
for k in res.keys():
if k==0:
ans+=res[0]*(res[0]-1)
elif k==30:
ans+=res[k]*(res[k]-1)
elif 60-k in res.keys():
ans+=res[k]*res[60-k]
return int(ans/2) | pairs-of-songs-with-total-durations-divisible-by-60 | Runtime faster than 91.92% , Memory Usage less than 97.64% | narry | 0 | 123 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,534 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/1288813/Python3-easy-to-understand-beat-96 | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
counter = 0
for i in range(len(time)):
time[i] %= 60
if time[i] == 0:
counter += 1
ans = counter * (counter - 1) // 2
m = {}
for i in time:
if (60 - i) in m:
ans += m[60 - i]
if i in m:
m[i] += 1
else:
m[i] = 1
return ans | pairs-of-songs-with-total-durations-divisible-by-60 | Python3 easy to understand beat 96% | ScoutBoi | 0 | 304 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,535 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/1219915/Python3-Simple-Approach-with-Comments-beats-95-in-Running-Time | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
# Initialize a dictionary to store the count of mod(duration,60) for each duration in 'time'
mod_cnt = {i:0 for i in range(0,60)}
# Update the dictionary entries
for slot in time:
mod_cnt[slot%60]+=1
cnt = 0
# Let d1 and d2 be two durations. If mod(d1,60) = x and mod(d2,60) = 60-x, then the total duration of (d1,d2) pair is divisible 60
# For x is from 1 to 29, if mod_cnt[x]=l1 and mod_cnt[60-x]=l2, then the total number of combinations from key x is l1*l2
for i in range(1,30):
cnt+=mod_cnt[i]*mod_cnt[60-i]
# If mod_cnt[0]=l1, then the total number of combinations from key 0 is (l1,2) = (l1*(l1-1))/2
# Similarly, if mod_cnt[30]=l1, then the total number of combinations from key 30 is (l1,2) = (l1*(l1-1))/2
cnt+=(mod_cnt[0]*(mod_cnt[0]-1))//2
cnt+=(mod_cnt[30]*(mod_cnt[30]-1))//2
return cnt | pairs-of-songs-with-total-durations-divisible-by-60 | Python3 Simple Approach, with Comments, beats 95% in Running Time | bPapan | 0 | 135 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,536 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/1186004/python-dict-O(N) | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
if not time or len(time) <= 1:
return 0
mod2cnt = dict()
for mod in range(60):
mod2cnt[mod] = 0
for t in time:
mod2cnt[t % 60] += 1
cnt = 0
for mod in range(31):
if mod in {0, 30}:
cnt += mod2cnt[mod] * (mod2cnt[mod] - 1) // 2
else:
cnt += mod2cnt[mod] * mod2cnt[60 - mod]
return cnt | pairs-of-songs-with-total-durations-divisible-by-60 | python dict O(N) | happyBo2020 | 0 | 132 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,537 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/964819/PYTHON-oror-EASY-oror-FAST-oror-O(1)-SPACE-oror-O(N)-TIME | class Solution(object):
def sumOfN(self, n):
return n * (n + 1) // 2
def numPairsDivisibleBy60(self, time):
ans = [0] * 60
for t in time:
ans[t%60] += 1
pair = 0
for i in range(1,30):
pair = pair+ (ans[i] * ans[60-i])
return pair + self.sumOfN(ans[0] - 1) + self.sumOfN(ans[30] - 1) | pairs-of-songs-with-total-durations-divisible-by-60 | PYTHON || EASY || FAST || O(1) SPACE || O(N) TIME | akashgkrishnan | 0 | 350 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,538 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/964709/Python-O(N)-time-complexity | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
c=0
d=dict()
for i in time:
try:
d[i%60]+=1
except:
d[i%60]=1
for i in range(1,30):
try:
c+=d[i]*d[60-i]
except:
pass
try:
c+=d[30]*(d[30]-1)//2
except:
pass
try:
c+=d[0]*(d[0]-1)//2
except:
pass
return c | pairs-of-songs-with-total-durations-divisible-by-60 | Python O(N) time complexity | keshavsingh4522 | 0 | 137 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,539 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/955359/Python3-PrefixSum-Explained | class Solution:
"""
time = [duration_1, duration_2, ...]
Want all duration_i and duration_j where i < j and:
- duration_i + duration_j = 60*n, where n is an integer
--> duration_i = 60*n - duration_j
===> mod both sides by 60 <===
--> duration_i % 60 = (60*n - duration_j) % 60
===> distribute mod 60 on right side <===
--> duration_i % 60 = (60*n % 60 - duration_j % 60) % 60
===> 60*n % 60 cancels out <===
--> duration_i % 60 = (-duration_j % 60) % 60
===> mod property: (a % b) % b = a % b <===
**** duration_i % 60 = -duration_j % 60 ****
For every duration after the first one:
- Check if duration_j % 60 key is in the hash_map,
and if so add the value of -duration_j % 60 key to num_pairs
- Increment the duration_i % 60 key by 1
"""
def numPairsDivisibleBy60(self, time: List[int]) -> int:
if len(time) < 2:
return 0
key_map = defaultdict(int)
key_map[time[0] % 60] += 1
num_pairs = 0
for duration in time[1:]:
key = -duration % 60
num_pairs += key_map[key]
key_map[duration % 60] += 1
return num_pairs | pairs-of-songs-with-total-durations-divisible-by-60 | Python3 PrefixSum Explained | nyc_coder | 0 | 126 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,540 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/343250/Solution-in-Python-3-(beats-100)-(2-lines) | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
T = collections.Counter([i % 60 for i in time])
return sum([T[i]*T[60-i] for i in range(1,30)])+(T[0]*(T[0]-1)+T[30]*(T[30]-1))//2
- Python 3
- Junaid Mansuri | pairs-of-songs-with-total-durations-divisible-by-60 | Solution in Python 3 (beats 100%) (2 lines) | junaidmansuri | 0 | 1,600 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,541 |
https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/337279/Python-solution-using-dictionary | class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
count=0
d={}
for i in time:
k=i%60
if k in d:
d[k]+=[i]
else:
d[k]=[i]
for i in d:
if i==30 or i==0 :count+=int(((len(d[i])**2)-len(d[i]))//2)
elif 60-i in d:
count+=len(d[i])*len(d[60-i])
d[i]=[]
d[60-i]=[]
return count | pairs-of-songs-with-total-durations-divisible-by-60 | Python solution using dictionary | ketan35 | 0 | 567 | pairs of songs with total durations divisible by 60 | 1,010 | 0.529 | Medium | 16,542 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/1581292/Well-Explained-oror-Thought-process-oror-94-faster | class Solution:
def shipWithinDays(self, weights: List[int], D: int) -> int:
def feasible(capacity):
days = 1
local = 0
for w in weights:
local+=w
if local>capacity:
local = w
days+=1
if days>D:
return False
return True
left, right = max(weights), sum(weights)
while left < right:
mid = left + (right-left)//2
if feasible(mid):
right = mid
else:
left = mid + 1
return left | capacity-to-ship-packages-within-d-days | 📌📌 Well-Explained || Thought process || 94% faster 🐍 | abhi9Rai | 31 | 1,900 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,543 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/1511827/Python-Simple-Binary-Search-Solution-with-Explanation | class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
def isEnough(capacity): #helper function, to check if given capacity is enough
count = 1
max_weight = capacity
for weight in weights:
if weight > max_weight:
max_weight = capacity
count += 1
max_weight -= weight
return True if count <= days else False
left, right = max(weights), sum(weights)
while left < right:
mid = left + (right - left) // 2
if isEnough(mid):
right = mid
else:
left = mid + 1
return left | capacity-to-ship-packages-within-d-days | [Python] Simple Binary Search Solution with Explanation | Saksham003 | 8 | 380 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,544 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/1696923/Python-Solution-with-encapsulation-and-explanation-time-and-space-complexity | class Solution:
def shipWithinDays(self, weights, days):
min_capacity = max(weights)
max_capacity = sum(weights)
def search_best_capacity(min_capacity, max_capacity, days):
while min_capacity < max_capacity:
mid_capacity = (max_capacity + min_capacity) // 2
curr_days = calculate_days(weights, mid_capacity)
if curr_days > days:
min_capacity = mid_capacity + 1
else:
max_capacity = mid_capacity
return min_capacity
def calculate_days(weights, capacity):
load = 0
num_days = 1
for weight in weights:
if load + weight <= capacity:
load += weight
else:
num_days += 1
load = weight
return num_days
return search_best_capacity(min_capacity, max_capacity, days) | capacity-to-ship-packages-within-d-days | Python Solution with encapsulation and explanation, time & space complexity | gixo | 4 | 230 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,545 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/1601624/Very-simple-Python-Binary-Search-Solution-with-explanation | class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
def getNeededDays(kilos):
neededDays=1
shipmentSize=0
for package in weights:
if shipmentSize+package<=kilos:
shipmentSize+=package
else:
shipmentSize=package
neededDays+=1
return neededDays
def binarySearch(l,h):
while l<h:
kilos=(l+h)//2
if getNeededDays(kilos)<=days:
h=kilos
else:
l=kilos+1
return l
l=max(weights)
h=sum(weights)
return binarySearch(l,h) | capacity-to-ship-packages-within-d-days | Very simple Python 🐍 Binary Search Solution with explanation | InjySarhan | 4 | 284 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,546 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/1477566/Binary-search%2BGreedy-solution | class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
def feasible(capacity):
day=1
total=0
for weight in weights:
total+=weight
if total>capacity: #if there is no space in ship belt,go to next days
total=weight
day+=1
if day>days: #if total day exceeds the days
return False
return True
left,right=max(weights),sum(weights) #capacity should be at least max(weights) and capacity need not be more than sum(weights)
while left<right:
mid=left+(right-left)//2
if feasible(mid):
right=mid
else:
left=mid+1
return left | capacity-to-ship-packages-within-d-days | Binary search+Greedy solution | Qyum | 3 | 142 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,547 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/2004375/PYTHON-SOL-oror-BINARY-SEARCH-oror-INTUATIVE-oror-EXPLAINED-WELL-oror-FASToror | class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
# Question Like Binary search
def possible(limit):
cur = 1
tmp = 0
for i in weights:
if i + tmp > limit:
cur += 1
tmp = i
if cur > days :
return False
else:
tmp += i
return True
low = max(weights)
high = sum(weights)
ans = high
while low <= high:
mid = (low + high)//2
if possible(mid):
if mid < ans : ans = mid
high = mid - 1
else:
low = mid + 1
return ans | capacity-to-ship-packages-within-d-days | PYTHON SOL || BINARY SEARCH || INTUATIVE || EXPLAINED WELL || FAST|| | reaper_27 | 2 | 163 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,548 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/797151/Python3-binary-search-the-capacity-space | class Solution:
def shipWithinDays(self, weights: List[int], D: int) -> int:
def fn(cpty):
"""Return days to deliver all packages given ship of given capacity."""
ans, val = 0, inf # to trigger +1 upon first input
for w in weights:
if val + w > cpty: # overcapacity
ans += 1
val = 0
val += w
return ans <= D
# "first true" binary search
lo, hi = max(weights), sum(weights)
while lo < hi:
mid = lo + hi >> 1
if fn(mid): hi = mid
else: lo = mid + 1
return lo | capacity-to-ship-packages-within-d-days | [Python3] binary search the capacity space | ye15 | 2 | 164 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,549 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/259318/Binary-Search-on-Result-Range-Python-Solution | class Solution:
def shipWithinDays(self, weights: List[int], D: int) -> int:
# find the range
capacity_lower = max(weights)/2
capacity_upper = max(weights)/2
days_need = math.inf
while days_need > D:
capacity_upper = capacity_upper*2
days_need = self.get_days(weights, capacity_upper)
start = max(int(capacity_upper/2),max(weights))
end = int(capacity_upper)
# binary search to locate the one
while start + 1 < end:
mid = start + (end-start)//2
mid_days = self.get_days(weights, mid)
if mid_days > D:
start = mid
else:
end = mid
if self.get_days(weights, start) <= D:
return start
else:
return end
def get_days(self, weights, capacity):
# return days needed
temp = 0
days = 1
for i in range(len(weights)):
if temp + weights[i] <= capacity:
temp = temp + weights[i]
else:
days = days + 1
temp = weights[i]
return days | capacity-to-ship-packages-within-d-days | Binary Search on Result Range - Python Solution | bug-dva | 2 | 466 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,550 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/2383014/O(nlogn)-time-python3-Binary-Search-solution | class Solution:
# O(nlogn) time,
# O(1) space,
# Approach: Binary Search,
def shipWithinDays(self, weights: List[int], days: int) -> int:
def isWeightValid(w:int) -> bool:
tot = 0
rem_days = days-1
for weight in weights:
if weight > w: return False
if tot + weight > w:
if rem_days < 1: return False
rem_days -=1
tot = 0
tot += weight
return True
def binarySearchCapacity(start:int, end:int) -> int:
mid = (start + end)//2
weightIsValid = isWeightValid(mid)
if weightIsValid and (mid == 1 or not isWeightValid(mid-1)):
return mid
elif start >= end-1:
return end
elif not weightIsValid:
return binarySearchCapacity(mid, end)
else:
return binarySearchCapacity(start, mid)
return binarySearchCapacity(1, sum(weights)) | capacity-to-ship-packages-within-d-days | O(nlogn) time python3 Binary Search solution | destifo | 1 | 60 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,551 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/2837725/python-solution-binary-search-%2B-greedy | class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
# lower bound
# the minimum ship capacity has to be at least max(weights)
left = max(max(weights), sum(weights) // days)
right = sum(weights)
def helper(target):
d = 1
total = 0
for weight in weights:
if total + weight <= target:
total += weight
else:
d += 1
total = weight
if d <= days:
return True
return False
while left < right:
mid = left + (right - left) // 2
if helper(mid):
right = mid
else:
left = mid + 1
return left
# time is logW * N
# space is 1 | capacity-to-ship-packages-within-d-days | python solution binary search + greedy | kk_vv_kk | 0 | 1 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,552 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/2668137/Python-Solution-or-Binary-Search | class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
def isPossible(value):
s=0
count=0
for weight in weights:
s+=weight
if s>value:
s=weight
count+=1
if s>value:
return False
# print(count)
if count<days:
return True
return False
low=min(weights)
high=sum(weights)
ans=high
while low<=high:
mid=(low+high)//2
# print(mid)
if isPossible(mid):
ans=mid
# print(mid)
high=mid-1
else:
low=mid+1
# print(isPossible(15))
return ans | capacity-to-ship-packages-within-d-days | Python Solution | Binary Search | Siddharth_singh | 0 | 9 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,553 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/2658921/Capacity-to-Ship-Packages-within-D-Days | class Solution:
def capacity_posible(self, a, days, capacity):
d = 0
s = 0
i = 0
while i < len(a):
# if some day weight > capacity --we can't load that so not posible
if a[i] > capacity:
return False
while i < len(a) and s + a[i] <= capacity:
s += a[i]
i += 1
d += 1
s = 0
if d <= days:
return True
return False
def shipWithinDays(self, weights, days: int) -> int:
high = sum(weights)
low = 1
if days == 1: return high
while low <= high:
mid = (low + high) // 2
# if the mid capacity is posible --we can go lwft and find the min capacity posible
if self.capacity_posible(weights, days, mid):
high = mid - 1
else:
low = mid + 1
return low
print(Solution().shipWithinDays([1,2,3,4,5,6,7,8,9,10], 5))
print(Solution().shipWithinDays([3,2,2,4,1,4], 3))
print(Solution().shipWithinDays([1,2,3,1,1], 4)) | capacity-to-ship-packages-within-d-days | Capacity to Ship Packages within D Days | Ninjaac | 0 | 26 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,554 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/2559002/Python3-or-Binary-Search-on-Possible-Range-of-Ship-Weight-Capacity-Values | class Solution:
#Time-Complexity: O(n + log(total)*n) ->O(nlog(total))
#Space-Complexity: O(1)
def shipWithinDays(self, weights: List[int], days: int) -> int:
#number of packages
n = len(weights)
total = sum(weights)
#define helper that takes in the ship capacity weight value
#as single parameter and computes number of days required
#to ship all packages!
def helper(r):
nonlocal weights
days = 1
counter = 0
for weight in weights:
counter += weight
if(counter <= r):
continue
#otherwise, we exceeded limit.
else:
days += 1
#we have to check before resetting counter if
#the single package weight exceed ship limit! ->
#It's impossible to ship each and every package!
if(weight > r):
return None
counter = weight
return days
#our search space is going to be possible range of weight
#capacity values ranging from lowest as 1 to highest as total!
l, h = 1, total
ans = None
while l <= h:
mid = (l + h) // 2
#now check if current mid ship capacity weight restraint
#require number of days <= input requirement(days)!
num_days_needed = helper(mid)
#check if result of helper call equals None!
#We have to try higher values of ship weight capacity requirements!
if(num_days_needed == None):
l = mid + 1
continue
else:
if(num_days_needed <= days):
ans = mid
#look for even smaller constraint value by reducing
#search space to left half portion!
h = mid - 1
continue
else:
l = mid + 1
continue
return ans | capacity-to-ship-packages-within-d-days | Python3 | Binary Search on Possible Range of Ship Weight Capacity Values | JOON1234 | 0 | 10 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,555 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/2221563/Binnary-Search-Approach-oror-Easy-and-Simple-Code | class Solution:
def validateDays(self, mid, weights, n, requiredDays):
s = 0
days = 1
for i in range(n):
if s + weights[i] <= mid:
s += weights[i]
else:
s = weights[i]
days += 1
if days <= requiredDays:
return True
return False
def shipWithinDays(self, weights: List[int], days: int) -> int:
low = max(weights)
high = sum(weights)
n = len(weights)
minimumWeightCapacity = 0
while low <= high:
mid = low + (high - low)//2
if self.validateDays(mid, weights, n, days):
minimumWeightCapacity = mid
high = mid - 1
else:
low = mid + 1
return minimumWeightCapacity | capacity-to-ship-packages-within-d-days | Binnary Search Approach || Easy and Simple Code | Vaibhav7860 | 0 | 71 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,556 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/2183757/python-3-or-simple-binary-search | class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
def canShip(capacity):
load, d = 0, 1
for weight in weights:
load += weight
if load > capacity:
d += 1
load = weight
return d <= days
low, high = max(weights), sum(weights)
while low < high:
mid = (low + high) // 2
if canShip(mid):
high = mid
else:
low = mid + 1
return low | capacity-to-ship-packages-within-d-days | python 3 | simple binary search | dereky4 | 0 | 88 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,557 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/2069725/Python-Easy-to-understand-binary-search | class Solution(object):
def shipWithinDays(self, weights, days):
"""
:type weights: List[int]
:type days: int
:rtype: int
"""
def can_ship(cap):
total_days = 1
current_weight = 0
for weight in weights:
current_weight += weight
if current_weight > cap:
current_weight = weight
total_days += 1
return total_days <= days
left = max(weights)
right = sum(weights)
while left < right:
mid = left + (right-left) // 2
if can_ship(mid):
right = mid
else:
left = mid + 1
return right | capacity-to-ship-packages-within-d-days | [Python] Easy to understand binary search | dlog | 0 | 89 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,558 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/1969110/Binary-Search-oror-Python-oror-O(n*logn) | class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
low = max(weights)
high = sum(weights)
def liner(max_val):
summ,day = 0,1
for i in weights:
if summ+i <= max_val:
summ += i
else:
summ = i
day += 1
return day
while low<=high:
mid = (low+high)//2
if liner(mid) > days:
low = mid + 1
else:
high = mid - 1
return low | capacity-to-ship-packages-within-d-days | Binary Search || Python || O(n*logn) | gamitejpratapsingh998 | 0 | 120 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,559 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/1925832/9-Lines-Python-Solution-oror-70-Faster-oror-Memory-less-than-80 | class Solution:
def shipWithinDays(self, W: List[int], D: int) -> int:
lo=max(W) ; hi=sum(W)
while lo<hi:
mid=(lo+hi)//2 ; cur=0 ; days=1
for w in W:
if cur+w>mid: days+=1 ; cur=0
cur+=w
if days>D: lo=mid+1
else:hi=mid
return lo | capacity-to-ship-packages-within-d-days | 9-Lines Python Solution || 70% Faster || Memory less than 80% | Taha-C | 0 | 62 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,560 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/1855909/python3-or-binary-search | class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
def ispossible(mid,weights,days):
dayct=1
wieghtsum=0
for i in range(len(weights)):
if (wieghtsum+weights[i])<=mid:
wieghtsum+=weights[i]
else:
dayct+=1
if dayct>days or weights[i]>mid:
return False
wieghtsum=weights[i]
return True
s=0
e=sum(weights)
ans=-1
while s<=e:
mid=s+(e-s)//2
if ispossible(mid,weights,days):
ans=mid
e=mid-1
else:
s=mid+1
return ans | capacity-to-ship-packages-within-d-days | python3 | binary search | Anilchouhan181 | 0 | 87 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,561 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/1838968/Python-3-(700ms)-or-Book-Allocation-Pattern-or-Binary-Search-Approach | class Solution:
def shipWithinDays(self, num: List[int], d: int) -> int:
def isPossible(num,d,m):
ws,c=0,1
for i in range(len(num)):
if ws+num[i]<=m:
ws+=num[i]
else:
c+=1
if c>d or num[i]>m:
return False
ws=num[i]
return True
s,e,ans=0,sum(num),-1
while s<=e:
m=s+(e-s)//2
if isPossible(num,d,m):
ans=m
e=m-1
else:
s=m+1
return ans | capacity-to-ship-packages-within-d-days | Python 3 (700ms) | Book Allocation Pattern | Binary Search Approach | MrShobhit | 0 | 78 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,562 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/1632305/Python3-Binary-Search-100-fast | class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
def calculate_days(ship):
ret = 1
carry = 0
for w in weights:
if w + carry > ship:
ret += 1
carry = w
else:
carry += w
return ret
min_ship, max_ship = max(int(sum(weights)/days), max(weights)), max(weights)*(int(len(weights)/days) + 1)
while min_ship < max_ship:
mid_ship = (min_ship + max_ship) // 2
mid_day = calculate_days(mid_ship)
if mid_day > days:
min_ship = mid_ship + 1
else:
max_ship = mid_ship
return min_ship | capacity-to-ship-packages-within-d-days | Python3 Binary Search 100% fast | BichengWang | 0 | 119 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,563 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/1379179/Python3-or-Binary-Search | class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
low=max(weights) #minimum capacity
high=sum(weights) #maximum capacity such that all shipped in 1 day
while low<high:
mid=(low+high)>>1
k1=self.capacity(mid,weights)
if k1>days: #if need days > given days we need to increase capacity
low=mid+1
elif k1<=days: # if need days < given days then decrease capacity till mid as mid can be one possible answer
high=mid
return low #return lower bound as we have to find minimum capacity
def capacity(self,cap,weights):
temp=0
cnt=1
for i in range(len(weights)):
temp+=weights[i]
if temp>cap:
cnt+=1
temp=weights[i]
return cnt | capacity-to-ship-packages-within-d-days | Python3 | Binary Search | swapnilsingh421 | 0 | 58 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,564 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/1275728/python-or-binary-search-or-faster-than-98 | class Solution:
def shipWithinDays(self, weights: List[int],d: int) -> int:
#n=len(weights)
h=sum(weights)
l=max(weights)
def fun(mid):
ans=1
count=0
for i in weights:
count+=i
if count>mid:
ans+=1
count=i
return ans
ans=8765437654
while(l<=h):
mid=(l+h)//2
#print(l,h,mid)
p=fun(mid)
print(p)
if p<=d:
ans=min(ans,mid)
h=mid-1
else:
l=mid+1
return ans | capacity-to-ship-packages-within-d-days | python | binary search | faster than 98% | heisenbarg | 0 | 116 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,565 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/1162177/binary-search-for-python | class Solution:
def shipWithinDays(self, weights: List[int], D: int) -> int:
min_cap, max_cap = max(weights), sum(weights)
index = -1
self.length = len(weights)
def can_finish(cap):
tmp = 0
days = 0
for i in range(self.length):
tmp += weights[i]
if tmp == cap:
days += 1
tmp = 0
elif tmp > cap:
days += 1
tmp = weights[i]
if tmp != 0 and i == len(weights) - 1:
days += 1
tmp = 0
return days <= D
while min_cap <= max_cap:
mid = min_cap + (max_cap - min_cap) // 2
if can_finish(mid):
max_cap = mid - 1
index = mid
else:
min_cap = mid + 1
return index | capacity-to-ship-packages-within-d-days | binary-search for python | faris-shi | 0 | 76 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,566 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/1157001/Runtime%3A-492-ms-faster-than-85.83-of-Python3-.-Memory-Usage%3A-17.7-MB-less-than-59.60-of-Python3 | class Solution:
def shipWithinDays(self, weights: List[int], D: int) -> int:
maxa=max(weights)
suma=sum(weights)
while maxa<suma:
agrigate=(maxa+suma)//2
strr=0
counting=1
for weight in weights:
strr+=weight
if strr>agrigate:
strr=weight
counting += 1
if counting>D:
maxa=agrigate+1
else:
suma=agrigate
return maxa | capacity-to-ship-packages-within-d-days | Runtime: 492 ms, faster than 85.83% of Python3 . Memory Usage: 17.7 MB, less than 59.60% of Python3 | aashutoshjha21022002 | 0 | 188 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,567 |
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/650509/Python3-beats-97-Capacity-To-Ship-Packages-Within-D-Days | class Solution:
def shipWithinDays(self, weights: List[int], D: int) -> int:
def canShip(capacity: int) -> bool:
nonlocal D
count = 1
loaded = 0
for w in weights:
if loaded + w <= capacity:
loaded += w
else:
count += 1
loaded = w
return count <= D
maxWeight = max(weights)
lo = sum(weights) // D
hi = maxWeight * len(weights) // D + 1
while lo < hi:
mid = (lo + hi) // 2
if mid < maxWeight or not canShip(mid):
lo = mid + 1
else:
hi = mid
return lo | capacity-to-ship-packages-within-d-days | Python3 beats 97% - Capacity To Ship Packages Within D Days | r0bertz | 0 | 359 | capacity to ship packages within d days | 1,011 | 0.646 | Medium | 16,568 |
https://leetcode.com/problems/numbers-with-repeated-digits/discuss/332462/Solution-in-Python-3-(beats-~99) | class Solution:
def numDupDigitsAtMostN(self, N: int) -> int:
T = [9,261,4725,67509,831429,9287109,97654149,994388229]
t = [99,999,9999,99999,999999,9999999,99999999,999999999]
if N < 10:
return 0
L = len(str(N))
m, n = [1], []
g = 11-L
for i in range(L):
n.append(int(str(N)[i]))
m.append(g)
g = g*(12-L+i)
S = 0
for i in range(L):
if len(set(n[:L-i-1])) != len(n)-i-1:
continue
k = 0
for j in range(10):
if j not in n[:L-i-1] and j > n[L-i-1]:
k += 1
S += k*m[i]
return(T[L-2]-(t[L-2]-N-S))
- Python 3
- Junaid Mansuri | numbers-with-repeated-digits | Solution in Python 3 (beats ~99%) | junaidmansuri | 2 | 962 | numbers with repeated digits | 1,012 | 0.406 | Hard | 16,569 |
https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/discuss/352417/Solution-in-Python-3-(beats-~99)-(With-Detailed-Explanation)-(-O(n)-time-)-(-O(1)-space-) | class Solution:
def canThreePartsEqualSum(self, A: List[int]) -> bool:
S = sum(A)
if S % 3 != 0: return False
g, C, p = S//3, 0, 0
for a in A[:-1]:
C += a
if C == g:
if p == 1: return True
C, p = 0, 1
return False | partition-array-into-three-parts-with-equal-sum | Solution in Python 3 (beats ~99%) (With Detailed Explanation) ( O(n) time ) ( O(1) space ) | junaidmansuri | 22 | 1,600 | partition array into three parts with equal sum | 1,013 | 0.432 | Easy | 16,570 |
https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/discuss/352417/Solution-in-Python-3-(beats-~99)-(With-Detailed-Explanation)-(-O(n)-time-)-(-O(1)-space-) | class Solution:
def canThreePartsEqualSum(self, A: List[int]) -> bool:
return (lambda x,y: x in y and 2*x in y and 3*x in y)(sum(A)//3,itertools.accumulate(A))
Junaid Mansuri
Chicago, IL | partition-array-into-three-parts-with-equal-sum | Solution in Python 3 (beats ~99%) (With Detailed Explanation) ( O(n) time ) ( O(1) space ) | junaidmansuri | 22 | 1,600 | partition array into three parts with equal sum | 1,013 | 0.432 | Easy | 16,571 |
https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/discuss/1611798/Python-3-faster-than-90 | class Solution:
def canThreePartsEqualSum(self, arr: List[int]) -> bool:
s = sum(arr)
if s % 3:
return False
part_sum = s / 3
cur_sum = parts = 0
for num in arr:
cur_sum += num
if cur_sum == part_sum:
if parts == 2:
return True
cur_sum = 0
parts += 1
return False | partition-array-into-three-parts-with-equal-sum | Python 3 faster than 90% | dereky4 | 3 | 308 | partition array into three parts with equal sum | 1,013 | 0.432 | Easy | 16,572 |
https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/discuss/1298683/Easy-Python-Solution(99.84) | class Solution:
def canThreePartsEqualSum(self, arr: List[int]) -> bool:
s=sum(arr)/3
if(s!=int(s) or len(arr)<3):
return False
x=0
c=0
for i in range(len(arr)-1):
x+=arr[i]
if(c==2):
break
if(x==s):
x=0
c+=1
return c==2 | partition-array-into-three-parts-with-equal-sum | Easy Python Solution(99.84%) | Sneh17029 | 1 | 430 | partition array into three parts with equal sum | 1,013 | 0.432 | Easy | 16,573 |
https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/discuss/1292829/Easy-to-understand-python3-solution. | class Solution:
def canThreePartsEqualSum(self, arr: List[int]) -> bool:
# sum of the array.
total = sum(arr)
# loop through the array.
count = 0
value = 0
for i in arr:
value += i
if value == total/3 and count != 3:
count += 1
value = 0
return True if count == 3 else False | partition-array-into-three-parts-with-equal-sum | Easy to understand python3 solution. | void2493 | 1 | 106 | partition array into three parts with equal sum | 1,013 | 0.432 | Easy | 16,574 |
https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/discuss/296550/Python-faster-than-93-292-ms | class Solution(object):
def canThreePartsEqualSum(self, A):
"""
:type A: List[int]
:rtype: bool
"""
if sum(A) % 3 != 0:
return False
S = sum(A)//3
k = 0
s = 0
for i in range(len(A)):
s += A[i]
if s == S:
s = 0
k += 1
if k==3:
return True
return False | partition-array-into-three-parts-with-equal-sum | Python - faster than 93%, 292 ms | il_buono | 1 | 234 | partition array into three parts with equal sum | 1,013 | 0.432 | Easy | 16,575 |
https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/discuss/2187525/iterative | class Solution:
def canThreePartsEqualSum(self, arr: List[int]) -> bool:
# find the equal partition by getting the int division of sum of arr and 3
# keep track of everytime we sum to that equal partition (result)
# if we sum to the equal partion reset a current variable and increment result
# if the amount of times we reach it is 3 we return True, otherwise False
# base case if we get a non equal partition
# Time O(N) Space: O(1)
if sum(arr) % 3:
return False
p = sum(arr) // 3
res = curr = 0
for i in range(len(arr)):
curr += arr[i]
if curr == p:
curr = 0
res += 1
return res >= 3 | partition-array-into-three-parts-with-equal-sum | iterative | andrewnerdimo | 0 | 25 | partition array into three parts with equal sum | 1,013 | 0.432 | Easy | 16,576 |
https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/discuss/1615484/Python%3A-90-Solution | class Solution:
def canThreePartsEqualSum(self, arr: List[int]) -> bool:
n = sum(arr) / 3
if int(n) != n:
return False
n = int(n)
i = 0
for _ in range(3):
a = 0
if i >= len(arr):
return False
for j in range(i, len(arr)):
a += arr[j]
if a == n:
break
if a != n:
return False
i = j + 1
return True | partition-array-into-three-parts-with-equal-sum | Python: 90% Solution | ctonic | 0 | 132 | partition array into three parts with equal sum | 1,013 | 0.432 | Easy | 16,577 |
https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/discuss/1568848/Python3-dollarolution | class Solution:
def canThreePartsEqualSum(self, arr: List[int]) -> bool:
x = sum(arr) // 3
if sum(arr) % 3 != 0:
return False
s, count = 0, 0
for i in arr:
s += i
if s == x:
s = 0
count += 1
if count > 3 and x == 0:
return True
if count > 3 and s != 0:
if x * (count - 3) == -s:
return True
return count == 3 | partition-array-into-three-parts-with-equal-sum | Python3 $olution | AakRay | 0 | 79 | partition array into three parts with equal sum | 1,013 | 0.432 | Easy | 16,578 |
https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/discuss/1231169/Python3-simple-solution | class Solution:
def canThreePartsEqualSum(self, arr: List[int]) -> bool:
m = sum(arr)
if m%3 != 0:
return False
x = m//3
z = 0
l = []
for p,q in enumerate(arr):
z += q
if z == x:
l.append(p)
z = 0
if len(l) >= 2:
for i in range(len(l)-1,-1,-1):
if l[0]<l[i] and len(arr)-1!=l[i]:
return True
else:
return False | partition-array-into-three-parts-with-equal-sum | Python3 simple solution | EklavyaJoshi | 0 | 83 | partition array into three parts with equal sum | 1,013 | 0.432 | Easy | 16,579 |
https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/discuss/1231169/Python3-simple-solution | class Solution:
def canThreePartsEqualSum(self, A: List[int]) -> bool:
s = sum(A)
if s%3 != 0:
return False
s = s//3
z = 0
c = 0
for i in A:
z += i
if z == s:
z = 0
c += 1
if c == 3:
return True
return False | partition-array-into-three-parts-with-equal-sum | Python3 simple solution | EklavyaJoshi | 0 | 83 | partition array into three parts with equal sum | 1,013 | 0.432 | Easy | 16,580 |
https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/discuss/783993/Python3-Prefix-Sum-technique-fast-and-short | class Solution:
def canThreePartsEqualSum(self, A: List[int]) -> bool:
prefix_sums = list(itertools.accumulate(A))
if prefix_sums[-1] % 3:
return False
TARGET = prefix_sums[-1] // 3
try:
return prefix_sums.index(TARGET * 2, prefix_sums.index(TARGET) + 1) < len(prefix_sums) - 1
except ValueError:
return False | partition-array-into-three-parts-with-equal-sum | Python3 Prefix Sum technique, fast & short | haoyun129 | 0 | 149 | partition array into three parts with equal sum | 1,013 | 0.432 | Easy | 16,581 |
https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/discuss/621719/Intuitive-solution-with-explanation-as-comment | class Solution:
def canThreePartsEqualSum(self, A: List[int]) -> bool:
# Corner/Edge cases
if len(A) < 3:
return False
sum_of_a = sum(A)
''' sum of array A'''
len_of_a = len(A)
''' Length of array A'''
if sum_of_a % 3 == 0:
# Make sure the sum of a can be divided by 3
num_of_part = 0
''' Number of partition so far'''
sum_of_part = 0
''' Sum of partition so far'''
k = sum_of_a // 3
''' Target sum of partition '''
for i, v in enumerate(A):
sum_of_part += v
if sum_of_part == k:
num_of_part += 1
sum_of_part = 0
if num_of_part == 2 and i+1 < len_of_a:
# If we have two partitions already
# and there are still element left,
# then we can say that A can satisfy
# the requirement
return True
return False | partition-array-into-three-parts-with-equal-sum | Intuitive solution with explanation as comment | puremonkey2001 | 0 | 124 | partition array into three parts with equal sum | 1,013 | 0.432 | Easy | 16,582 |
https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/discuss/469253/Python3-97.27-(320-ms)6.25-(19.3-MB)-O(n)-time-O(1)-space-left-then-right-subarray | class Solution:
def canThreePartsEqualSum(self, A: List[int]) -> bool:
sum_ = sum(A) / 3
if (sum_ == int(sum_) and len(A) >= 3):
sum_ = int(sum_)
left = 0
boundary = len(A) - 2
A_len = len(A)
current_sum = 0
while (left < A_len and current_sum != sum_):
current_sum += A[left]
left += 1
if (current_sum == sum_):
right = len(A) - 1
current_sum = 0
while (right > left and current_sum != sum_):
current_sum += A[right]
right -= 1
if (current_sum == sum_):
return True
return False | partition-array-into-three-parts-with-equal-sum | Python3 97.27% (320 ms)/6.25% (19.3 MB) -- O(n) time / O(1) space -- left then right subarray | numiek_p | 0 | 105 | partition array into three parts with equal sum | 1,013 | 0.432 | Easy | 16,583 |
https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/discuss/455830/Python3-simple-general-solution-n-3 | class Solution:
def canThreePartsEqualSum(self, A: List[int]) -> bool:
return self.nPartition(A)
def nPartition(self, l:list, n = 3) -> bool:
t = sum(l)
if t % n != 0 or len(l) < n:
return False
count,count_sum,target=0,0,t//n
for i in l:
count_sum += i
if count_sum == target:
count_sum = 0
count += 1
return count >= n | partition-array-into-three-parts-with-equal-sum | Python3 simple general solution, n = 3 | jb07 | 0 | 120 | partition array into three parts with equal sum | 1,013 | 0.432 | Easy | 16,584 |
https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/discuss/265034/Simple-Python-3-Solution | class Solution:
def canThreePartsEqualSum(self, A):
A += [0]
sa = sum(A)
saby3 = sa // 3
sdum = 0
count = 0
x = 0
for x in range(len(A)):
sdum += A[x]
if sdum == saby3:
count += 1
sdum = 0
if count == 3:
break
if count == 3 and sum(A[x:1]) == 0:
return True
else:
return False | partition-array-into-three-parts-with-equal-sum | Simple Python 3 Solution | pratul1997 | 0 | 132 | partition array into three parts with equal sum | 1,013 | 0.432 | Easy | 16,585 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/1521786/oror-Very-easy-explanation-oror-DP-oror-Complexity-Analysis-oror-Python | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
dp = [0]*(len(values))
dp[0] = values[0]
maxVal = 0
for i in range(1, len(values)):
dp[i] = max(dp[i-1], values[i-1]+i-1)
maxVal = max(maxVal, dp[i]+values[i]-i)
return maxVal | best-sightseeing-pair | ✅ || Very easy explanation || DP || Complexity Analysis || Python | siddp6 | 34 | 1,100 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,586 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/1521786/oror-Very-easy-explanation-oror-DP-oror-Complexity-Analysis-oror-Python | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
maxVal = 0
cur = 0
for i in range(1, len(values)):
cur = max(cur, values[i-1]+i-1)
maxVal = max(maxVal, cur+values[i]-i)
return maxVal | best-sightseeing-pair | ✅ || Very easy explanation || DP || Complexity Analysis || Python | siddp6 | 34 | 1,100 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,587 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/2192535/Python-3-or-O(n)-or-Very-clearly-explained! | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
n = len(values)
maximum = 0
for i in range(n):
for j in range(i+1, n):
if i >= j: continue
maximum = max(maximum, values[i] + values[j] + i - j)
return maximum | best-sightseeing-pair | ✅Python 3 | O(n) | Very clearly explained! | PythonerAlex | 3 | 129 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,588 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/2192535/Python-3-or-O(n)-or-Very-clearly-explained! | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
n = len(values)
i = maximum = 0
for j in range(i+1, n):
maximum = max(maximum, values[i] + values[j] + i - j)
if values[j] + j - i > values[i]: i = j
return maximum | best-sightseeing-pair | ✅Python 3 | O(n) | Very clearly explained! | PythonerAlex | 3 | 129 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,589 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/2568365/Fast-and-Simple-Python3-or-O(n)-Time-O(n)-Space | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
i = best = 0
for j in range(1, len(values)):
best = max(best, values[i] + values[j] + i - j)
if values[j] - i >= values[i] - j:
i = j
return best | best-sightseeing-pair | Fast & Simple Python3 | O(n) Time, O(n) Space | ryangrayson | 1 | 48 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,590 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/1853306/WEEB-DOES-PYTHONC%2B%2B-DP-SOLUTION-ONE-PASS-WITH-O(1)-SPACE | class Solution:
def maxScoreSightseeingPair(self, nums: List[int]) -> int:
curMaxPair, result = 0, 0
for i in range(len(nums)):
if nums[i] + curMaxPair - i > result:
result = nums[i] + curMaxPair - i
if nums[i] + i > curMaxPair:
curMaxPair = nums[i] + i
return result | best-sightseeing-pair | WEEB DOES PYTHON/C++ DP SOLUTION ONE PASS WITH O(1) SPACE | Skywalker5423 | 1 | 62 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,591 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/1816366/Python-oror-Easy-to-understand | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
part1=values[0]+0 # start with index 0
part2=0 # intialize part2 inside for loop
for i in range(1,len(values)):
part2=max(part2,part1+values[i]-i)
part1=max(part1,values[i]+i)
return part2 | best-sightseeing-pair | Python || Easy to understand | rushi_javiya | 1 | 45 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,592 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/1728942/python3-bad-and-simple-DP | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
size = len(values)
curr_right = size - 1
ans = -1
for i in range(size - 2, -1, -1):
temp_right = curr_right
for j in range(curr_right, i, -1):
if values[curr_right] - values[j] < curr_right - j:
temp_right = j
curr_right = temp_right
ans = max(ans, values[i] + values[curr_right] + i - curr_right)
return ans | best-sightseeing-pair | python3 bad and simple DP | 752937603 | 1 | 33 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,593 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/2840685/Python-4-lines-solution | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
max_right, best = 0, values[-1]
# calculate maximum pair value at the right
for i in range(len(values) - 2, -1, -1):
best = max(best, values[i] + max_right - 1, values[i] + values[i+1] -1)
max_right = max(max_right-1, values[i+1] - 1)
return best | best-sightseeing-pair | Python 4-lines solution | yuriyskh | 0 | 1 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,594 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/2829727/Python3-or-Linear-Dp-Approach-or-Explanation | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
i = 0
n = len(values)
ans = -math.inf
for j in range(1,n):
ans = max(values[i] + values[j] + i - j , ans)
if values[j] + j > values[i] + i:
i = j
return ans | best-sightseeing-pair | [Python3] | Linear Dp Approach | Explanation | swapnilsingh421 | 0 | 2 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,595 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/2716176/Easy-Python-Postfix-O(n)-Solution | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
# Array tracks max from end of array to current index
postfix_max = values.copy()
n = len(postfix_max)
# Subtract i from every index (account for j - i)
for i in range(n):
postfix_max[i] -= i
# Keep postfix max for every index
for i in range(n-2, -1, -1):
postfix_max[i] = max(postfix_max[i], postfix_max[i+1])
best = 0
# For each number, check the current value + the greatest value after it + index.
# We add index since we subtracted i from every index initially, but our start index is increasing every iteration
for i in range(n-1):
best = max(best, values[i] + postfix_max[i+1] + i)
return best | best-sightseeing-pair | Easy Python Postfix O(n) Solution | arnavn101 | 0 | 4 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,596 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/2683217/Python-or-Dynamic-programming-or-O(n)-solution | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
carry, ind, step, ans = values[0], 0, None, values[0]
for i in range(1, len(values)):
step = max(values[i - 1] - 1, carry + ind - i) + values[i]
if values[i] >= carry - i + ind:
carry = values[i]
ind = i
ans = max(ans, step)
return ans | best-sightseeing-pair | Python | Dynamic programming | O(n) solution | LordVader1 | 0 | 20 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,597 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/2555401/python-cool-solution-short | class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
mm=-float('inf')
mx=-float('inf')
for i in range(len(values)):
mx=max(mx,mm+values[i]-i)
mm=max(mm,values[i]+i)
return mx | best-sightseeing-pair | python cool solution short | benon | 0 | 27 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,598 |
https://leetcode.com/problems/best-sightseeing-pair/discuss/2538524/Easy-python-8-line-solution | class Solution:
def maxScoreSightseeingPair(self, a: List[int]) -> int:
mx=a[0]
mxx=float("-infinity")
for i in range(1,len(a)):
bk=a[i]-i
mxx=max(mxx,mx+bk)
mx=max(a[i]+i,mx)
return mxx | best-sightseeing-pair | Easy python 8 line solution | shubham_1307 | 0 | 20 | best sightseeing pair | 1,014 | 0.595 | Medium | 16,599 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.