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/minimum-hours-of-training-to-win-a-competition/discuss/2797910/Python-simple-O(N)-Time-and-O(1)-space-solution | class Solution:
def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:
hours = 0
curr_hours = 0
energy_sum = sum(energy)
for elem in experience:
if initialExperience> elem:
initialExperience+=elem
else:
curr_hours= elem+1-initialExperience
hours+=curr_hours
initialExperience+=elem+curr_hours
if initialEnergy <= energy_sum:
hours+= energy_sum + 1 -initialEnergy
return hours | minimum-hours-of-training-to-win-a-competition | Python simple O(N) Time and O(1) space solution | Rajeev_varma008 | 0 | 2 | minimum hours of training to win a competition | 2,383 | 0.41 | Easy | 32,600 |
https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2789297/Python-simple-easy-to-understand-solution | class Solution:
def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:
en = sum(energy)
ex = initialExperience
tm = 0
if en >= initialEnergy:
tm += en-initialEnergy+1
idx = 0
while (idx < len(energy)):
if ex > experience[idx]:
en -= energy[idx]
ex += experience[idx]
idx += 1
else:
tm += experience[idx]-ex+1
ex = experience[idx]+1
return tm | minimum-hours-of-training-to-win-a-competition | Python simple easy to understand solution | ankurkumarpankaj | 0 | 1 | minimum hours of training to win a competition | 2,383 | 0.41 | Easy | 32,601 |
https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2762101/Python3-simple-solution | class Solution:
def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:
totalTrainingHours = 0
for i in range(len(energy)):
if experience[i] >= initialExperience:
totalTrainingHours += experience[i] - initialExperience + 1
initialExperience = experience[i] + 1
if energy[i] >= initialEnergy:
totalTrainingHours += energy[i] - initialEnergy + 1
initialEnergy = energy[i] + 1
initialEnergy -= energy[i]
initialExperience += experience[i]
return totalTrainingHours | minimum-hours-of-training-to-win-a-competition | Python3 simple solution | EklavyaJoshi | 0 | 4 | minimum hours of training to win a competition | 2,383 | 0.41 | Easy | 32,602 |
https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2703185/python | class Solution:
def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:
result = 0
A, B = initialEnergy, initialExperience
for a, b in zip(energy, experience):
if A <= a:
diff = a - A + 1
result += diff
A += diff
if B <= b:
diff = b - B + 1
result += diff
B += diff
B += b
A -= a
return result | minimum-hours-of-training-to-win-a-competition | python | emersonexus | 0 | 9 | minimum hours of training to win a competition | 2,383 | 0.41 | Easy | 32,603 |
https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2517520/Easy-very-readable-programme-Python | class Solution:
def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:
# Just Read the solution
# Everything is in clear with variable
# Happy coding :)
k=initialExperience
Hours_for_energy=0
if initialEnergy<=sum(energy):
Hours_for_energy=(sum(energy)+1)-initialEnergy
for i in experience:
if initialExperience<=i:
initialExperience+=(i-initialExperience)+1
initialExperience+=i
Hours_for_experience=initialExperience-sum(experience)-k
return Hours_for_energy+Hours_for_experience | minimum-hours-of-training-to-win-a-competition | Easy very readable programme , Python | Aniket_liar07 | 0 | 34 | minimum hours of training to win a competition | 2,383 | 0.41 | Easy | 32,604 |
https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2465959/Python3-II-Easy-to-understand-(less-than-100-faster-than-33.33) | class Solution:
def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:
cur_experience, min_experience= initialExperience, 0
for i in range(len(experience)):
if cur_experience <= experience[i]:
min_experience += experience[i]-cur_experience+1
cur_experience = 2*experience[i]+1
else:
cur_experience += experience[i]
minenergy = sum(energy)+1-initialEnergy if initialEnergy<=sum(energy) else 0
return minexperience+minenergy | minimum-hours-of-training-to-win-a-competition | Python3 II Easy to understand (less than 100%, faster than 33.33%) | JanuaryofSun | 0 | 27 | minimum hours of training to win a competition | 2,383 | 0.41 | Easy | 32,605 |
https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2464479/Linear-solution | class Solution:
def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:
add_energy = add_experience = 0
for e, x in zip(energy, experience):
if initialEnergy <= e:
add_e = e + 1 - initialEnergy
add_energy += add_e
initialEnergy += add_e
if initialExperience <= x:
add_x = x + 1 - initialExperience
add_experience += add_x
initialExperience += add_x
initialEnergy -= e
initialExperience += x
return add_energy + add_experience | minimum-hours-of-training-to-win-a-competition | Linear solution | EvgenySH | 0 | 12 | minimum hours of training to win a competition | 2,383 | 0.41 | Easy | 32,606 |
https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2460007/Python3-solution-explained | class Solution:
def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:
# for energy we gonna subtract at every opponent, so we need X > sum(energy) || X must be equal to sum(energy)+1 if initialEnergy it's lower than the sum
# for experience we need to check everytime if current experience is equal or lower than the exp of our opponent, if so we need to have Exp == opponent experience + 1
ans = 0
s = sum(energy)
if initialEnergy <= s:
ans += abs(s-initialEnergy)+1
for i in range(len(experience)):
if initialExperience <= experience[i]:
t = abs(experience[i] - initialExperience) + 1
initialExperience += t
ans += t
initialExperience += experience[i]
return ans | minimum-hours-of-training-to-win-a-competition | Python3 solution explained | FlorinnC1 | 0 | 16 | minimum hours of training to win a competition | 2,383 | 0.41 | Easy | 32,607 |
https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2459652/Python-Solution-or-Easy-to-understand | class Solution:
def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:
energy_req = 0
exp_req = 0
for i in range(len(energy)):
if initialEnergy > energy[i]:
initialEnergy -= energy[i]
else:
diff = (energy[i] - initialEnergy) + 1
energy_req += diff
initialEnergy += diff
initialEnergy -= energy[i]
if initialExperience > experience[i]:
initialExperience += experience[i]
else:
diff = (experience[i] - initialExperience) + 1
exp_req += diff
initialExperience += diff
initialExperience += experience[i]
return energy_req+exp_req | minimum-hours-of-training-to-win-a-competition | Python Solution | Easy to understand 🤘 | sudarshaana | 0 | 8 | minimum hours of training to win a competition | 2,383 | 0.41 | Easy | 32,608 |
https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2458826/Easy-to-Understand-or-Brute-force-or-Firtst-Instinct-or-Python3 | class Solution:
def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:
hours = 0
if(initialEnergy < 0 or initialExperience < 0):
return 0
if(len(energy) == 0 or len(experience) == 0):
return 0
for i in range(len(energy)):
if(initialEnergy <= energy[i]):
hours += (energy[i]-initialEnergy)+1
initialEnergy += (energy[i]-initialEnergy)+1
if(initialExperience <= experience[i]):
hours += (experience[i]-initialExperience)+1
initialExperience += (experience[i]-initialExperience)+1
initialEnergy -= energy[i]
initialExperience += experience[i]
return hours | minimum-hours-of-training-to-win-a-competition | Easy to Understand | Brute force | Firtst Instinct | Python3 | sanju39194 | 0 | 7 | minimum hours of training to win a competition | 2,383 | 0.41 | Easy | 32,609 |
https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2458697/Python-or-Easy-to-understand | class Solution:
def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:
needed_energy = sum(energy) - initialEnergy + 1 # finding energy amount
needed_energy = needed_energy if needed_energy > 0 else 0
needed_experience = 0
for i, exp in enumerate(experience):
if initialExperience + needed_experience <= exp: # check whether you need to increment experience
needed_experience += exp - (initialExperience + needed_experience) + 1
initialExperience += exp
return needed_energy + needed_experience | minimum-hours-of-training-to-win-a-competition | Python | Easy to understand ✅ | cyber_kazakh | 0 | 8 | minimum hours of training to win a competition | 2,383 | 0.41 | Easy | 32,610 |
https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2457051/Python-5-lines-easy-to-understand | class Solution:
def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:
energy_needed, experience_needed = max(sum(energy) - initialEnergy + 1, 0), 0
for e in experience:
experience_needed += e - initialExperience + 1 if e >= initialExperience else 0
initialExperience += experience_needed + e if e >= initialExperience else e
return energy_needed + experience_needed | minimum-hours-of-training-to-win-a-competition | ✅ Python 5 lines easy to understand | idntk | 0 | 20 | minimum hours of training to win a competition | 2,383 | 0.41 | Easy | 32,611 |
https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2456760/Python-Simple-Python-Solution | class Solution:
def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:
result = 0
for i in range(len(energy)):
a = initialEnergy - energy[i]
b = initialExperience - experience[i]
if a <= 0:
result = result + abs(a) + 1
initialEnergy = initialEnergy + abs(a) + 1
if b <= 0:
result = result + abs(b) + 1
initialExperience = initialExperience + abs(b) + 1
initialEnergy = initialEnergy - energy[i]
initialExperience = initialExperience + experience[i]
return result; | minimum-hours-of-training-to-win-a-competition | [ Python ] ✅✅ Simple Python Solution 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 32 | minimum hours of training to win a competition | 2,383 | 0.41 | Easy | 32,612 |
https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2456754/Python-or-Self-Explanatory-or-O(n) | class Solution:
def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:
res = 0
if initialEnergy > sum(energy) + 1:
res = 0
else:
res += sum(energy) + 1 - initialEnergy
for num in experience:
if initialExperience > num:
initialExperience += num
else:
train = num - initialExperience + 1
res += train
initialExperience += train + num
return res | minimum-hours-of-training-to-win-a-competition | Python | Self Explanatory | O(n) | xychen35 | 0 | 10 | minimum hours of training to win a competition | 2,383 | 0.41 | Easy | 32,613 |
https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2456743/noob-way-explained-simulation-kinda | class Solution:
def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:
xp = initialExperience # nicer name
nrg = initialEnergy # nicer name
training = 0 # this is our answer we will output
for enemy_nrg in energy: # go through each enemy one by one...
while nrg <= enemy_nrg: # if true, then we need more training
nrg += 1 # training means we get +1 energy
training += 1 # add training time
nrg -= enemy_nrg # we finished training or maybe we didnt need to, but now that we have beated the enemy we subtract energy[i]
for enemy_xp in experience: # same thing
while xp <= enemy_xp:
xp += 1
training += 1
xp += enemy_xp # but instead we gain xp after we beat the enemy
return training | minimum-hours-of-training-to-win-a-competition | noob way explained simulation kinda | Pinfel | 0 | 13 | minimum hours of training to win a competition | 2,383 | 0.41 | Easy | 32,614 |
https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2456712/Python-orSelf-Explanatory-or-Clean-Code-or-O(n) | class Solution:
def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:
hoursNeeded=0
for i in range(0,len(energy)):
CurrEnergy=0
CurrExperience=0
if initialEnergy>energy[i]:
initialEnergy=initialEnergy-energy[i]
else:
CurrEnergy+=(energy[i]-initialEnergy)+1
initialEnergy+=CurrEnergy
initialEnergy=initialEnergy-energy[i]
if initialExperience>experience[i]:
initialExperience=initialExperience+experience[i]
else:
CurrExperience+=(experience[i]-initialExperience)+1
initialExperience+=CurrExperience
initialExperience=initialExperience+experience[i]
hoursNeeded+=CurrEnergy
hoursNeeded+=CurrExperience
return hoursNeeded | minimum-hours-of-training-to-win-a-competition | Python |Self Explanatory | Clean Code | O(n) | _ysh_ | 0 | 18 | minimum hours of training to win a competition | 2,383 | 0.41 | Easy | 32,615 |
https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2456588/Python3-or-Solved-Using-Single-Pass-in-Both-Arrays | class Solution:
def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:
#Approach: Do a single traversal and for every ith opponent, compare your current energy and exp to opponent
#and adjust so you always win! How much you have to adjust will be number of hours of training you have to invest
#before you compete!
#At the end, return answer!
ans = 0
cenergy = initialEnergy
cexp = initialExperience
#n = number of opponents to face!
n = len(energy)
for i in range(n):
if(cenergy <= energy[i]):
ans += (energy[i] - cenergy + 1)
cenergy = 1
#if current player has lower exp, then he needs to make it up for it!
#difference + 1 wil take his current exp to next exp value from opp so he can win!
#but also, in doing so, he needs to already be 1 ahead! -> set cexp to opponent's exp + 1!
#Regardless, since he won, he needs to get ith opponents exp added!
if(cexp <= experience[i]):
ans += (experience[i] - cexp + 1)
cexp = experience[i] + 1
#regardless, current experience only goes up!
cexp += (experience[i])
continue
else:
cenergy -= energy[i]
if(cexp <= experience[i]):
ans += (experience[i] - cexp + 1)
cexp = experience[i] + 1
cexp += (experience[i])
return ans | minimum-hours-of-training-to-win-a-competition | Python3 | Solved Using Single Pass in Both Arrays | JOON1234 | 0 | 26 | minimum hours of training to win a competition | 2,383 | 0.41 | Easy | 32,616 |
https://leetcode.com/problems/largest-palindromic-number/discuss/2456725/Python-oror-Easy-Approach-oror-Hashmap | class Solution:
def largestPalindromic(self, num: str) -> str:
ans = []
b = [str(x) for x in range(9, -1, -1)]
from collections import defaultdict
a = defaultdict(int)
for x in num:
a[x] += 1
for x in b:
n = len(ans)
if n % 2 == 0:
if a[x] > 0:
ans = ans[:n // 2] + [x] * a[x] + ans[n // 2:]
else:
if x == '0':
if len(ans) != 1:
ans = ans[:n // 2] + [x] * (a[x] // 2) + [ans[n // 2]] + [x] * (a[x] // 2) + ans[n // 2 + 1:]
else:
if a[x] >= 2:
ans = ans[:n // 2] + [x] * (a[x] // 2) + [ans[n // 2]] + [x] * (a[x] // 2) + ans[n // 2 + 1:]
res = "".join(ans)
return str(int(res)) | largest-palindromic-number | ✅Python || Easy Approach || Hashmap | chuhonghao01 | 4 | 178 | largest palindromic number | 2,384 | 0.306 | Medium | 32,617 |
https://leetcode.com/problems/largest-palindromic-number/discuss/2456740/Python3-freq-table | class Solution:
def largestPalindromic(self, num: str) -> str:
freq = Counter(num)
mid = next((ch for ch in "9876543210" if freq[ch]&1), '')
half = ''.join(ch*(freq[ch]//2) for ch in "0123456789")
return (half[::-1] + mid + half).strip('0') or '0' | largest-palindromic-number | [Python3] freq table | ye15 | 1 | 23 | largest palindromic number | 2,384 | 0.306 | Medium | 32,618 |
https://leetcode.com/problems/largest-palindromic-number/discuss/2818086/python-O(n)-Hash_table | class Solution:
def largestPalindromic(self, num: str) -> str:
dict_frequency = {}
for char in num:
if char in dict_frequency:
dict_frequency[char] += 1
else:
dict_frequency[char] = 1
left_str = ''
right_str = ''
# For placing the number at the middle.
odd_digit = 0
for i in range(10, 0, -1):
digit = str(i-1)
if digit not in dict_frequency:
continue
count = dict_frequency[digit]
if count % 2 == 0:
freq = count // 2
for j in range(freq):
left_str += digit
right_str = digit + right_str
dict_frequency[digit] = 0
else:
# checking if it is not already assisgned then assigned the largest one.
if odd_digit == 0:
odd_digit = digit
freq = count // 2
for j in range(freq):
left_str += digit
right_str = digit + right_str
dict_frequency[digit] = 1
# Concating the left one to the right one.
final = ''
if odd_digit:
final = left_str + odd_digit + right_str
else:
final = left_str + right_str
# if leading '0' and trailing '0' is present then removing it.
final = final.strip('0')
# if only '0' is present then we are left with only empty string, so assigning one '0' char and returning it.
if not len(final):
final = '0'
return str(int(final)) | largest-palindromic-number | python O(n), Hash_table | Raushan_geeks | 0 | 1 | largest palindromic number | 2,384 | 0.306 | Medium | 32,619 |
https://leetcode.com/problems/largest-palindromic-number/discuss/2469388/Counter-and-one-pass-over-digits-100-speed | class Solution:
def largestPalindromic(self, num: str) -> str:
cnt = Counter(num)
left = middle = ""
for c in "987654321":
n, r = divmod(cnt[c], 2)
if n:
left += c * n
if not middle and r:
middle = c
n, r = divmod(cnt["0"], 2)
if left and n:
left += "0" * n
if not middle and r or not left and n and not middle:
middle = "0"
return f"{left}{middle}{left[::-1]}" | largest-palindromic-number | Counter and one pass over digits, 100% speed | EvgenySH | 0 | 19 | largest palindromic number | 2,384 | 0.306 | Medium | 32,620 |
https://leetcode.com/problems/largest-palindromic-number/discuss/2464658/Python-oror-100-oror-Greedy-oror-Hashing-oror-O(N)-Time-oror-O(1)-SPACE | class Solution:
def largestPalindromic(self, num: str) -> str:
count = Counter(num)
fre = ''.join(count[i]//2*i for i in '9876543210')
mid = max(count[i]%2 * i for i in count)
return (fre +mid + fre[::-1]).strip('0') or '0' | largest-palindromic-number | Python || 100% || Greedy || Hashing || O(N) Time || O(1) SPACE | roaring_lion | 0 | 12 | largest palindromic number | 2,384 | 0.306 | Medium | 32,621 |
https://leetcode.com/problems/largest-palindromic-number/discuss/2457133/Find-the-Largest-Odd-number-add-the-Even-Numbers-in-increasing-around-the-largest | class Solution:
def largestPalindromic(self, s: str) -> str:
count = Counter(s)
s = sorted(count.items())
start = -1
for p in s[::-1]:
if int(p[1]) %2 == 1:
start = int(p[0])
break
res = ''
if start != -1:
res = res + str(start)
oldres = res
for p in s:
for i in range( (p[1] - 1) //2 if p[1]%2 ==1 else p[1]//2):
res = str(p[0]) + res + str(p[0])
if all(i == '0' for i in res): #res[0] == '0' and res[-1] == '0':
return '0'
if res[0] == '0':
res = oldres
return res | largest-palindromic-number | Find the Largest Odd number, add the Even Numbers in increasing around the largest | xmky | 0 | 8 | largest palindromic number | 2,384 | 0.306 | Medium | 32,622 |
https://leetcode.com/problems/largest-palindromic-number/discuss/2457045/Python-simple-solution-with-O(n)-and-hashmap | class Solution:
def largestPalindromic(self, num: str) -> str:
freq = {}
for digit in num:
freq[digit] = freq.get(digit, 0) + 1
if len(freq) == 1:
if num[0] == "0":
return "0"
return num
mid_num = "0"
for k, v in freq.items():
if v % 2 != 0 and k > mid_num:
mid_num = k
freq[k] -= 1
res = mid_num
leading_zeros = False
for n in ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]:
if freq.get(n, 0) <= 1:
continue
add = freq[n] // 2
res = n * add + res + n * add
if n == "0":
leading_zeros = True
else:
leading_zeros = False
if leading_zeros:
res = res.strip("0")
return res | largest-palindromic-number | Python simple solution with O(n) and hashmap | vinaylasetti253 | 0 | 12 | largest palindromic number | 2,384 | 0.306 | Medium | 32,623 |
https://leetcode.com/problems/largest-palindromic-number/discuss/2456826/Python-Easy-Counter-Approach | class Solution:
def largestPalindromic(self, num: str) -> str:
c = Counter(num)
res = ""
def add_n_to_res(n: str) -> None:
nonlocal res
if c[n] >= 2:
res = res + n * (c[n]//2)
c[n] -= (c[n]//2) * 2
# add all elements in decreasing order
for n in range(9, 0, -1):
add_n_to_res(str(n))
# add non leading zero
if res:
add_n_to_res('0')
# find highest middle element
mid = -1
for n in c:
if c[n]:
mid = max(mid, int(n))
return res + str(mid) + res[::-1] if mid != -1 else res + res[::-1] | largest-palindromic-number | ✅ Python Easy Counter Approach | idntk | 0 | 21 | largest palindromic number | 2,384 | 0.306 | Medium | 32,624 |
https://leetcode.com/problems/largest-palindromic-number/discuss/2456800/loop-9-to-1-with-freq-greater-2-then-same-again-for-the-middle-number | class Solution:
def largestPalindromic(self, num: str) -> str:
counts = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # 0-9
for i in range(len(num)):
counts[int(num[i])] += 1
out = ""
for i in range(9, -1, -1): # if it appears twice or more then we can use it as a sandwich, priority big number on the outsides
if (i == 0 and out == ""):
break
while counts[i] >= 2:
out += str(i)
counts[i] -= 2
for i in range(9, -1, -1): # we find the biggest available number for the middle number from the remaining counts
if (counts[i] > 0):
return out + str(i) + out[::-1]
return out + out[::-1] | largest-palindromic-number | loop 9 to 1 with freq >= 2, then same again for the middle number | Pinfel | 0 | 4 | largest palindromic number | 2,384 | 0.306 | Medium | 32,625 |
https://leetcode.com/problems/largest-palindromic-number/discuss/2456664/Python-using-counter-and-heap | class Solution:
def largestPalindromic(self, num: str) -> str:
counter = Counter(num)
l = [(-int(n), c) for n, c in counter.items()]
heapq.heapify(l)
left, right = [], []
mid = None
while l:
n, c = heapq.heappop(l)
n = -n
if c % 2 == 0:
left = left + [n] * (c // 2)
right = [n] * (c // 2) + right
else:
if c - 1 > 0:
heapq.heappush(l, (-n, c - 1))
if mid is None:
mid = n
if mid is None and l:
mid = -l[0][0]
while right and right[-1] == 0:
right.pop()
res = left[:len(right)] + [mid] + right if mid is not None else left[:len(right)] + right
if not res:
return "0"
return ''.join([str(i) for i in res]) | largest-palindromic-number | Python using counter and heap | wangzhihao0629 | 0 | 18 | largest palindromic number | 2,384 | 0.306 | Medium | 32,626 |
https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/discuss/2456656/Python3-bfs | class Solution:
def amountOfTime(self, root: Optional[TreeNode], start: int) -> int:
graph = defaultdict(list)
stack = [(root, None)]
while stack:
n, p = stack.pop()
if p:
graph[p.val].append(n.val)
graph[n.val].append(p.val)
if n.left: stack.append((n.left, n))
if n.right: stack.append((n.right, n))
ans = -1
seen = {start}
queue = deque([start])
while queue:
for _ in range(len(queue)):
u = queue.popleft()
for v in graph[u]:
if v not in seen:
seen.add(v)
queue.append(v)
ans += 1
return ans | amount-of-time-for-binary-tree-to-be-infected | [Python3] bfs | ye15 | 33 | 1,400 | amount of time for binary tree to be infected | 2,385 | 0.562 | Medium | 32,627 |
https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/discuss/2572699/DFS-Python | class Solution:
def amountOfTime(self, root, start: int) -> int:
time_to_infect_tree, _ = self.dfs(root, start)
return time_to_infect_tree
def dfs(self, root, start):
if root == None:
return -1, -1
left_infect_time, left_distance = self.dfs(root.left, start)
right_infect_time, right_distance = self.dfs(root.right, start)
if left_distance == -1 and right_distance == -1:
distance = -1
infect_time = max(right_infect_time, left_infect_time) + 1
elif left_distance != -1:
distance = left_distance + 1
infect_time = max(left_infect_time, right_infect_time + left_distance + 2)
else:
distance = right_distance + 1
infect_time = max(right_infect_time, left_infect_time + right_distance + 2)
if root.val == start:
distance = 0
return infect_time, distance | amount-of-time-for-binary-tree-to-be-infected | DFS Python | YairLevi | 0 | 47 | amount of time for binary tree to be infected | 2,385 | 0.562 | Medium | 32,628 |
https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/discuss/2572699/DFS-Python | class Solution:
def amountOfTime(self, root, start: int) -> int:
time_to_infect_tree, _ = self.dfs(root, start)
return time_to_infect_tree
def dfs(self, root, start):
# if root is None
if root == None:
return -1, -1
# get time to infect subtree from root, as well as distance from root of subtree
# to the infected node (-1 if root is not a parent of it)
left_infect_time, left_distance = self.dfs(root.left, start)
right_infect_time, right_distance = self.dfs(root.right, start)
# if both subtrees don't contain the infected node
if left_distance == -1 and right_distance == -1:
distance = -1
# infect time is as if from root node, AKA simply the depth of the subtree
infect_time = max(right_infect_time, left_infect_time) + 1
# if left subtree contains the infected node
elif left_distance != -1:
# update distance to infected node
distance = left_distance + 1
# distance to the infected node from root.left, then two edges to root.right (+2), then
# infect time of right subtree as if from root.right
infect_time = max(left_infect_time, right_infect_time + left_distance + 2)
# same as before, but with right subtree containing the infected
else:
distance = right_distance + 1
infect_time = max(right_infect_time, left_infect_time + right_distance + 2)
# if found the infected node
if root.val == start:
distance = 0
return infect_time, distance | amount-of-time-for-binary-tree-to-be-infected | DFS Python | YairLevi | 0 | 47 | amount of time for binary tree to be infected | 2,385 | 0.562 | Medium | 32,629 |
https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/discuss/2477572/Find-neighbors-and-largest-distance-75-speed | class Solution:
def amountOfTime(self, root: Optional[TreeNode], start: int) -> int:
neighbors = defaultdict(set)
row = {root}
while row:
new_row = set()
for node in row:
if node.left:
neighbors[node.val].add(node.left.val)
neighbors[node.left.val].add(node.val)
new_row.add(node.left)
if node.right:
neighbors[node.val].add(node.right.val)
neighbors[node.right.val].add(node.val)
new_row.add(node.right)
row = new_row
level = {start}
seen = set()
ans = -1
while level:
ans += 1
new_level = set()
for node in level:
new_level.update(neighbors[node])
seen.add(node)
level = new_level - seen
return ans | amount-of-time-for-binary-tree-to-be-infected | Find neighbors and largest distance, 75% speed | EvgenySH | 0 | 66 | amount of time for binary tree to be infected | 2,385 | 0.562 | Medium | 32,630 |
https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/discuss/2467516/Python3-DFS-Efficient-Solution | class Solution:
def amountOfTime(self, root: Optional[TreeNode], start: int) -> int:
def dfs(root):
if root is None:
return None, 0
node_l, l = dfs(root.left)
node_r, r = dfs(root.right)
if root.val == start:
return 0, max(l, r)
if node_l is not None:
return node_l + 1, max(node_l + 1, l, node_l + 1 + r)
if node_r is not None:
return node_r + 1, max(node_r + 1, r, node_r + 1 + l)
return None, max(l, r) + 1
_, ans = dfs(root)
return ans | amount-of-time-for-binary-tree-to-be-infected | Python3 DFS Efficient Solution | user6397p | 0 | 8 | amount of time for binary tree to be infected | 2,385 | 0.562 | Medium | 32,631 |
https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/discuss/2461185/python3-Reference-sol-for-find-parent-nodes-and-do-bfs | class Solution:
def amountOfTime(self, root: Optional[TreeNode], start: int) -> int:
if start == root:
return 0
s = []
parents = {}
parents[root.val] = None
def dfs(node):
if not node:
return (0, False)
if node.left:
parents[node.left.val] = node
dfs(node.left)
if node.right:
parents[node.right.val] = node
dfs(node.right)
if node.val == start:
s.append(node)
dfs(root)
visited = defaultdict(bool)
visited[s[0].val] = True
ans = 0
while s:
for i in range(len(s)):
node = s.pop(0)
visited[node.val] = True
if node.left and not visited[node.left.val]:
s.append(node.left)
if node.right and not visited[node.right.val]:
s.append(node.right)
if parents[node.val] and not visited[parents[node.val].val]:
s.append(parents[node.val])
ans += 1
return ans - 1 | amount-of-time-for-binary-tree-to-be-infected | [python3] Reference sol for find parent nodes and do bfs | vadhri_venkat | 0 | 5 | amount of time for binary tree to be infected | 2,385 | 0.562 | Medium | 32,632 |
https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/discuss/2457123/Python-Creating-Graph-and-BFS-Easy-Understanding | class Solution:
def amountOfTime(self, root: Optional[TreeNode], start: int) -> int:
records = defaultdict(list)
self.helper(root, records)
visited = set()
visited.add(start)
level = 0
queue = deque()
queue.append((start, level))
while queue:
node, level = queue.popleft()
for neighbor in records[node]:
if neighbor not in visited:
queue.append((neighbor, level+1))
visited.add(neighbor)
return level
def helper(self, root, records):
if root.left != None:
#print(root.val, root.left.val)
records[root.val].append(root.left.val)
records[root.left.val].append(root.val)
self.helper(root.left, records)
if root.right != None:
records[root.val].append(root.right.val)
records[root.right.val].append(root.val)
self.helper(root.right, records)
return | amount-of-time-for-binary-tree-to-be-infected | Python Creating Graph and BFS Easy Understanding | zhaoxinglyu12138 | 0 | 4 | amount of time for binary tree to be infected | 2,385 | 0.562 | Medium | 32,633 |
https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/discuss/2456834/simulation-python3 | class Solution:
def amountOfTime(self, root: Optional[TreeNode], start: int) -> int:
### building the map, see for each node who it touches ###
queue = [(root, None)]
mapping = {}
while (queue):
curr, parent = queue.pop()
touches = []
if (curr.left):
touches.append(curr.left.val)
queue.append((curr.left, curr))
if (curr.right):
touches.append(curr.right.val)
queue.append((curr.right, curr))
if (parent):
touches.append(parent.val)
mapping[curr.val] = touches
### do a simulation kinda ###
time = 0
current_wave = [start]
next_wave = []
seen = set()
seen.add(start)
while (current_wave):
node_id = current_wave.pop()
for touch in mapping[node_id]:
if touch not in seen:
next_wave.append(touch)
seen.add(touch)
if (len(current_wave) == 0):
if (len(next_wave) == 0):
return time
else:
time += 1
current_wave = next_wave
next_wave = []
return 0 | amount-of-time-for-binary-tree-to-be-infected | simulation python3 | Pinfel | 0 | 5 | amount of time for binary tree to be infected | 2,385 | 0.562 | Medium | 32,634 |
https://leetcode.com/problems/find-the-k-sum-of-an-array/discuss/2456716/Python3-HeapPriority-Queue-O(NlogN-%2B-klogk) | class Solution:
def kSum(self, nums: List[int], k: int) -> int:
maxSum = sum([max(0, num) for num in nums])
absNums = sorted([abs(num) for num in nums])
maxHeap = [(-maxSum + absNums[0], 0)]
ans = [maxSum]
while len(ans) < k:
nextSum, i = heapq.heappop(maxHeap)
heapq.heappush(ans, -nextSum)
if i + 1 < len(absNums):
heapq.heappush(maxHeap, (nextSum - absNums[i] + absNums[i + 1], i + 1))
heapq.heappush(maxHeap, (nextSum + absNums[i + 1], i + 1))
return ans[0] | find-the-k-sum-of-an-array | [Python3] Heap/Priority Queue, O(NlogN + klogk) | xil899 | 82 | 5,300 | find the k sum of an array | 2,386 | 0.377 | Hard | 32,635 |
https://leetcode.com/problems/find-the-k-sum-of-an-array/discuss/2456716/Python3-HeapPriority-Queue-O(NlogN-%2B-klogk) | class Solution:
def kSum(self, nums: List[int], k: int) -> int:
maxSum = sum([max(0, num) for num in nums])
absNums = sorted([abs(num) for num in nums])
maxHeap, nextSum = [(-maxSum + absNums[0], 0)], -maxSum
for _ in range(k - 1):
nextSum, i = heapq.heappop(maxHeap)
if i + 1 < len(absNums):
heapq.heappush(maxHeap, (nextSum - absNums[i] + absNums[i + 1], i + 1))
heapq.heappush(maxHeap, (nextSum + absNums[i + 1], i + 1))
return -nextSum | find-the-k-sum-of-an-array | [Python3] Heap/Priority Queue, O(NlogN + klogk) | xil899 | 82 | 5,300 | find the k sum of an array | 2,386 | 0.377 | Hard | 32,636 |
https://leetcode.com/problems/find-the-k-sum-of-an-array/discuss/2456675/Python3-priority-queue | class Solution:
def kSum(self, nums: List[int], k: int) -> int:
m = sum(x for x in nums if x > 0)
pq = [(-m, 0)]
vals = sorted(abs(x) for x in nums)
for _ in range(k):
x, i = heappop(pq)
if i < len(vals):
heappush(pq, (x+vals[i], i+1))
if i: heappush(pq, (x-vals[i-1]+vals[i], i+1))
return -x | find-the-k-sum-of-an-array | [Python3] priority queue | ye15 | 40 | 1,900 | find the k sum of an array | 2,386 | 0.377 | Hard | 32,637 |
https://leetcode.com/problems/longest-subsequence-with-limited-sum/discuss/2492737/Prefix-Sum | class Solution:
def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
nums = list(accumulate(sorted(nums)))
return [bisect_right(nums, q) for q in queries] | longest-subsequence-with-limited-sum | Prefix Sum | votrubac | 9 | 1,200 | longest subsequence with limited sum | 2,389 | 0.648 | Easy | 32,638 |
https://leetcode.com/problems/longest-subsequence-with-limited-sum/discuss/2492742/Python3-2-line-binary-search | class Solution:
def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
prefix = list(accumulate(sorted(nums)))
return [bisect_right(prefix, q) for q in queries] | longest-subsequence-with-limited-sum | [Python3] 2-line binary search | ye15 | 8 | 405 | longest subsequence with limited sum | 2,389 | 0.648 | Easy | 32,639 |
https://leetcode.com/problems/longest-subsequence-with-limited-sum/discuss/2499976/Python-Solution-or-Easy-Approach | class Solution:
def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
answer = [0] * len(queries)
for id, query in enumerate(queries):
spec_sum = 0
for i, number in enumerate(sorted(nums)):
spec_sum += number
if spec_sum <= query:
answer[id] += 1
else:
break
return answer | longest-subsequence-with-limited-sum | ✅ Python Solution | Easy Approach | cyber_kazakh | 2 | 80 | longest subsequence with limited sum | 2,389 | 0.648 | Easy | 32,640 |
https://leetcode.com/problems/longest-subsequence-with-limited-sum/discuss/2493093/Python-oror-2-Easy-Approaches-oror-Prefix-Sum | class Solution:
def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
numsSorted = sorted(nums)
res = []
for q in queries:
total = 0
count = 0
for num in numsSorted:
total += num
count += 1
if total > q:
count -= 1
break
res.append(count)
return res | longest-subsequence-with-limited-sum | ✅Python || 2 Easy Approaches || Prefix Sum | chuhonghao01 | 2 | 163 | longest subsequence with limited sum | 2,389 | 0.648 | Easy | 32,641 |
https://leetcode.com/problems/longest-subsequence-with-limited-sum/discuss/2493093/Python-oror-2-Easy-Approaches-oror-Prefix-Sum | class Solution:
def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
ans = []
nums.sort()
sumx = []
res = 0
for x in nums:
res += x
sumx.append(res)
for j in range(len(queries)):
for i, y in enumerate(sumx):
if y <= queries[j]:
continue
else:
ans.append(i)
break
else:
if len(ans) < j + 1:
ans.append(len(nums))
return ans | longest-subsequence-with-limited-sum | ✅Python || 2 Easy Approaches || Prefix Sum | chuhonghao01 | 2 | 163 | longest subsequence with limited sum | 2,389 | 0.648 | Easy | 32,642 |
https://leetcode.com/problems/longest-subsequence-with-limited-sum/discuss/2761640/Python3-Binary-Search-Alogirthm | class Solution:
def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
def binarySearch(arr, target):
l = 0
r = len(arr) - 1
while l <= r:
mid = (l + r) // 2
if arr[mid] > target:
r = mid - 1
else:
l = mid + 1
return l
nums.sort()
Sum = 0
res = []
# Build the Prefix Sum Array.
for i,num in enumerate(nums):
Sum += num
nums[i] = Sum
for q in queries:
res.append(binarySearch(nums, q)) # If Insertion Index is 3 that means first three elements of nums can be summed which is <= query
return res | longest-subsequence-with-limited-sum | Python3 - Binary Search Alogirthm | theReal007 | 0 | 2 | longest subsequence with limited sum | 2,389 | 0.648 | Easy | 32,643 |
https://leetcode.com/problems/longest-subsequence-with-limited-sum/discuss/2750432/Python-Prefix-Sum-98.4 | class Solution:
def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
nums.sort()
for i in range(1,len(nums)):
nums[i] += nums[i-1]
ans = []
for quer in queries:
ans.append(bisect.bisect_right(nums, quer))
return ans | longest-subsequence-with-limited-sum | Python Prefix Sum , 98.4 % | vijay_2022 | 0 | 2 | longest subsequence with limited sum | 2,389 | 0.648 | Easy | 32,644 |
https://leetcode.com/problems/longest-subsequence-with-limited-sum/discuss/2634715/Python-prefix-sum-solution | class Solution(object):
def answerQueries(self, nums, queries):
"""
:type nums: List[int]
:type queries: List[int]
:rtype: List[int]
"""
nums.sort()
res = [0]*len(queries) #our result should be the length of queries
for r in range(len(queries)): # loop through all the element of queries to see if it can make in nums array
tar = queries[r] #target
sums = 0
ln = 0
for n in nums:
sums += n
if sums <= tar: # if it is less that target continue updating the result and the length too
ln +=1
res[r] = ln
else:
break
return res | longest-subsequence-with-limited-sum | Python prefix sum solution | pandish | 0 | 20 | longest subsequence with limited sum | 2,389 | 0.648 | Easy | 32,645 |
https://leetcode.com/problems/longest-subsequence-with-limited-sum/discuss/2508856/python-very-intuitive-(sorting-and-heap-and-hash-table) | class Solution:
def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
# create a max heap
sub = []
total = 0
for elem in nums:
heapq.heappush(sub, -elem)
total += elem
# process reversely
queries = {i: v for i, v in enumerate(queries)}
queries = dict(sorted(queries.items(), key=lambda x: -x[1]))
ans = {}
for idx, lte in queries.items():
while total > lte:
to_del = -heapq.heappop(sub)
total -= to_del
ans.update({idx: len(sub)})
ans = dict(sorted(ans.items(), key=lambda x: x[0]))
return list(ans.values()) | longest-subsequence-with-limited-sum | [python] very intuitive (sorting & heap & hash table) | g4ls0n | 0 | 10 | longest subsequence with limited sum | 2,389 | 0.648 | Easy | 32,646 |
https://leetcode.com/problems/longest-subsequence-with-limited-sum/discuss/2497213/Sort-accumulate-and-bisect-80-speed | class Solution:
def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
nums.sort()
acc = list(accumulate(nums))
return [bisect_right(acc, q) for q in queries] | longest-subsequence-with-limited-sum | Sort, accumulate and bisect, 80% speed | EvgenySH | 0 | 10 | longest subsequence with limited sum | 2,389 | 0.648 | Easy | 32,647 |
https://leetcode.com/problems/longest-subsequence-with-limited-sum/discuss/2496846/Python-or-Sort-%2B-Cumulative-Sum-or-O(nlogn) | class Solution:
def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
nums.sort()
nums, ans = list(accumulate(nums)), []
for q in queries:
idx = bisect_left(nums, q)
ans.append(idx if idx >= len(nums) or nums[idx] != q else idx + 1)
return ans | longest-subsequence-with-limited-sum | Python | Sort + Cumulative Sum | O(nlogn) | leeteatsleep | 0 | 10 | longest subsequence with limited sum | 2,389 | 0.648 | Easy | 32,648 |
https://leetcode.com/problems/longest-subsequence-with-limited-sum/discuss/2495031/Python3-easy-to-understand-solution.-Take-Love-. | class Solution:
def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
nums.sort()
answer = []
for i in queries:
count = 0
total = 0
for num in nums:
total += num
if total > i:
break
count += 1
answer.append(count)
return answer | longest-subsequence-with-limited-sum | Python3 easy to understand solution. Take Love . | mdshazid121 | 0 | 20 | longest subsequence with limited sum | 2,389 | 0.648 | Easy | 32,649 |
https://leetcode.com/problems/longest-subsequence-with-limited-sum/discuss/2494678/O(n)-using-heuristic-%2B-sorted-from-high-query-and-small-value-decrease-(Illustration) | class Solution:
def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
"""
sorted +
"""
a = sorted(nums)[::-1]
q = sorted(zip(queries, range(len(queries))))
s = sum(a)
ans = [-1] * len(queries)
print("nums: ", a, " - q:", q)
print("+ [Init] s:", s, "ans:", ans)
n, m = len(nums), len(queries)
iq = m - 1
ia = 0
for iq in range(m-1,-1,-1):
qi, pi = q[iq]
print("++", "s:", s, "q:", qi, a[ia:])
while ia<=n-1 and s>qi:
s -= a[ia]
ia += 1
print("++", "s:", s, "q:", qi, a[ia:])
ans[pi] = n - ia
print("-->", "s:", s, "q:", qi, "a:", a[ia:], "ans:", ans)
print()
print("ans:", ans)
print("=" * 20)
return ans
print = lambda *a, **aa: () | longest-subsequence-with-limited-sum | O(n) using heuristic + sorted from high query and small value decrease (Illustration) | dntai | 0 | 4 | longest subsequence with limited sum | 2,389 | 0.648 | Easy | 32,650 |
https://leetcode.com/problems/longest-subsequence-with-limited-sum/discuss/2494597/Python-Simple-Python-Solution-Using-Sorting | class Solution:
def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
result = []
nums = sorted(nums)
for i in range(len(queries)):
current_sum = 0
count = 0
for j in range(len(nums)):
current_sum = current_sum + nums[j]
if current_sum <= queries[i]:
count = count + 1
else:
break
result.append(count)
return result | longest-subsequence-with-limited-sum | [ Python ] ✅✅ Simple Python Solution Using Sorting 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 24 | longest subsequence with limited sum | 2,389 | 0.648 | Easy | 32,651 |
https://leetcode.com/problems/longest-subsequence-with-limited-sum/discuss/2493285/Secret-Python-Answer-2-lines-of-code | class Solution:
def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
ac = list(itertools.accumulate(sorted(nums)))
return [bisect.bisect(ac, queries[i]) for i in range(len(queries))] | longest-subsequence-with-limited-sum | [Secret Python Answer🤫🐍👌😍] 2 lines of code | xmky | 0 | 15 | longest subsequence with limited sum | 2,389 | 0.648 | Easy | 32,652 |
https://leetcode.com/problems/longest-subsequence-with-limited-sum/discuss/2493028/Python-bisect_right | class Solution:
def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
nums.sort()
for i in range(1, len(nums)):
nums[i] += nums[i-1]
return [bisect_right(nums, q) for q in queries] | longest-subsequence-with-limited-sum | Python, bisect_right | blue_sky5 | 0 | 16 | longest subsequence with limited sum | 2,389 | 0.648 | Easy | 32,653 |
https://leetcode.com/problems/longest-subsequence-with-limited-sum/discuss/2492906/Python3-Prefixsum-Binary-Search-Easy-Solution | class Solution:
def answerQueries(self, nums: List[int], q: List[int]) -> List[int]:
nums.sort()
pref=[]
pref.append(nums[0])
for i in nums[1:]:
pref.append(i+pref[-1])
ans=[]
for i in q:
ans.append(bisect.bisect(pref, i))
return ans | longest-subsequence-with-limited-sum | Python3, Prefixsum, Binary Search, Easy Solution | mrprashantkumar | 0 | 13 | longest subsequence with limited sum | 2,389 | 0.648 | Easy | 32,654 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2492763/Python3-stack | class Solution:
def removeStars(self, s: str) -> str:
stack = []
for ch in s:
if ch == '*': stack.pop()
else: stack.append(ch)
return ''.join(stack) | removing-stars-from-a-string | [Python3] stack | ye15 | 3 | 46 | removing stars from a string | 2,390 | 0.64 | Medium | 32,655 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2811356/Python-Easy-Solution-in-O(n)-Complexity | class Solution:
def removeStars(self, s: str) -> str:
c,n=0,len(s)
t=""
for i in range(n-1,-1,-1):
if s[i]=='*':
c+=1
else:
if c==0:
t+=s[i]
else:
c-=1
return t[-1::-1] | removing-stars-from-a-string | Python Easy Solution in O(n) Complexity | DareDevil_007 | 1 | 14 | removing stars from a string | 2,390 | 0.64 | Medium | 32,656 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2493130/Python-oror-Easy-Approach-oror-Stack | class Solution:
def removeStars(self, s: str) -> str:
stack = []
for char in s:
if char != '*':
stack.append(char)
else:
stack.pop()
return "".join(stack) | removing-stars-from-a-string | ✅Python || Easy Approach || Stack | chuhonghao01 | 1 | 39 | removing stars from a string | 2,390 | 0.64 | Medium | 32,657 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2493035/python-stack-solution | class Solution:
def removeStars(self, s: str) -> str:
string = list(s)
stack = []
for i in string:
if i == "*":
stack.pop()
else:
stack.append(i)
return "".join(stack) | removing-stars-from-a-string | python stack solution | tolimitiku | 1 | 8 | removing stars from a string | 2,390 | 0.64 | Medium | 32,658 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2831734/Python-solution-STACK-oror-Easy-oror-Beginner-Friendly | class Solution:
def removeStars(self, s: str) -> str:
stack=[]
for i in s:
if i=='*':
stack.pop()
else:
stack.append(i)
return "".join(stack) | removing-stars-from-a-string | Python solution - STACK || Easy || Beginner Friendly✔ | T1n1_B0x1 | 0 | 1 | removing stars from a string | 2,390 | 0.64 | Medium | 32,659 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2801135/Removing-Stars-From-a-string | class Solution:
def removeStars(self, s: str) -> str:
stack=[]
for i in s:
if stack and stack[-1]!='*' and i=='*':
stack.pop()
stack.append(i)
stack.pop()
else:
stack.append(i)
return ''.join(stack) | removing-stars-from-a-string | Removing Stars From a string | shivansh2001sri | 0 | 2 | removing stars from a string | 2,390 | 0.64 | Medium | 32,660 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2799713/Stack-oror-Python3 | class Solution:
def removeStars(self, s: str) -> str:
stack = []
for ch in s:
if stack and ch == '*':
stack.pop()
else:
stack.append(ch)
return ''.join(stack) | removing-stars-from-a-string | Stack || Python3 | joshua_mur | 0 | 1 | removing stars from a string | 2,390 | 0.64 | Medium | 32,661 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2798521/Very-simple-solution-in-5-lines-using-Stack | class Solution:
def removeStars(self, s: str) -> str:
res = []
for c in s:
if c == "*":
res.pop()
else:
res.append(c)
return "".join(res) | removing-stars-from-a-string | Very simple solution in 5 lines using Stack | ankurbhambri | 0 | 6 | removing stars from a string | 2,390 | 0.64 | Medium | 32,662 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2781667/Simple-Python-solution-using-count-variable-and-single-for-loop.-O(n) | class Solution:
def removeStars(self, s: str) -> str:
res = ''
count = 0
for i in range(len(s)-1,-1,-1):
if s[i] =='*':
count+=1
elif count>0:
count-=1
else:
res = s[i]+res
return res | removing-stars-from-a-string | Simple Python solution using count variable and single for loop. O(n) | sheetalpatne | 0 | 3 | removing stars from a string | 2,390 | 0.64 | Medium | 32,663 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2753714/Python3-Solution-with-using-stack-%2B-solution-without-using-stack | class Solution:
def removeStars(self, s: str) -> str:
cur_idx = len(s) - 1
cur_stars_cnt = 0
res = []
while cur_idx >= 0:
while cur_idx >= 0 and s[cur_idx] == '*':
cur_stars_cnt += 1
cur_idx -= 1
while cur_idx >= 0 and cur_stars_cnt > 0 and s[cur_idx] != '*':
cur_stars_cnt -= 1
cur_idx -= 1
if cur_idx >= 0 and s[cur_idx] != '*':
cur_stars_cnt = 0
res.append(s[cur_idx])
cur_idx -= 1
return ''.join(res[::-1]) | removing-stars-from-a-string | [Python3] Solution with using stack + solution without using stack | maosipov11 | 0 | 2 | removing stars from a string | 2,390 | 0.64 | Medium | 32,664 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2753714/Python3-Solution-with-using-stack-%2B-solution-without-using-stack | class Solution:
def removeStars(self, s: str) -> str:
stack = []
for idx in range(len(s)):
if s[idx] != '*':
stack.append(s[idx])
elif stack:
stack.pop()
return ''.join(stack) | removing-stars-from-a-string | [Python3] Solution with using stack + solution without using stack | maosipov11 | 0 | 2 | removing stars from a string | 2,390 | 0.64 | Medium | 32,665 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2650806/Simple-Python-solution-using-if-else-with-explanation | class Solution:
def removeStars(self, s: str) -> str:
# Initiate a blank string
final_string_list = []
for i in s:
# If a '*' is encountered, remove the element in the final_str_list only if it ain't empty. Do nothing if it is empty.
if i == '*':
if final_string_list:
final_string_list.pop()
else:
# Keep on appending the non - * characters in a list
final_string_list.append(i)
# Return the joined elements of the list in a string
return ''.join(final_string_list) | removing-stars-from-a-string | Simple Python solution using if-else with explanation | code_snow | 0 | 16 | removing stars from a string | 2,390 | 0.64 | Medium | 32,666 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2594925/80-less-Memory-Solution-oror-Stack-oror-Simple-Solution | class Solution:
def removeStars(self, s: str) -> str:
stack = []
for i in range(len(s)):
if s[i] == '*' and len(stack)!=0:
stack.pop()
elif s[i]!='*':
stack.append(s[i])
return ''.join(stack) | removing-stars-from-a-string | 80% less Memory Solution || Stack || Simple Solution | ajinkyabhalerao11 | 0 | 9 | removing stars from a string | 2,390 | 0.64 | Medium | 32,667 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2575557/easy-python-solution | class Solution:
def removeStars(self, s: str) -> str:
char = ""
for i in range(len(s)) :
if s[i] != '*' :
char += s[i]
else :
if len(char) >= 1 :
char = char[:-1]
return char | removing-stars-from-a-string | easy python solution | sghorai | 0 | 7 | removing stars from a string | 2,390 | 0.64 | Medium | 32,668 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2529320/python-solution-simple-stack-problem | class Solution:
def removeStars(self, s: str) -> str:
stack = []
for i in s:
if i == '*':
stack.pop()
else:
stack.append(i)
return "".join(stack) | removing-stars-from-a-string | python solution simple stack problem | pandish | 0 | 19 | removing stars from a string | 2,390 | 0.64 | Medium | 32,669 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2528837/Python-Solution-or-Stack-Simulation-or-Clean-Code | class Solution:
def removeStars(self, s: str) -> str:
stack = []
for i in range(0,len(s)):
if stack and s[i] == "*":
stack.pop(-1)
else:
stack.append(s[i])
return "".join(stack) | removing-stars-from-a-string | Python Solution | Stack Simulation | Clean Code | Gautam_ProMax | 0 | 21 | removing stars from a string | 2,390 | 0.64 | Medium | 32,670 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2521107/Python-top-90-solution | class Solution:
def removeStars(self, s: str) -> str:
stack = []
for i in s:
if i == '*':
stack.pop()
else:
stack.append(i)
return ''.join(stack) | removing-stars-from-a-string | Python top 90% solution | StikS32 | 0 | 26 | removing stars from a string | 2,390 | 0.64 | Medium | 32,671 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2496309/Python-Easy-approach-simple-for-loop | class Solution:
def removeStars(self, s: str) -> str:
lt = []
for i in range(len(s)):
if(s[i] == "*"):
lt.pop()
else:
lt.append(s[i])
return "".join(lt) | removing-stars-from-a-string | Python Easy approach simple for loop | rajitkumarchauhan99 | 0 | 11 | removing stars from a string | 2,390 | 0.64 | Medium | 32,672 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2495474/Easy-python-solution-with-stack. | class Solution:
def removeStars(self, s: str) -> str:
st=[]
for i in range(len(s)):
if s[i]!="*":
st.append(s[i])
else:
st.pop()
return "".join(st) | removing-stars-from-a-string | Easy python solution with stack. | a_dityamishra | 0 | 4 | removing stars from a string | 2,390 | 0.64 | Medium | 32,673 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2494638/Python-Simple-Python-Solution-Using-Stack | class Solution:
def removeStars(self, s: str) -> str:
stack = []
for i in s:
if i != '*':
stack.append(i)
else:
stack.pop(-1)
return ''.join(stack) | removing-stars-from-a-string | [ Python ] ✅✅ Simple Python Solution Using Stack 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 18 | removing stars from a string | 2,390 | 0.64 | Medium | 32,674 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2494598/O(n)-using-Stack | class Solution:
def removeStars(self, s: str) -> str:
q = []
for si in s:
if si != '*':
q.append(si)
else:
q.pop(-1)
ans = "".join(q)
return ans | removing-stars-from-a-string | O(n) using Stack | dntai | 0 | 2 | removing stars from a string | 2,390 | 0.64 | Medium | 32,675 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2494325/Stack-Push-and-Pop-Python | class Solution:
def removeStars(self, s: str) -> str:
# a=s.copy()
# ptr=0
stack=[]
for i in range(len(s)):
if s[i]=="*":
# a=a[:i-1]+a[i+1:]
stack.pop(-1)
else:
stack.append(s[i])
return "".join(stack) | removing-stars-from-a-string | Stack Push and Pop - Python | Prithiviraj1927 | 0 | 4 | removing stars from a string | 2,390 | 0.64 | Medium | 32,676 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2494034/Python-Stack-Implementation | class Solution:
def removeStars(self, s: str) -> str:
### [1]
stack = [ ]
n = len(s)
for i in range(n):
### [1]
stack += [ s[i] ]
### [2]
while stack and stack[-1] == "*":
### [2]
stack.pop()
stack.pop()
### [3]
return ''.join(stack) | removing-stars-from-a-string | Python Stack Implementation | vaebhav | 0 | 3 | removing stars from a string | 2,390 | 0.64 | Medium | 32,677 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2493311/Secret-Python-Answer-Using-a-Stack | class Solution:
def removeStars(self, s: str) -> str:
res = []
for c in s:
res.append(c)
if res[-1] == '*':
res.pop()
if res:
res.pop()
return ''.join(res) | removing-stars-from-a-string | [Secret Python Answer🤫🐍👌😍] Using a Stack | xmky | 0 | 4 | removing stars from a string | 2,390 | 0.64 | Medium | 32,678 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2492958/Python3-Stack-Implementation-Easy-short-solution | class Solution:
def removeStars(self, s: str) -> str:
ans=[]
for i in s:
if i != "*":
ans.append(i)
else:
ans.pop()
return "".join(ans) | removing-stars-from-a-string | Python3, Stack Implementation, Easy short solution | mrprashantkumar | 0 | 3 | removing stars from a string | 2,390 | 0.64 | Medium | 32,679 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2492944/Python-Stack | class Solution:
def removeStars(self, s: str) -> str:
stack = []
for c in s:
if c == "*":
if stack:
stack.pop()
else:
stack.append(c)
return "".join(stack) | removing-stars-from-a-string | [Python] Stack | tejeshreddy111 | 0 | 6 | removing stars from a string | 2,390 | 0.64 | Medium | 32,680 |
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2492842/Python3-or-Solved-Using-Simple-Logic-of-Pattern | class Solution:
#Time-Complexity: O(N^2)
#Space-Complexity:O(1)
#Space-Complexity:O(
def removeStars(self, s: str) -> str:
#Brute-Force approach: As long as star character appears in string input s, continously simulate!
#while "*" in s:
#iterate from left to right char by char until you hit star! then update s to subsequence!
#for i in range(len(s)):
# cur_char = s[i]
# if(cur_char == '*'):
#reupdate s!
# s = s[:i-1] + s[i+1:]
# break
#return s
#optimized version: Simply traverse linearly using single pointer in linear time
#by taking advantage of fact that the star char you see when you traverse from L to R is s.t. the last char
#in built up string will be one char to be removed along with star char per operation!
ans = ""
for i in range(len(s)):
cur_char = s[i]
if(cur_char == '*'):
#pop off last char!
ans = ans[:len(ans)-1]
continue
else:
ans += cur_char
return ans | removing-stars-from-a-string | Python3 | Solved Using Simple Logic of Pattern | JOON1234 | 0 | 8 | removing stars from a string | 2,390 | 0.64 | Medium | 32,681 |
https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2492802/Python3-simulation | class Solution:
def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:
ans = sum(map(len, garbage))
prefix = list(accumulate(travel, initial=0))
for ch in "MPG":
ii = 0
for i, s in enumerate(garbage):
if ch in s: ii = i
ans += prefix[ii]
return ans | minimum-amount-of-time-to-collect-garbage | [Python3] simulation | ye15 | 4 | 48 | minimum amount of time to collect garbage | 2,391 | 0.851 | Medium | 32,682 |
https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2493187/Python-oror-Easy-Approach-oror-Prefix-Sum-oror-Hashmap | class Solution:
def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:
from collections import defaultdict
ans = 0
lastH = {}
num = defaultdict(int)
for i in range(len(garbage)):
for char in garbage[i]:
num[char] += 1
lastH[char] = i
pref = []
res = 0
for x in travel:
res += x
pref.append(res)
ans = sum(num.values())
for k, v in lastH.items():
if lastH[k] != 0:
ans += pref[lastH[k] - 1]
return ans | minimum-amount-of-time-to-collect-garbage | ✅Python || Easy Approach || Prefix Sum || Hashmap | chuhonghao01 | 3 | 162 | minimum amount of time to collect garbage | 2,391 | 0.851 | Medium | 32,683 |
https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2555618/Easy-Python-Solution-using-Prefix-Sum | class Solution:
def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:
# add 0 to prefix because for the first house the commute time is 0
prefix = [0]
cur = 0
for time in travel:
cur += time
prefix.append(cur)
# the default index is zero
# it does not mean each grabage appears in the first house, only for calculation convenience
M_idx, G_idx, P_idx = 0, 0, 0
res = 0
for i in range(len(garbage)):
res += len(garbage[i])
if "M" in garbage[i]:
M_idx = i
if "G" in garbage[i]:
G_idx = i
if "P" in garbage[i]:
P_idx = i
res += prefix[M_idx]
res += prefix[G_idx]
res += prefix[P_idx]
return res | minimum-amount-of-time-to-collect-garbage | Easy Python Solution using Prefix Sum | siyu_ | 2 | 70 | minimum amount of time to collect garbage | 2,391 | 0.851 | Medium | 32,684 |
https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2696875/Python3-Solution | class Solution:
def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:
m = p = g = -1
self.time = 0
T = [0]
for t in travel: T.append(t)
for i, house in enumerate(garbage):
if 'M' in house: m = i
if 'P' in house: p = i
if 'G' in house: g = i
def DFS(type, x):
for i, house in enumerate(garbage):
if i > x: break
self.time += T[i]
if type in house: self.time += house.count(type)
DFS('M', m)
DFS('P', p)
DFS('G', g)
return self.time | minimum-amount-of-time-to-collect-garbage | Python3 Solution | mediocre-coder | 1 | 139 | minimum amount of time to collect garbage | 2,391 | 0.851 | Medium | 32,685 |
https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2513601/Python-Simple-reversed-traversal-or-100-Space-or-98-Time | class Solution:
def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:
g = m = p = False # whether each truck should drive until the current house
time = 0 # total time needed
# starting from the last house and going backwards, we track which trucks should drive until there by looking at the garbage content.
while len(travel):
t = travel.pop() # travel cost to the current house
s = garbage.pop() # garbage string for the current house
# if at least one truck was not needed for all houses after the current, check if it is needed in this house (and thus for all previous houses).
if sum([g, m, p]) < 3:
if 'G' in s:
g = True
if 'M' in s:
m = True
if 'P' in s:
p = True
# add to the time cost the number of garbage items in this house and the travel costs for the number of tracks that need to drive until here
time += sum([g, m, p]) * t + len(s)
# add the garbage cost for the initial house, where no driving time is needed
time = time + len(garbage[0])
return time | minimum-amount-of-time-to-collect-garbage | [Python] Simple reversed traversal | 100% Space | 98% Time | Sk3_ | 1 | 57 | minimum amount of time to collect garbage | 2,391 | 0.851 | Medium | 32,686 |
https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2494981/Python-Simple-Python-Solution-Using-Prefix-Sum-and-HashMap | class Solution:
def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:
result = 0
prefix_sum = []
for i in range(len(travel)):
if i == 0:
prefix_sum.append(travel[0])
else:
prefix_sum.append(prefix_sum[ i - 1 ] + travel[i])
frequency = {'P': [0,0], 'M': [0,0], 'G': [0,0]}
for i in range(len(garbage)):
G_Count = garbage[i].count('G')
P_Count = garbage[i].count('P')
M_Count = garbage[i].count('M')
if 'P' in garbage[i]:
frequency['P'][0] = frequency['P'][0] + P_Count
frequency['P'][1] = i
if 'M' in garbage[i]:
frequency['M'][0] = frequency['M'][0] + M_Count
frequency['M'][1] = i
if 'G' in garbage[i]:
frequency['G'][0] = frequency['G'][0] + G_Count
frequency['G'][1] = i
for key in frequency:
frequency_count, last_index = frequency[key]
result = result + frequency_count
if last_index != 0:
result = result + prefix_sum[last_index - 1]
return result | minimum-amount-of-time-to-collect-garbage | [ Python ] ✅✅ Simple Python Solution Using Prefix Sum and HashMap 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 1 | 23 | minimum amount of time to collect garbage | 2,391 | 0.851 | Medium | 32,687 |
https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2848432/Python-3-Simple-Solution | class Solution:
def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:
types = ["G", "P", "M"]
score = 0
for t in types:
#boolean set to True once the last instance of a letter is found
last = False
# iterate backwards through garbage
for i in range(len(garbage)-1, -1, -1):
# increment score by 1 for each instance of letter
for letter in garbage[i]:
if letter == t:
score += 1
last = True
#start adding travel once last instance has been found
if last and i !=0:
score += travel[i-1]
return score | minimum-amount-of-time-to-collect-garbage | Python 3 Simple Solution | mbmatthewbrennan | 0 | 1 | minimum amount of time to collect garbage | 2,391 | 0.851 | Medium | 32,688 |
https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2815169/Simple-Python-Approach | class Solution:
def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:
travel.insert(0,0)
#return travel
glass = 0
glassi = [0]
paper = 0
paperi = [0]
metal = 0
metali = [0]
for i in range(0,len(garbage)):
if "G" in garbage[i]:
glass += garbage[i].count("G")
glassi.append(i)
glass += sum(travel[min(glassi): max(glassi) + 1])
for i in range(0,len(garbage)):
if "M" in garbage[i]:
metal += garbage[i].count("M")
metali.append(i)
metal += sum(travel[min(metali): max(metali) + 1])
for i in range(0,len(garbage)):
if "P" in garbage[i]:
paper += garbage[i].count("P")
paperi.append(i)
paper += sum(travel[min(paperi): max(paperi) + 1])
return glass + metal + paper | minimum-amount-of-time-to-collect-garbage | Simple Python Approach | Shagun_Mittal | 0 | 1 | minimum amount of time to collect garbage | 2,391 | 0.851 | Medium | 32,689 |
https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2776217/Python-!-Easy-Approach | class Solution:
def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:
g,p,m = 0,0,0
res = 0
for i in range(len(garbage)-1,-1,-1):
res += len(garbage[i])
if g==0 and "G" in set(garbage[i]):
g = sum(travel[:i])
if p==0 and "P" in set(garbage[i]):
p = sum(travel[:i])
if m==0 and "M" in set(garbage[i]):
m = sum(travel[:i])
return res+g+p+m | minimum-amount-of-time-to-collect-garbage | Python ! Easy Approach | w7Pratham | 0 | 2 | minimum amount of time to collect garbage | 2,391 | 0.851 | Medium | 32,690 |
https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2736417/Python3-Straightfoward-with-comments | class Solution:
def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:
# Find the last appearance of each type of garbage (the furthest each truck will need to go)
# If no stops include a type of garbage, leave it as -1 so we know we don't need that truck
lastG = -1
lastP = -1
lastM = -1
for i in range(len(garbage)-1, -1, -1):
if lastG == -1 and 'G' in garbage[i]:
lastG = i
if lastP == -1 and 'P' in garbage[i]:
lastP = i
if lastM == -1 and 'M' in garbage[i]:
lastM = i
# There are two sources of "time", the travelling and the picking up
total = 0
# Travelling
# We can sum the travel distances up to the last stop for each type of garbage
# If there are no stops (that type = -1), then we can skip it
if lastG != -1: total += sum(travel[:lastG])
if lastP != -1: total += sum(travel[:lastP])
if lastM != -1: total += sum(travel[:lastM])
# Picking Up
# Every instance of garbage must be picked up, regardless of type or location
# So we can just sum all the chars in each stop and add it to the total
for stop in garbage:
total += len(stop)
return total | minimum-amount-of-time-to-collect-garbage | [Python3] Straightfoward with comments | connorthecrowe | 0 | 3 | minimum amount of time to collect garbage | 2,391 | 0.851 | Medium | 32,691 |
https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2707767/Python-greater95 | class Solution:
def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:
G = P = M = 0
for c in garbage[-1]:
if c == "G": G += 1
elif c == "P": P += 1
else: M += 1
for i in range(len(garbage)-2, -1, -1):
if G: G += travel[i]
if P: P += travel[i]
if M: M += travel[i]
for c in garbage[i]:
if c == "G": G += 1
elif c == "P": P += 1
else: M += 1
return G+M+P | minimum-amount-of-time-to-collect-garbage | Python >95% | dionjw | 0 | 2 | minimum amount of time to collect garbage | 2,391 | 0.851 | Medium | 32,692 |
https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2687025/Python-Simple-Solution-Prefix-Sum-faster-than-96.58-of-Python3-online-submissions | class Solution:
def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:
travel = [0]+travel
trucks = ["G","P","M"]
count=0
for i in range(len(trucks)):
k = 0
res = 0
for j in range(len(garbage)):
if track[i] in garbage[j]:
k=j
res += garbage[j].count(trucks[i])
count += res+sum(travel[:k+1])
return count
#Upvote will be encouraging. | minimum-amount-of-time-to-collect-garbage | Python Simple Solution Prefix Sum faster than 96.58% of Python3 online submissions | anshsharma17 | 0 | 11 | minimum amount of time to collect garbage | 2,391 | 0.851 | Medium | 32,693 |
https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2666681/Python-One-run-O(n)O(1)-easy-to-understand-solution | class Solution:
def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:
paper = 0
glass = 0
metal = 0
# this is just a way to make the two list same length
# so now travel[0] is zero means time to reach house 0 is 0
travel = [0] + travel
for i in range(len(garbage) - 1, - 1, -1):
g = garbage[i]
t = travel[i]
paper += g.count('P')
glass += g.count('G')
metal += g.count('M')
# we only add in the time if any garbage is present in
# later houses
if paper > 0:
paper += t
if glass > 0:
glass += t
if metal > 0:
metal += t
return paper + glass + metal | minimum-amount-of-time-to-collect-garbage | [Python] One run O(n)/O(1) easy to understand solution | eaglediao | 0 | 4 | minimum amount of time to collect garbage | 2,391 | 0.851 | Medium | 32,694 |
https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2663234/Python3-2-solutions%3A-while-loop-with-deque.popleft()-for-loop-with-reversed() | class Solution:
def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:
garbage_types_covered = {'M': False, 'P': False, 'G': False}
time = 0
for i, house in enumerate(reversed(garbage)):
time += sum(house.count(garbage_type) for garbage_type in garbage_types_covered)
for garbage_type, covered in garbage_types_covered.items():
if not covered and garbage_type in house:
time += sum(travel[:len(travel)-i])
garbage_types_covered[garbage_type] = True
return time | minimum-amount-of-time-to-collect-garbage | [Python3] 2 solutions: while loop with deque.popleft(); for loop with reversed() | ivnvalex | 0 | 2 | minimum amount of time to collect garbage | 2,391 | 0.851 | Medium | 32,695 |
https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2640803/easy-python-solution | class Solution:
def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:
counter = 0
garbageDict = {}
for i in range(len(garbage)) :
counter += len(garbage[i])
if 'G' in garbage[i] :
garbageDict['G'] = i
if 'P' in garbage[i] :
garbageDict['P'] = i
if 'M' in garbage[i] :
garbageDict['M'] = i
for key in garbageDict.keys() :
counter += sum(travel[:garbageDict[key]])
return counter | minimum-amount-of-time-to-collect-garbage | easy python solution | sghorai | 0 | 15 | minimum amount of time to collect garbage | 2,391 | 0.851 | Medium | 32,696 |
https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2499630/Linear-solution-with-accumulate-75-speed | class Solution:
def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:
g_info = {"M": [0, -1], "P": [0, -1], "G": [0, -1]}
for i, s in enumerate(garbage):
for c in s:
g_info[c][0] += 1
g_info[c][1] = i
acc = list(accumulate(travel, initial=0))
return sum(count + acc[idx] for count, idx in g_info.values()
if idx > -1) | minimum-amount-of-time-to-collect-garbage | Linear solution with accumulate, 75% speed | EvgenySH | 0 | 10 | minimum amount of time to collect garbage | 2,391 | 0.851 | Medium | 32,697 |
https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2498500/Lengthy-code-but-you-like-it...-for-python-beginners-with-explanation | class Solution:
def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:
#Naive approach
#For beginners who just started dsa..
#(1): Finding the last position of each type
m_end,p_end,g_end=0,0,0
for i in range(len(garbage)-1,-1,-1): #Traversing reverse
for j in garbage[i]:
if j=="M": #if it finds the type store value in a m_end and break
m_end=i
break
if(m_end>0): #No need to check for further loops if you get that type..
break
for i in range(len(garbage)-1,-1,-1): #Same as for p_end
for j in garbage[i]:
if j=="P":
p_end=i
break
if(p_end>0):
break
for i in range(len(garbage)-1,-1,-1): #Same as for g_end
for j in garbage[i]:
if j=="G":
g_end=i
break
if(g_end>0):
break
#print(m_end,p_end,g_end) # You can check the values...
#(2) Now Counting the P,G,M in our lists and storing in count_p,count_m,count_g respectively
count_p,count_m,count_g=0,0,0
for i in garbage:
count_p+=i.count("P")
count_m+=i.count("M")
count_g+=i.count("G")
#print(count_p,count_m,count_g) #You can check the values...
#(3) Now, we will evaluate total traveled distance..
p,m,g=0,0,0
if(count_p>0): #Check if there is any "P" in list or not if not than travel will be 0
for i in range(p_end): #loop till the last "P" present in the list
p+=travel[i] #sum the travel
p+=count_p #add the count of "P" as we known to collect the garbage we required 1 minute
#print(p) #You can check the value of p
if(count_m>0): #same as above explanation for "M"
for i in range(m_end):
m+=travel[i]
m+=count_m
#print(m)
if(count_g>0): #same as above explanation for "G"
for i in range(g_end):
g+=travel[i]
g+=count_g
#print(g)
return p+m+g | minimum-amount-of-time-to-collect-garbage | Lengthy code but you like it... for python beginners with explanation | mehtay037 | 0 | 11 | minimum amount of time to collect garbage | 2,391 | 0.851 | Medium | 32,698 |
https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2495480/Simple-Python-Solution | class Solution:
def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:
m = p = g = 0
lm = lp = lg = -1
d = dict()
for i in range(len(garbage)):
d[i] = garbage[i]
for i in range(len(garbage)):
if "G" in garbage[i]:
lg = i
if "P" in garbage[i]:
lp = i
if "M" in garbage[i]:
lm = i
for i in range(len(garbage)):
if lg!=-1:
if i<=lg and "G" in d[i]:
for j in d[i]:
if j=="G":
g+=1
if i>0 and i<=lg:
g+=travel[i-1]
if lm!=-1:
if i<=lm and "M" in d[i]:
for j in d[i]:
if j=="M":
m+=1
if i>0 and i<=lm:
m+=travel[i-1]
if lp!=-1:
if i<=lp and "P" in d[i]:
for j in d[i]:
if j=="P":
p+=1
if i>0 and i<=lp:
p+=travel[i-1]
return m+g+p | minimum-amount-of-time-to-collect-garbage | Simple Python Solution | a_dityamishra | 0 | 7 | minimum amount of time to collect garbage | 2,391 | 0.851 | Medium | 32,699 |
Subsets and Splits