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-deletions-to-make-character-frequencies-unique/discuss/2209096/Boom!!-Python-makes-it-easy.
class Solution: def minDeletions(self, s: str) -> int: deleted_elements = 0 counter = Counter(s) freq_values = sorted(counter.values())[::-1] for index in range(len(freq_values)): while freq_values[index] != 0 and freq_values[index] in freq_values[:index] + freq_values[index+1:]: freq_values[index] -= 1 deleted_elements += 1 return deleted_elements
minimum-deletions-to-make-character-frequencies-unique
Boom!! - Python makes it easy.
yours-truly-rshi
2
127
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,900
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/2207623/Python-Simple-Python-Solution-Using-HashMap-oror-Dictionary
class Solution: def minDeletions(self, s: str) -> int: d = {} result = 0 visted = [] for char in s: if char not in d: d[char] = 1 else: d[char] = d[char] + 1 d = dict(sorted(d.items(), key = lambda x : x[1])) for i in d: if d[i] not in visted: visted.append(d[i]) else: while d[i] != 0: if d[i] not in visted: visted.append(d[i]) break d[i] = d[i] - 1 result = result + 1 return result
minimum-deletions-to-make-character-frequencies-unique
[ Python ] βœ…βœ… Simple Python Solution Using HashMap || Dictionary πŸ₯³βœŒπŸ‘
ASHOK_KUMAR_MEGHVANSHI
2
130
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,901
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/1430139/Python3-or-O(n)-Time-or-O(1)-space-for-larger-n
class Solution: def minDeletions(self, s: str) -> int: count=[0 for i in range(26)] for i in s: count[ord(i)-ord('a')]+=1 count=[i for i in count if i>0] count.sort(reverse=True) mx = max(count) values=0 mn=count[0] for i in range(1,len(count)): if mn<=count[i]: mn=max(mn-1,0) values+=(count[i]-mn) else: mn = count[i] return values
minimum-deletions-to-make-character-frequencies-unique
Python3 | O(n) Time | O(1) space for larger n
HemantRana
2
286
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,902
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/2208062/Python-Simple-Python-Solution-Using-HashMap-oror-Dictionary
class Solution: def minDeletions(self, s: str) -> int: d = {} result = 0 visted = [] for char in s: if char not in d: d[char] = 1 else: d[char] = d[char] + 1 d = dict(sorted(d.items(), key = lambda x : x[1])) for i in d: if d[i] not in visted: visted.append(d[i]) else: while d[i] != 0: if d[i] not in visted: visted.append(d[i]) break d[i] = d[i] - 1 result = result + 1 return result
minimum-deletions-to-make-character-frequencies-unique
[ Python ] βœ…βœ… Simple Python Solution Using HashMap || Dictionary πŸ₯³βœŒπŸ‘
ASHOK_KUMAR_MEGHVANSHI
1
101
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,903
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/2207450/Python3-or-easy-or-explained-or-easy-to-understand-or-Unique-Occurance
class Solution: def minDeletions(self, s: str) -> int: lst=[] for e in set(s): lst.append(s.count(e)) # append the count of each char lst.sort(reverse=True) # sort it in reverse order n = len(lst) ans = 0 for i in range(1, n): if lst[i] == lst[i-1] and lst[i]>0: # check if freq. of ele at index i same. or not with i-1 j=i+1 lst[i]-=1 # if same delete the character ans+=1 # increment the ans as char is deleted while j<n and lst[i] <= lst[j]: # use this loop to delete the char with same freq. if lst[j]>0: lst[j]-=1 ans+=1 # increment the ans as char is deleted j+=1 return ans # return ans
minimum-deletions-to-make-character-frequencies-unique
Python3 | easy | explained | easy to understand | Unique Occurance
H-R-S
1
33
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,904
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/2190985/Python3-Explanation-with-comments-simple-solution
class Solution: def minDeletions(self, s: str) -> int: ## RC ## ## APPROACH : HASHMAP ## ## LOGIC ## ## Lets take an example freq {3,3,3,4,4,4} ## ## 1. We can establish that, distinct freq we can have are {1, 2, 3, 4} ## ## 2. So, obvisouly we add highest freq value as it is, ## 3. for the next highest, if it equal to previous, we delete one character ## ## 4. We repeat the same for other also, ( but instead of deleting one char at a time and checking if it is unique or not, we can store previous value that is added to set and incase if the current value is equal to previous, we add previous value-1 (deleting a character) to set and change prev=previous-1, we stop iterating when we have all distinct freqs and remaning chars should be deleted, in the above example we stop at 2nd 3, so we delete [3,3] and we add [1,2,3,4] to set) counts = collections.Counter(s) final_set = set() for key,val in sorted(counts.items(), key=lambda item: -item[1]): if val not in final_set: final_set.add(val) prev=val else: # indicates it is same freq as prev element final_set.add(prev - 1) prev=prev-1 if prev == 0: break return len(s) - sum(final_set)
minimum-deletions-to-make-character-frequencies-unique
[Python3] Explanation with comments, simple solution
101leetcode
1
40
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,905
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/1075874/Python-simple-greedy-using-Counter
class Solution: def minDeletions(self, s: str) -> int: #listing element quantities: example "ceabaacb" -> [2,1,3,2] s = list(collections.Counter(s).values()) freq, count = set(), 0 for i in s: while i in freq: i -= 1 count += 1 if i > 0: freq.add(i) return count
minimum-deletions-to-make-character-frequencies-unique
Python simple greedy using Counter
Onlycst
1
292
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,906
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/2814974/Python-Recursive-Solution
class Solution: def minDeletions(self, s: str) -> int: from collections import Counter c = Counter(s) res = [] global cnt cnt = 0 def foo(n): global cnt if n not in res: res.append(n) else: cnt += 1 n -= 1 if n!=0: foo(n) for i in c: foo(c[i]) return (cnt)
minimum-deletions-to-make-character-frequencies-unique
Python Recursive Solution
fatin_istiaq
0
1
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,907
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/2555218/Python-Solution-or-O(N2)-or-Brute-Force
class Solution: def minDeletions(self, s: str) -> int: freq = {} for ch in s: freq[ch] = 1 + freq.get(ch, 0) vals = list(freq.values()) vals.sort() ans = 0 if len(vals) > 1: for i in range(1, len(vals)): if vals[i] == vals[i-1]: for x in range(vals[i-1]-1, 0, -1): if x not in vals: ans += (vals[i-1] - x) vals[i-1] = x break else: ans += vals[i-1] vals[i-1] = 0 return ans
minimum-deletions-to-make-character-frequencies-unique
Python Solution | O(N^2) | Brute Force
dos_77
0
31
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,908
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/2268268/Python3-Simple-Solution
class Solution: def minDeletions(self, s: str) -> int: maps = {} for x in s : if x not in maps : maps[x] = 0 maps[x] += 1 maps = [ [v,k] for k,v in maps.items()] maps.sort() counter = 0 x = 1 while x < len(maps) : if maps[x-1][0] > 0 : if maps[x][0] == maps[x-1][0] : counter += 1 maps[x][0] -= 1 x -= 2 maps.sort() x += 1 return counter
minimum-deletions-to-make-character-frequencies-unique
Python3 Simple Solution
jasoriasaksham01
0
84
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,909
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/2210463/Minimum-Deletions-to-Make-Character-Frequencies-Unique-or-Easy-python-solution-using-set
class Solution: def minDeletions(self, s: str) -> int: deletions = 0 char_counts = collections.Counter(s) frequency_set = set() for char,count in char_counts.items(): while count > 0 and count in frequency_set: count -= 1 deletions += 1 frequency_set.add(count) return deletions
minimum-deletions-to-make-character-frequencies-unique
Minimum Deletions to Make Character Frequencies Unique | Easy python solution using set
nishanrahman1994
0
6
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,910
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/2210064/O(N)-Solution-in-Python
class Solution: def minDeletions(self, s: str) -> int: d = {} for c in s: d[c] = d.get(c, 0) + 1 # Calculate indices h = [[] for i in range(len(s)+1)] # make an array for indices. for k in d: val = d[k] # frequency h[val].append(k) # add chars to frequency like in bucket sort for eg s = aabbeeedddd can be [[],[a,b],[e],[d] ] stack = [] # use a stack to store un used frequencies while traversing from start i.e, 0 res = 0 for i in range(len(s)+1): if len(h[i]) == 1: # if frequency is 1 then no need to do anything continue while len(h[i]) > 1: # while frequency is greater than 1 then we take pop() last unused frequency and then subtract the curr_index from last unused index....we have to do that many deletions idx = stack.pop() if len(stack) >0 else 0 # if stack is empty then we will have to delete all the occurences of one charater. res = res + i - idx h[i].pop() # remove the charater from array if len(h[i]) == 0: # unused index stack.append(i) return res
minimum-deletions-to-make-character-frequencies-unique
O(N) Solution in Python
saqibmubarak
0
10
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,911
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/2209893/Python-solution
class Solution: def minDeletions(self, s: str) -> int: char_dict = {} count_set = set() final_count = 0 for i in s: if i in char_dict: char_dict[i] += 1 else: char_dict[i] = 1 sorted(char_dict,key=char_dict.get,reverse=True) char_dict = {k:v for k,v in char_dict.items() if v>0} print(char_dict) for ch in char_dict: count = char_dict[ch] while count in count_set and count>0: count -= 1 final_count += 1 else: count_set.add(count) return final_count
minimum-deletions-to-make-character-frequencies-unique
Python solution
NiketaM
0
6
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,912
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/2209526/Pythonoror-Easy-to-understand-with-explaination-ororGreedy-ApproachororHash-MapororNO-SORTING
class Solution: def minDeletions(self, s: str) -> int: freq,seen_freq,ans={},[],0 for ch in s: #storing character and it's frequency in a hash map freq[ch]=freq.get(ch,0)+1 for character,frequency in freq.items(): #if some previous character had the same frequency #then we decrease it until the frequency is unique #for each such decrement we increase the answer by 1 while frequency in seen_freq and frequency!=0: ans+=1 frequency-=1 #storing the frequency in a list, inorder to compare #the next characters of the string seen_freq.append(frequency) #finally we return the ans return ans
minimum-deletions-to-make-character-frequencies-unique
Python|| Easy to understand with explaination βœ…||Greedy Approach||Hash Map||NO SORTING
695roshan
0
7
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,913
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/2208463/Python3-oror-hashMap
class Solution: def minDeletions(self, s: str) -> int: hashMap, res = {}, 0 for c in s: if c in hashMap.keys(): hashMap[c] += 1 else: hashMap[c] = 1 f_arr = list(hashMap.values()) f_arr.sort(reverse=True) f = f_arr[0] for i in range(len(f_arr)): if f_arr[i] <= f: f = f_arr[i] - 1 else: v = f_arr[i] while v > f: v -= 1 res += 1 f = 0 if (v-1) < 0 else v - 1 return res
minimum-deletions-to-make-character-frequencies-unique
Python3 || hashMap
sagarhasan273
0
3
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,914
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/2208332/Python-or-Easy-solution-using-hashmap
class Solution: def minDeletions(self, s: str) -> int: # creating a hashtable to count each char frequrncy d = {} count = 0 uniquelst = [] for c in s: d[c] = 1 + d.get(c,0) for _,v in d.items(): while v > 0 and v in uniquelst: count += 1 v -= 1 if v not in uniquelst: uniquelst.append(v) return count
minimum-deletions-to-make-character-frequencies-unique
Python | Easy solution using hashmap
__Asrar
0
18
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,915
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/2208318/Python3-oror-Very-Simple-Solution-oror-Easy-to-understand-oror-Greedy-approach
class Solution: def minDeletions(self, s: str) -> int: C=Counter(s) l=list(C.values()) l.sort(reverse=True) s=sum(l) cnt=pr=l[0] #cnt for Count and pr for previous value for i in l[1:]: if i==pr: cnt+=i-1 pr=i-1 elif i<pr: cnt+=i pr=i else: cnt+=pr-1 pr-=1 if pr==0: break return s-cnt
minimum-deletions-to-make-character-frequencies-unique
Python3 || Very Simple Solution || Easy to understand || Greedy approach
aditya1292
0
4
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,916
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/2207988/Python3-Solution
class Solution: def minDeletions(self, s: str) -> int: counter = Counter(s) freq_set = set() # we use a set to keep track of the unique frequency count res = 0 # sort the string in decreasing order by the frequency # for count in sorted(counter.values(), reverse = True): # check if the frequency already exist in the set or we # decrease it until 0 (ignoring it) # # keep decreasing if it already exist # while count in freq_set and count > 0: count -= 1 res += 1 freq_set.add(count) return res
minimum-deletions-to-make-character-frequencies-unique
Python3 Solution
M-Phuykong
0
11
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,917
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/2207490/Python3-Greedy-oror-hashset
class Solution: def minDeletions(self, s: str) -> int: hashset=set() freq=Counter(s) # count the frequency of each character ans=0 for j in freq.values(): if j not in hashset: # if the frequency is not yet appeared in hashset it means it is unique hashset.add(j) # add it to hashset else: # if freq of char appeared before while j in hashset and j>0: # just decrease its freq(delete some of the characters) j-=1 ans+=1 # count the number of char deleted hashset.add(j) # add the new freq to hashset return ans
minimum-deletions-to-make-character-frequencies-unique
Python3 Greedy || hashset
akshat12199
0
9
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,918
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/2207322/Easy-to-understand!
class Solution: def minDeletions(self, s: str) -> int: """ Make a dict named frequency, record the number of every frequency. Traverse every frequency, if the number of it >1, move one of it to frequency<i and the quantity==0,record the distance when moving frequency. Worst time comlexity: O(n^2), space comlexity: O(n) """ # Make the frequency dict counter=collections.Counter(s) frequency=collections.Counter(counter.values()) # Move frequency to where==0 or move to 0 ans=0 frequencyList=list(frequency.keys()) for i in frequencyList: while frequency[i]>1: d=i-1 while d>0 and frequency[d]>0: d-=1 frequency[d]+=1 frequency[i]-=1 ans+=i-d return ans
minimum-deletions-to-make-character-frequencies-unique
Easy to understand!
XRFXRF
0
15
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,919
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/2207146/Python-using-counter.-Time%3A-O(N).-Space%3A-O(N)
class Solution: def minDeletions(self, s: str) -> int: count = sorted(Counter(s).values()) result = 0 for idx in range(len(count) - 2, -1, -1): if count[idx] >= count[idx + 1]: result += min(count[idx], count[idx] - count[idx+1] + 1) count[idx] = max(count[idx+1] - 1, 0) return result
minimum-deletions-to-make-character-frequencies-unique
Python, using counter. Time: O(N). Space: O(N)
blue_sky5
0
40
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,920
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/2201069/Solution-using-DictionaryHash-with-detailed-explanation
class Solution: def minDeletions(self, s: str) -> int: charcountdict={} for letter in s: if letter not in charcountdict: charcountdict[letter]=1 else: charcountdict[letter]+=1 countlist=list(charcountdict.values()) removecount=0 for i in range(0,len(countlist)): while (countlist[i] in countlist[:i:]) or (countlist[i] in countlist[i+1::]): removecount+=1 countlist[i]-=1 if(countlist[i]==0): break return removecount
minimum-deletions-to-make-character-frequencies-unique
Solution using Dictionary/Hash with detailed explanation
yogeshwarb
0
15
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,921
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/2177818/Python-easy-to-read-and-understand-or-hashmap
class Solution: def minDeletions(self, s: str) -> int: d = {} for i in s: d[i] = d.get(i, 0) + 1 seen = set() items = sorted(d.values(), reverse=True) ans = 0 for val in items: while val in seen: val -= 1 ans += 1 if val:seen.add(val) return ans
minimum-deletions-to-make-character-frequencies-unique
Python easy to read and understand | hashmap
sanial2001
0
33
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,922
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/1921268/Python3-Solution
class Solution: def minDeletions(self, s: str) -> int: cnt = 0 d = {} auxSet = set({}) for i in s: if i in d: d[i] += 1 else: d[i] = 1 distinctValuesList = d.values() for cn in distinctValuesList: if cn not in auxSet: auxSet.add(cn) else: ini = cn while ini > 0: ini -= 1 if ini not in auxSet: auxSet.add(ini) break cnt += cn-ini return cnt
minimum-deletions-to-make-character-frequencies-unique
Python3 Solution
DietCoke777
0
62
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,923
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/1798035/python-solution-using-max-heap
class Solution: def minDeletions(self, s: str) -> int: pq = [-v for k, v in Counter(s).items()] heapify(pq) count = 0 while pq: v = heappop(pq) if not pq: break vv = pq[0] if v == vv: if -v - 1 > 0: heappush(pq, v + 1) count += 1 return count
minimum-deletions-to-make-character-frequencies-unique
python solution using max heap
23333_tragedy
0
74
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,924
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/1166996/Python-3-or-distributing-over-a-dictionary
class Solution: def minDeletions(self, s: str) -> int: #collect the frequency of the symbols in dictionary{symbol:frequency} frequency={} for i in s: try: frequency[i]=frequency[i]+1 except: frequency[i]=1 working_list=list() #get only the frequencies in a list values = list(frequency.values()) #insert in the frequencies in a dictionary with freqency as the key #if there is a collision for a frequency, decrement the value and insert #it in the next possible position #return the number of collison linechart={} deletion=0 values.sort() #print(values) lb=0 for i in values: z=i try: while(True): if z==lb : deletion=deletion+lb lb=i break if linechart[z]: z=z-1 deletion=deletion+1 except: linechart[z]=True return deletion
minimum-deletions-to-make-character-frequencies-unique
Python 3 | distributing over a dictionary
vjpn97
0
101
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,925
https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/1146503/Python3-easy-solution-using-dictionary
class Solution: def minDeletions(self, s: str) -> int: cnt_dict = {} for c in s: if c in cnt_dict: cnt_dict[c]+=1 else: cnt_dict[c]=1 #Store the frequency of each character in a dictionary cnt_dict = {k: v for k, v in sorted(cnt_dict.items(), reverse=True, key=lambda item: item[1])} #Sort the dictionary in a non-increasing order of the frequencies freq_found = [] #Store which frequencies have been found till now res = 0 #Store how many characters to remove to make frequencies unique for c in cnt_dict.keys(): while cnt_dict[c]>0 and cnt_dict[c] in freq_found: #Don't reduce the frequency if the frequency is already 0 cnt_dict[c]-=1 res+=1 freq_found.append(cnt_dict[c]) #Found a unique frequency, append to the list return res
minimum-deletions-to-make-character-frequencies-unique
Python3 easy solution using dictionary
bPapan
0
216
minimum deletions to make character frequencies unique
1,647
0.592
Medium
23,926
https://leetcode.com/problems/sell-diminishing-valued-colored-balls/discuss/927674/Python3-Greedy
class Solution: def maxProfit(self, inventory: List[int], orders: int) -> int: inventory.sort(reverse=True) # inventory high to low inventory += [0] ans = 0 k = 1 for i in range(len(inventory)-1): if inventory[i] > inventory[i+1]: if k*(inventory[i] - inventory[i+1]) < orders: ans += k*(inventory[i] + inventory[i+1] + 1)*(inventory[i] - inventory[i+1])//2 # arithmic sum orders -= k*(inventory[i] - inventory[i+1]) else: q, r = divmod(orders, k) ans += k*(2*inventory[i] - q + 1) * q//2 + r*(inventory[i] - q) return ans % 1_000_000_007 k += 1
sell-diminishing-valued-colored-balls
[Python3] Greedy
ye15
32
5,200
sell diminishing valued colored balls
1,648
0.305
Medium
23,927
https://leetcode.com/problems/sell-diminishing-valued-colored-balls/discuss/927674/Python3-Greedy
class Solution: def maxProfit(self, inventory: List[int], orders: int) -> int: fn = lambda x: sum(max(0, xx - x) for xx in inventory) # balls sold # last true binary search lo, hi = 0, 10**9 while lo < hi: mid = lo + hi + 1 >> 1 if fn(mid) >= orders: lo = mid else: hi = mid - 1 ans = sum((x + lo + 1)*(x - lo)//2 for x in inventory if x > lo) return (ans - (fn(lo) - orders) * (lo + 1)) % 1_000_000_007
sell-diminishing-valued-colored-balls
[Python3] Greedy
ye15
32
5,200
sell diminishing valued colored balls
1,648
0.305
Medium
23,928
https://leetcode.com/problems/sell-diminishing-valued-colored-balls/discuss/2807111/Python3-Solution-or-Sorting-or-O(nlogn)
class Solution: def maxProfit(self, A, O): nsum = lambda n : (n * (n + 1)) // 2 A.sort(reverse = True) A.append(0) ans, mod = 0, 10 ** 9 + 7 for i in range(len(A) - 1): if (i + 1) * (A[i] - A[i + 1]) > O: k, l = O // (i + 1), O % (i + 1) return (ans + (i + 1) * (nsum(A[i]) - nsum(A[i] - k)) + l * (A[i] - k)) % mod ans = (ans + (i + 1) * (nsum(A[i]) - nsum(A[i + 1]))) % mod O -= (i + 1) * (A[i] - A[i + 1]) return ans
sell-diminishing-valued-colored-balls
βœ” Python3 Solution | Sorting | O(nlogn)
satyam2001
1
43
sell diminishing valued colored balls
1,648
0.305
Medium
23,929
https://leetcode.com/problems/sell-diminishing-valued-colored-balls/discuss/1306530/Python-Binary-Search-and-Arithmetic-series-formula-680ms
class Solution: def maxProfit(self, inventory: List[int], orders: int) -> int: inventory.sort(reverse=True) inventory.append(0) p = 0 for i in range(10**5): if inventory[i]>inventory[i+1]: if (i+1)*(inventory[i]-inventory[i+1])>=orders: left, right = inventory[i+1]+1, inventory[i] while left<=right: mid = (left+right)//2 numBalls = (inventory[i]-mid+1)*(i+1) if 0<=numBalls-orders<i+1: k = numBalls-orders p += ((inventory[i]+mid)*(inventory[i]-mid+1)//2)*(i+1)-(k*mid) return p%1000000007 elif numBalls<orders: right = mid-1 else: left = mid+1 else: orders -= (i+1)*(inventory[i]-inventory[i+1]) p += ((inventory[i]+inventory[i+1]+1)*(inventory[i]-inventory[i+1])//2)*(i+1)
sell-diminishing-valued-colored-balls
Python Binary Search & Arithmetic series formula 680ms
johnnylu305
1
743
sell diminishing valued colored balls
1,648
0.305
Medium
23,930
https://leetcode.com/problems/sell-diminishing-valued-colored-balls/discuss/1970689/Python3-or-Binary-Search
class Solution: def maxProfit(self, inventory: List[int], orders: int) -> int: left = 0 right = max(inventory) while right - left > 1: mid = left + (right - left) // 2 sold_balls = sum(inv - mid for inv in inventory if inv > mid) if sold_balls > orders: left = mid else: right = mid sold_balls = total = 0 def gausian_sum(val): return (val * (val + 1)) // 2 for inv in inventory: if inv > right: sold_balls += (inv - right) total += gausian_sum(inv) - gausian_sum(right) if sold_balls < orders: total += (orders - sold_balls) * right return total % (10**9 + 7) credit: @EvgenySH
sell-diminishing-valued-colored-balls
Python3 | Binary Search
showing_up_each_day
-1
207
sell diminishing valued colored balls
1,648
0.305
Medium
23,931
https://leetcode.com/problems/sell-diminishing-valued-colored-balls/discuss/1934512/Python3-Greedy-READABLE-Solution-for-Dummies-by-a-Dummy
class Solution: def maxProfit(self, inventory: List[int], orders: int) -> int: inventory.sort(reverse=True) N = len(inventory) width = 1 total = 0 # sum of Arthematic Progression def sumAP(startHeight, endHeight): sum1 = startHeight * (startHeight + 1) // 2 sum2 = endHeight * (endHeight + 1) // 2 return sum1 - sum2 i = 0 while orders > 0: startHeight = inventory[i] endHeight = inventory[i+1] if i < N-1 else 0 if width * (startHeight - endHeight) < orders: total += width * sumAP(startHeight, endHeight) orders -= width * (startHeight - endHeight) else: # enters else only once at the end q, r = divmod(orders, width) endHeight = inventory[i] - q total += width * sumAP(startHeight, endHeight) total += r * (startHeight - q) return total % (10 ** 9 + 7) width += 1 i += 1
sell-diminishing-valued-colored-balls
Python3 Greedy READABLE Solution for Dummies by a Dummy
moreCreativeUsername
-1
141
sell diminishing valued colored balls
1,648
0.305
Medium
23,932
https://leetcode.com/problems/defuse-the-bomb/discuss/1903674/Python-Solution
class Solution: def decrypt(self, code: List[int], k: int) -> List[int]: if k == 0: return [0] * len(code) data = code + code result = [sum(data[i + 1: i + 1 + abs(k)]) for i in range(len(code))] # result = [] # for i in range(len(code)): # result.append(sum(data[i + 1: i + 1 + abs(k)])) if 0 > k: return result[k - 1:] + result[:k - 1] return result
defuse-the-bomb
Python Solution
hgalytoby
2
142
defuse the bomb
1,652
0.612
Easy
23,933
https://leetcode.com/problems/defuse-the-bomb/discuss/2677931/Python3-oror-TC-O(N)SCO(1)-oror-Optimized-Solution
class Solution: def helper(self,code,k): res = [] total = sum(code[1:k+1]) res.append(total) i,j = 1,k+1 while i<len(code): if j==len(code): j = 0 total+=-code[i]+code[j] res.append(total) j+=1 i+=1 return res def decrypt(self, code: List[int], k: int) -> List[int]: if k==0: return [0]*len(code) if k>0: return self.helper(code,k) code = code[::-1] k=-1*k lst = self.helper(code,k) return lst[::-1]
defuse-the-bomb
Python3 || TC = O(N),SC=O(1) || Optimized Solution
shacid
0
15
defuse the bomb
1,652
0.612
Easy
23,934
https://leetcode.com/problems/defuse-the-bomb/discuss/2640698/An-Approach-Using-Modulo-and-Nested-Loops
class Solution: def decrypt(self, code: List[int], k: int) -> List[int]: if k == 0: return [0] * len(code) cracked = [] * len(code) if k < 0: for i in range(len(code)): total = 0 for j in range(i - 1, i + k - 1, -1): total += code[j % len(code)] cracked.append(total) else: for i in range(len(code)): total = 0 for j in range(i + 1, i + k + 1): total += code[j % len(code)] cracked.append(total) return cracked
defuse-the-bomb
An Approach Using Modulo and Nested Loops
kcstar
0
11
defuse the bomb
1,652
0.612
Easy
23,935
https://leetcode.com/problems/defuse-the-bomb/discuss/2522873/Python-3-or-easy-to-understand
class Solution: def decrypt(self, code: List[int], k: int) -> List[int]: # replace every number with 0 if k == 0: return [0] * len(code) sum = 0 res = [] if k > 0: left = 0 # for 0th number, get sum of next k numbers # Note: k < len(code) as per constraint in description while left < k: left = left + 1 sum += code[left] res.append(sum) # for 1...n, increment left ptr # sum[curr] = sum[curr - 1] - code[curr] + code[left_ptr] for curr in range(1, len(code)): left = (left + 1) % len(code) sum -= code[curr] sum += code[left] res.append(sum) else: right = len(code) # for 0th number, get sum of previous k numbers # Note: k < -(len(code)) as per constraint in description while (len(code) - right) < abs(k): right = right - 1 sum += code[right] res.append(sum) # for 0...n, increment right ptr # sum[curr + 1] = sum[curr] + code[curr] - code[right_ptr] for curr in range(0, len(code) - 1): sum += code[curr] sum -= code[right] right = (right + 1) % len(code) res.append(sum) return res
defuse-the-bomb
Python 3 | easy to understand
user7726Y
0
25
defuse the bomb
1,652
0.612
Easy
23,936
https://leetcode.com/problems/defuse-the-bomb/discuss/2440184/Python3
class Solution: def decrypt(self, code: List[int], k: int) -> List[int]: if k>0: code+=code[:k] for i in range(len(code)-k): summ=0 for j in range(i+1,i+k+1): summ+=code[j] code[i]=summ for i in range(k): code.pop() elif k<0: code=code[len(code)-abs(k):]+code for i in range(len(code)-1,abs(k)-1,-1): summ=0 for j in range(i-abs(k),i): summ+=code[j] code[i]=summ for i in range(abs(k)): code.pop(0) else: for i in range(len(code)): code[i]=0 return code
defuse-the-bomb
Python3
aditya_maskar
0
43
defuse the bomb
1,652
0.612
Easy
23,937
https://leetcode.com/problems/defuse-the-bomb/discuss/2440184/Python3
class Solution: def decrypt(self, code: List[int], k: int) -> List[int]: if k>0: code+=code[:k] for i in range(len(code)-k): code[i]= sum(code[i+1:i+k+1]) code = code[:len(code)-k] elif k<0: code=code[len(code)-abs(k):]+code for i in range(len(code)-1,abs(k)-1,-1): code[i] = sum(code[i-abs(k):i]) code = code[abs(k):] else: for i in range(len(code)): code[i]=0 return code
defuse-the-bomb
Python3
aditya_maskar
0
43
defuse the bomb
1,652
0.612
Easy
23,938
https://leetcode.com/problems/defuse-the-bomb/discuss/1895586/Python3-Simple-Easy-to-Understand-List-Generator
class Solution: def decrypt(self, code: List[int], k: int) -> List[int]: n=len(code) return [ sum( [ code[(i+1+l)%n] if k>=0 else code[(i-1-l)%n] for l in range(abs(k)) ] ) for i in range(n) ]
defuse-the-bomb
Python3 Simple Easy to Understand List Generator
Forest-Dewberry
0
56
defuse the bomb
1,652
0.612
Easy
23,939
https://leetcode.com/problems/defuse-the-bomb/discuss/1816147/5-Lines-Python-Solution-oror-90-Faster(40ms)-oror-Memory-less-than-92
class Solution: def decrypt(self, code: List[int], k: int) -> List[int]: ans=[] ; l=len(code) ; code_=code*3 if k==0: return [0]*l elif k>0: [ans.append(sum(code_[l+i+1:l+i+k+1])) for i in range(l)] else: [ans.append(sum(code_[l+i+k:l+i])) for i in range(l)] return ans
defuse-the-bomb
5-Lines Python Solution || 90% Faster(40ms) || Memory less than 92%
Taha-C
0
43
defuse the bomb
1,652
0.612
Easy
23,940
https://leetcode.com/problems/defuse-the-bomb/discuss/1763942/Python-dollarolution
class Solution: def decrypt(self, code: List[int], k: int) -> List[int]: v = code*2 if k < 0: for i in range(len(v)//2,len(v)): code[i-len(code)] = sum(v[i+k:i]) else: for i in range(len(code)): code[i] = sum(v[i+1:i+k+1]) return code
defuse-the-bomb
Python $olution
AakRay
0
46
defuse the bomb
1,652
0.612
Easy
23,941
https://leetcode.com/problems/defuse-the-bomb/discuss/1750935/Python-Easy-Solution
class Solution: def decrypt(self, code: List[int], k: int) -> List[int]: l = len(code) ans = code code = code + code + code for i in range(l,2*l): ans[i-l] =0 if k == 0: return [0]*l elif k > 0: for j in range(1,k+1): ans[i-l] = ans[i-l]+code[i+j] else: for j in range(1,-k+1): ans[i-l] = ans[i-l]+code[i-j] return ans
defuse-the-bomb
Python Easy Solution
MengyingLin
0
52
defuse the bomb
1,652
0.612
Easy
23,942
https://leetcode.com/problems/defuse-the-bomb/discuss/1241434/Python-O(n)-time-O(1)-additional-space-Re-use-array
class Solution: def decrypt(self, A: List[int], k: int) -> List[int]: n = len(A) mod = 101 if k == 0: for i in range(n): A[i] = 0 return A start, end = 1, k if k < 0: k = -k start, end = n - k, n - 1 curr = sum(A[i] for i in range(start, end + 1)) for i in range(n): A[i] += curr * mod curr -= A[start] % mod start = (start + 1) % n end = (end + 1) % n curr += A[end] % mod for i in range(n): A[i] //= mod return A
defuse-the-bomb
Python O(n) time, O(1) additional space, Re-use array
omars1515
0
164
defuse the bomb
1,652
0.612
Easy
23,943
https://leetcode.com/problems/defuse-the-bomb/discuss/1026846/Python3-via-prefix-sum
class Solution: def decrypt(self, code: List[int], k: int) -> List[int]: n = len(code) code *= 2 # augmenting array prefix = [0] # prefix sum (w/ leading 0) for x in code: prefix.append(prefix[-1] + x) ans = [] for i in range(n): if k >= 0: ans.append(prefix[i+k+1] - prefix[i+1]) else: ans.append(prefix[i+n] - prefix[i+n+k]) return ans
defuse-the-bomb
[Python3] via prefix sum
ye15
0
81
defuse the bomb
1,652
0.612
Easy
23,944
https://leetcode.com/problems/defuse-the-bomb/discuss/1026846/Python3-via-prefix-sum
class Solution: def decrypt(self, code: List[int], k: int) -> List[int]: if k < 0: return self.decrypt(code[::-1], -k)[::-1] prefix = [0] # prefix sum (w/ leading 0) for x in code*2: prefix.append(prefix[-1] + x) ans = [] for i in range(len(code)): ans.append(prefix[i+k+1] - prefix[i+1]) return ans
defuse-the-bomb
[Python3] via prefix sum
ye15
0
81
defuse the bomb
1,652
0.612
Easy
23,945
https://leetcode.com/problems/defuse-the-bomb/discuss/1026846/Python3-via-prefix-sum
class Solution: def decrypt(self, code: List[int], k: int) -> List[int]: if k < 0: return self.decrypt(code[::-1], -k)[::-1] ans, x = [], 0 # range sum for i in range(len(code) + k): x += code[i%len(code)] if i >= k: x -= code[i-k] ans.append(x) return ans
defuse-the-bomb
[Python3] via prefix sum
ye15
0
81
defuse the bomb
1,652
0.612
Easy
23,946
https://leetcode.com/problems/defuse-the-bomb/discuss/1013248/Python3-easy-solution.
class Solution: def decrypt(self, code: List[int], k: int) -> List[int]: size=len(code) temp=nums*2 if k>0: for i in range(size): code[i]=sum(temp[i+1:i+k+1]) elif k<0: for i in range(size,size*2): code[i-size]=sum(temp[i-1:i+k-1:-1]) else: code = [0]*size return nums
defuse-the-bomb
Python3 easy solution.
heimdall2308
0
71
defuse the bomb
1,652
0.612
Easy
23,947
https://leetcode.com/problems/defuse-the-bomb/discuss/943365/Intuitive-approach
class Solution: def decrypt(self, code: List[int], k: int) -> List[int]: decoded_nums = [] def decode(pos, k=k, code=code): decode_num = 0 if k != 0: for i in range(1, abs(k)+1): new_pos = pos + (i if k > 0 else -i) new_pos = new_pos % len(code) if new_pos > 0 else new_pos decode_num += code[new_pos] else: pass return decode_num for i in range(len(code)): decoded_nums.append(decode(i)) return decoded_nums
defuse-the-bomb
Intuitive approach
puremonkey2001
0
55
defuse the bomb
1,652
0.612
Easy
23,948
https://leetcode.com/problems/defuse-the-bomb/discuss/936785/Python-Explanation-Doubling-length-of-array
class Solution: def decrypt(self, code: List[int], k: int) -> List[int]: """ If k > 0, replace the ith number with the sum of the next k numbers. If k < 0, replace the ith number with the sum of the previous k numbers. If k == 0, replace the ith number with 0. """ # If k is 0, then return an array of zeroes if k == 0: return [0 for _ in range(len(code))] elif k > 0: # Double the length of the given array, and return the sums of the ranges tmp = code + code return [sum(tmp[i+1:i+k+1]) for i in range(len(code))] else: # Double the length of the given array, and return the sums of the ranges tmp = code + code n = len(code) return [sum(tmp[i+n+k:i+n]) for i in range(len(code))]
defuse-the-bomb
Python – Explanation – Doubling length of array
ericklarac
0
96
defuse the bomb
1,652
0.612
Easy
23,949
https://leetcode.com/problems/defuse-the-bomb/discuss/1073821/Python3-simple-and-easy-to-understand-solution
class Solution: def decrypt(self, code: List[int], k: int) -> List[int]: n = len(code) z = code.copy() y = code.copy() if k == 0: z = [0]*n elif k > 0: y += code for i in range(n): z[i] = sum(y[i+1 : i+k+1]) else: y = code + z k = abs(k) for i in range(n): z[i] = sum(y[i+n-k : i+n]) return z
defuse-the-bomb
Python3 simple and easy to understand solution
EklavyaJoshi
-1
118
defuse the bomb
1,652
0.612
Easy
23,950
https://leetcode.com/problems/defuse-the-bomb/discuss/1016113/Ultra-Simple-CppPython3-Solution-or-Suggestions-for-optimization-are-welcomed-or
class Solution: def decrypt(self, code: List[int], k: int) -> List[int]: s=0 temp=0 ans=[] for i in range(0,len(code)): temp=k s=0 if temp==0: ans.append(0) elif temp>0: j=i+1 while temp>0 and j<len(code): s+=code[j] j=j+1 temp=temp-1 if temp>0: j=0 while temp>0 and j<len(code): s+=code[j] j=j+1 temp=temp-1 ans.append(s) else: temp=temp*(-1) j=i-1 while j>=0 and temp>0: s+=code[j] j=j-1 temp=temp-1 if temp>0: j=len(code)-1 while j>=0 and temp>0: s+=code[j] j=j-1 temp=temp-1 ans.append(s) return ans
defuse-the-bomb
Ultra Simple Cpp/Python3 Solution | Suggestions for optimization are welcomed |
angiras_rohit
-1
90
defuse the bomb
1,652
0.612
Easy
23,951
https://leetcode.com/problems/minimum-deletions-to-make-string-balanced/discuss/1020107/Python-DP-solution-easy-to-understand
class Solution: def minimumDeletions(self, s: str) -> int: # track the minimum number of deletions to make the current string balanced ending with 'a', 'b' end_a, end_b = 0,0 for val in s: if val == 'a': # to end with 'a', nothing to do with previous ending with 'a' # to end with 'b', need to delete the current 'a' from previous ending with 'b' end_b += 1 else: # to end with 'a', need to delete the current 'b' from previous ending with 'a' # to end with 'b', nothing to do, so just pick smaller of end_a, end_b end_a, end_b = end_a+1, min(end_a, end_b) return min(end_a, end_b)
minimum-deletions-to-make-string-balanced
[Python] DP solution easy to understand
cloverpku
12
1,100
minimum deletions to make string balanced
1,653
0.588
Medium
23,952
https://leetcode.com/problems/minimum-deletions-to-make-string-balanced/discuss/1912995/Python-easy-to-read-and-understand-or-stack
class Solution: def minimumDeletions(self, s: str) -> int: stack, res = [], 0 for i in range(len(s)): if stack and s[i] == "a" and stack[-1] == "b": stack.pop() res += 1 else: stack.append(s[i]) return res
minimum-deletions-to-make-string-balanced
Python easy to read and understand | stack
sanial2001
6
231
minimum deletions to make string balanced
1,653
0.588
Medium
23,953
https://leetcode.com/problems/minimum-deletions-to-make-string-balanced/discuss/1452670/Python-Stack-or-Beats-95
class Solution: def minimumDeletions(self, s: str) -> int: count = 0 stack = [] for c in s: if c == 'b': stack.append(c) elif stack: stack.pop() count += 1 return count
minimum-deletions-to-make-string-balanced
Python Stack | Beats 95%
russellh
4
294
minimum deletions to make string balanced
1,653
0.588
Medium
23,954
https://leetcode.com/problems/minimum-deletions-to-make-string-balanced/discuss/1093898/Python3-greedy
class Solution: def minimumDeletions(self, s: str) -> int: ans = suffix = 0 for c in reversed(s): if c == "a": suffix += 1 else: ans = min(1 + ans, suffix) return ans
minimum-deletions-to-make-string-balanced
[Python3] greedy
ye15
3
128
minimum deletions to make string balanced
1,653
0.588
Medium
23,955
https://leetcode.com/problems/minimum-deletions-to-make-string-balanced/discuss/1948314/WEEB-DOES-PYTHONC%2B%2B-PREFIX-%2B-SUFFIX-SUM
class Solution: def minimumDeletions(self, s: str) -> int: preSum = [0] * (len(s) + 1) sufSum = [0] * (len(s) + 1) for i in range(len(s)): if s[i] == "a": preSum[i] += 1 + preSum[i-1] else: preSum[i] = preSum[i-1] if s[len(s)-i-1] == "b": sufSum[len(s)-i-1] += 1 + sufSum[len(s)-i] else: sufSum[len(s)-i-1] += sufSum[len(s)-i] maxStringLength = 0 for i in range(len(s)): if preSum[i] + sufSum[i] > maxStringLength: maxStringLength = preSum[i] + sufSum[i] return len(s) - maxStringLength
minimum-deletions-to-make-string-balanced
WEEB DOES PYTHON/C++ PREFIX + SUFFIX SUM
Skywalker5423
1
112
minimum deletions to make string balanced
1,653
0.588
Medium
23,956
https://leetcode.com/problems/minimum-deletions-to-make-string-balanced/discuss/2793615/Python-98-beats-Time
class Solution: def minimumDeletions(self, s: str) -> int: l=len(s) i=0 while i<l and s[i]!='b': i+=1 j=l-1 while j>=0 and s[j]!='a': j-=1 if i==l or j==-1: return 0 ca=0 cb=0 ans=0 for k in range(i,j+1): if s[k]=='a': if cb>0: if ca>=cb: ans+=cb ca=0 cb=0 else: ca+=1 else: cb+=1 ans+=min(ca,cb) return ans
minimum-deletions-to-make-string-balanced
Python 98% beats Time
RjRahul003
0
3
minimum deletions to make string balanced
1,653
0.588
Medium
23,957
https://leetcode.com/problems/minimum-deletions-to-make-string-balanced/discuss/2687358/Python3-or-Linear-DP
class Solution: def minimumDeletions(self, s: str) -> int: cntB=0 n=len(s) dp=[0]*n for i in range(n): if s[i]=='b': cntB+=1 dp[i]=dp[i-1] if i>=1 else dp[i] else: val=dp[i-1]+1 if i>=1 else 1 dp[i]=min(cntB,val) return dp[-1]
minimum-deletions-to-make-string-balanced
[Python3] | Linear DP
swapnilsingh421
0
12
minimum deletions to make string balanced
1,653
0.588
Medium
23,958
https://leetcode.com/problems/minimum-deletions-to-make-string-balanced/discuss/2016830/Python-solution-with-O(n)-using-stack
class Solution: def minimumDeletions(self, s: str) -> int: stack = [] res = 0 for i in s: # checking stack is empty or not to avoid errors #if last element in stack is 'b' then the present character is 'a' this case will wrong # so we pop the stack and increse the count if len(stack)!=0 and stack[-1]=='b' and i != 'b': stack.pop() res+=1 #if everything is fine we just push element into the stack else: stack.append(i) return res
minimum-deletions-to-make-string-balanced
Python solution with O(n) using stack
Vamsidhar01
0
129
minimum deletions to make string balanced
1,653
0.588
Medium
23,959
https://leetcode.com/problems/minimum-deletions-to-make-string-balanced/discuss/1952754/Python3-Solution-with-using-dp-approach
class Solution: """ if char == 'b' -> no more cost if char == 'a': 1. move all 'b' before 'a' -> cost += cnt_b 2. remove 'a' -> cost += 1 """ def minimumDeletions(self, s: str) -> int: res = 0 cnt_b = 0 for char in s: if char == 'b': cnt_b += 1 else: res = min(res + 1, cnt_b) return res
minimum-deletions-to-make-string-balanced
[Python3] Solution with using dp approach
maosipov11
0
83
minimum deletions to make string balanced
1,653
0.588
Medium
23,960
https://leetcode.com/problems/minimum-deletions-to-make-string-balanced/discuss/1348883/Easy-to-understand%3A-Python-solution
class Solution: def minimumDeletions(self, s: str) -> int: # consider each index as b start # count left_a, left_b, right_a, right_b on L/R at each point # num_changes = left_b + right_a counts = {} n = len(s) left_a, left_b, right_a, right_b = 0, 0, s.count('a'), s.count('b') for i in range(n): counts[i] = (left_a, left_b, right_a, right_b) if s[i] == 'a': left_a += 1 right_a -= 1 elif s[i] == 'b': left_b += 1 right_b -= 1 counts[n] = (left_a, left_b, right_a, right_b) min_changes = float('inf') for i in range(n + 1): left_b, right_a = counts[i][1], counts[i][2] min_changes = min(min_changes, left_b + right_a) return min_changes
minimum-deletions-to-make-string-balanced
Easy to understand: Python solution
sherryfansf
0
257
minimum deletions to make string balanced
1,653
0.588
Medium
23,961
https://leetcode.com/problems/minimum-deletions-to-make-string-balanced/discuss/1245883/easy-to-understand-greedy-python
class Solution: def minimumDeletions(self, s: str) -> int: n = float("inf") na = s.count("a") nb = 0 for i in range(len(s)): if s[i]=="a": na -= 1 elif s[i]=="b": nb += 1 n = min(na + nb,n) return min(n,s.count("a"),s.count("b"))
minimum-deletions-to-make-string-balanced
easy to understand, greedy, python
albertnew2018
0
153
minimum deletions to make string balanced
1,653
0.588
Medium
23,962
https://leetcode.com/problems/minimum-deletions-to-make-string-balanced/discuss/1182576/Python%3A-Two-Ideas
class Solution: def minimumDeletions(self, s: str) -> int: def recurse(i, j): if i == len(s): return 0 return recurse(i+1, j) + (s[i] == ('b' if i <= j else 'a')) return min([recurse(0, j) for j in range(-1, len(s)+1)])
minimum-deletions-to-make-string-balanced
Python: Two Ideas
dev-josh
0
189
minimum deletions to make string balanced
1,653
0.588
Medium
23,963
https://leetcode.com/problems/minimum-deletions-to-make-string-balanced/discuss/1182576/Python%3A-Two-Ideas
class Solution: def minimumDeletions(self, s: str) -> int: a_idx = [0] + list(itertools.accumulate([1 if c == 'a' else 0 for c in s])) b_idx = [0] + list(itertools.accumulate([1 if c == 'b' else 0 for c in s])) result = float('inf') for idx in range(len(s)): result = min( result, a_idx[-1] - a_idx[idx+1] + b_idx[idx] - b_idx[0] ) return result
minimum-deletions-to-make-string-balanced
Python: Two Ideas
dev-josh
0
189
minimum deletions to make string balanced
1,653
0.588
Medium
23,964
https://leetcode.com/problems/minimum-jumps-to-reach-home/discuss/1540090/Simple-BFS-oror-Clean-and-Concise-oror-Well-coded
class Solution: def minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int: forbidden = set(forbidden) limit = max(x,max(forbidden))+a+b seen = set() q = [(0,0,False)] while q: p,s,isb = q.pop(0) if p>limit or p<0 or p in forbidden or (p,isb) in seen: continue if p==x: return s q.append((p+a,s+1,False)) if not isb: q.append((p-b,s+1,True)) seen.add((p,isb)) return -1
minimum-jumps-to-reach-home
πŸ“ŒπŸ“Œ Simple BFS || Clean & Concise || Well-coded 🐍
abhi9Rai
4
618
minimum jumps to reach home
1,654
0.287
Medium
23,965
https://leetcode.com/problems/minimum-jumps-to-reach-home/discuss/1052778/Python-Easy-understanding-BFS-solution-with-explanation
class Solution: def minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int: forbidden = set(forbidden) visited = set() limit = max(x, max(forbidden)) + a + b queue = [(0, 0, False)] while queue: pos, step, back = queue.pop(0) if pos > limit or pos < 0 or pos in forbidden or (pos, back) in visited: continue if pos == x: return step queue.append((pos+a, step+1, False)) if not back: queue.append((pos-b, step+1, True)) visited.add((pos, back)) return -1
minimum-jumps-to-reach-home
[Python] Easy-understanding BFS solution with explanation
Pandede
2
413
minimum jumps to reach home
1,654
0.287
Medium
23,966
https://leetcode.com/problems/minimum-jumps-to-reach-home/discuss/2522402/Python3-BFS-and-My-Interpretation-of-How-to-Find-The-Upper-Bound
class Solution1: def minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int: """Very difficult one. I had the intuition correct, that by using BFS, we can always find the solution when x is reachable. The difficulty is when x is not reachable. Since we can always add a, there is no end to BFS. Thus, the key to the problem is to find the upper bound for BFS. If no solution is found within the upper bound, we can say x is not reachable. To determine the upper bound, we have to use the Bezout's Identity, which stipulates that given any integers u and v, a * v + b * v = n * gcd(a, b). In addition, we need some ingenuity, which is detailed in this post: https://leetcode.com/problems/minimum-jumps-to-reach-home/discuss/978357/C%2B%2B-bidirectional-BFS-solution-with-proof-for-search-upper-bound I am going to describe here my understanding of finding the upper bound. We know that if a >= b, we basically cannot go left. Thus, the upper bound is x itself. This means if we go beyond x, there is no way we can go back. So whenever we go beyond x, we know x is not reachable. If a < b, we can go right and left. Now we can definitely go beyond x. Furthermore, to verify all possibilities, we have to go beyond max(forbidden), because the forbidden values add another layer of complexity. We must go beyond that to hit all possibilities associated with the forbidden value. Thus, the upper bound must be beyond max(x, max(forbidden)). Given Bezout's Identity, let p = n * gcd(a, b) that is the smallest value bigger than max(x, max(forbidden)). p is the left most point that we can reach beyond max(x, max(forbidden)). Notice that there is no more forbidden value to the right of p. Therefore, we don't have to worry about the added complexity of forbidden values now. Let's say we are at p right now. The first move we can make that will land us in the new territory is p + a. Since a is a multiple of gcd(a, b), there are other points we can reach between p and p + a, such as: p + gcd(a, b), p + 2 * gcd(a, b), ..., p - gcd(a, b) + a Note that all these positions can only be reached by a left jump. Therefore, the upper bound must be p - gcd(a, b) + a + b. One might ask, why can't we go beyond p - gcd(a, b) + a + b? We certainly can, but going beyond p - gcd(a, b) + a + b won't help us to reach x if we don't go left. And if we go left, eventually we will end up at one of the positions in [p, p + a] again, and when that happens, we have already taken more steps than visiting the positions in [p, p + a] for the first time. Therefore, the upper bound must be p - gcd(a, b) + a + b. Since p = n * gcd(a, b) is the smallest multiple of gcd(a, b) that is larger than max(x, max(forbidden)), we have p - gcd(a, b) <= max(x, max(forbidden)). Thus, p - gcd(a, b) + a + b <= max(x, max(forbidden)) + a + b. Therefore, it is perfectly okay for us to set the upper bound to be max(x, max(forbidden)) + a + b Once we have the upper bound, we can use BFS to find the solution. O(max(x, max(forbidden)) + a + b), 264 ms, faster than 31.58% """ upper_bound = max(x, max(forbidden)) + a + b forbidden = set(forbidden) queue = set([(0, False)]) steps = 0 visited = set() while queue: temp = set() for pos, is_pre_left in queue: visited.add(pos) if pos == x: return steps if pos + a <= upper_bound and pos + a not in forbidden and pos + a not in visited: temp.add((pos + a, False)) if pos - b >= 0 and pos - b not in forbidden and pos - b not in visited and not is_pre_left: temp.add((pos - b, True)) if temp: steps += 1 queue = temp return -1
minimum-jumps-to-reach-home
[Python3] BFS and My Interpretation of How to Find The Upper Bound
FanchenBao
1
85
minimum jumps to reach home
1,654
0.287
Medium
23,967
https://leetcode.com/problems/minimum-jumps-to-reach-home/discuss/2130948/PYTHON-BFS-Solution-beats-93.98
class Solution: def minimumJumps(self, fb: List[int], a: int, b: int, x: int) -> int: fb = set(fb) q = deque([[0,0,True]]) while(q): n,l,isf = q.popleft() if(n<0 or n in fb or n>2000+2*b): continue fb.add(n) if(n==x): return l if isf and n-b>0: q.append([n-b,l+1,False]) q.append([n+a,l+1,True]) return -1
minimum-jumps-to-reach-home
[PYTHON] BFS Solution beats 93.98%
markintosh_andrew
1
169
minimum jumps to reach home
1,654
0.287
Medium
23,968
https://leetcode.com/problems/minimum-jumps-to-reach-home/discuss/1103362/Python3-bfs
class Solution: def minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int: forbidden = set(forbidden) upper = max(forbidden | {x}) + a + b ans = 0 queue = [(0, 0)] forbidden.add(0) while queue: newq = [] for n, k in queue: if n == x: return ans if n+a <= upper and n+a not in forbidden: newq.append((n+a, 0)) forbidden.add(n+a) if k == 0 and 0 <= n-b and n-b not in forbidden: newq.append((n-b, 1)) ans += 1 queue = newq return -1
minimum-jumps-to-reach-home
[Python3] bfs
ye15
1
229
minimum jumps to reach home
1,654
0.287
Medium
23,969
https://leetcode.com/problems/minimum-jumps-to-reach-home/discuss/2811470/Python-(Simple-BFS)
class Solution: def minimumJumps(self, forbidden, a, b, x): limit, visited = max(x,max(forbidden)) + a + b, set() stack = [(0,0,False)] while stack: val, steps, par = stack.pop(0) if val > limit or val < 0 or val in forbidden or (val,par) in visited: continue else: visited.add((val,par)) if val == x: return steps stack.append((val+a,steps+1,False)) if not par: stack.append((val-b,steps+1,True)) return -1
minimum-jumps-to-reach-home
Python (Simple BFS)
rnotappl
0
5
minimum jumps to reach home
1,654
0.287
Medium
23,970
https://leetcode.com/problems/distribute-repeating-integers/discuss/1103429/Python3-backtracking
class Solution: def canDistribute(self, nums: List[int], quantity: List[int]) -> bool: freq = {} for x in nums: freq[x] = 1 + freq.get(x, 0) vals = sorted(freq.values(), reverse=True) quantity.sort(reverse=True) # pruning - large values first def fn(i): """Return True if possible to distribute quantity[i:] to remaining.""" if i == len(quantity): return True seen = set() for k in range(len(vals)): if vals[k] >= quantity[i] and vals[k] not in seen: seen.add(vals[k]) # pruning - unqiue values vals[k] -= quantity[i] if fn(i+1): return True vals[k] += quantity[i] # backtracking return fn(0)
distribute-repeating-integers
[Python3] backtracking
ye15
2
159
distribute repeating integers
1,655
0.392
Hard
23,971
https://leetcode.com/problems/distribute-repeating-integers/discuss/1489459/simple-dfs-with-bitmasking
class Solution: def canDistribute(self, nums: List[int], quantity: List[int]) -> bool: arr=[0]*(1001) for i in nums: arr[i]+=1 arr.sort(reverse=True) #print(arr) arr=arr[:10] dict={} def dfs(ind,arr): if ind==m: return True if (ind,tuple(arr)) in dict: return dict[(ind,tuple(arr))] for i in range(0,10): if arr[i]>=quantity[ind]: arr[i]-=quantity[ind] a=dfs(ind+1,arr) arr[i]+=quantity[ind] if a: dict[(ind,tuple(arr))]=True return True dict[(ind,tuple(arr))]=False return False m=len(quantity) return dfs(0,arr)
distribute-repeating-integers
simple dfs with bitmasking
heisenbarg
1
106
distribute repeating integers
1,655
0.392
Hard
23,972
https://leetcode.com/problems/determine-if-two-strings-are-close/discuss/935962/Python3-2-line-via-counter
class Solution: def closeStrings(self, word1: str, word2: str) -> bool: cnt1, cnt2 = Counter(word1), Counter(word2) return cnt1.keys() == cnt2.keys() and sorted(cnt1.values()) == sorted(cnt2.values())
determine-if-two-strings-are-close
[Python3] 2-line via counter
ye15
2
112
determine if two strings are close
1,657
0.541
Medium
23,973
https://leetcode.com/problems/determine-if-two-strings-are-close/discuss/935962/Python3-2-line-via-counter
class Solution: def closeStrings(self, word1: str, word2: str) -> bool: def fn(word): """Return freq table of word.""" freq = {} for c in word: freq[c] = 1 + freq.get(c, 0) return freq freq1, freq2 = fn(word1), fn(word2) return freq1.keys() == freq2.keys() and sorted(freq1.values()) == sorted(freq2.values())
determine-if-two-strings-are-close
[Python3] 2-line via counter
ye15
2
112
determine if two strings are close
1,657
0.541
Medium
23,974
https://leetcode.com/problems/determine-if-two-strings-are-close/discuss/1029096/Python%3A-2-lines-solution-with-counter
class Solution: def closeStrings(self, word1: str, word2: str) -> bool: c1, c2 = Counter(word1), Counter(word2) return c1.keys() == c2.keys() and Counter(c1.values()) == Counter(c2.values())
determine-if-two-strings-are-close
Python: 2 lines solution with counter
jaykim9438
1
71
determine if two strings are close
1,657
0.541
Medium
23,975
https://leetcode.com/problems/determine-if-two-strings-are-close/discuss/935972/PYTHON-oror-NLOGN-oror-FAST-oror-EASY
class Solution(object): def closeStrings(self, word1, word2): count1 = dict() count2 = dict() for char in word1: count1[char] = count1.get(char, 0) + 1 for char in word2: count2[char] = count2.get(char,0) + 1 return sorted(count1.values()) == sorted(count2.values()) and set(word1)== set(word2)
determine-if-two-strings-are-close
PYTHON || NLOGN || FAST || EASY
akashgkrishnan
1
113
determine if two strings are close
1,657
0.541
Medium
23,976
https://leetcode.com/problems/determine-if-two-strings-are-close/discuss/2520906/Python3-solution-or-Explained
class Solution: def closeStrings(self, word1: str, word2: str) -> bool: """ operation 1 ~ swapping characters - this means that the order of the characters is not a problem since we can move them as we want operation 2 ~ same number of keys and same values at values - using 2 hashmaps of the 2 words you'll see that we only need the same keys and the same values (not necessary allocated to the same key though since we can use operation 2 to move them around) """ d1, d2 = {}, {} for i in range(len(word1)): if word1[i] not in d1: d1[word1[i]] = 1 else: d1[word1[i]] += 1 for i in range(len(word2)): if word2[i] not in d2: d2[word2[i]] = 1 else: d2[word2[i]] += 1 return sorted(d1.keys()) == sorted(d2.keys()) and sorted(d1.values()) == sorted(d2.values())
determine-if-two-strings-are-close
Python3 solution | Explained
FlorinnC1
0
11
determine if two strings are close
1,657
0.541
Medium
23,977
https://leetcode.com/problems/determine-if-two-strings-are-close/discuss/2111798/python-3-oror-simple-hash-map-solution-oror-O(n)O(1)
class Solution: def closeStrings(self, word1: str, word2: str) -> bool: count1 = collections.Counter(word1) count2 = collections.Counter(word2) return (count1.keys() == count2.keys() and sorted(count1.values()) == sorted(count2.values()))
determine-if-two-strings-are-close
python 3 || simple hash map solution || O(n)/O(1)
dereky4
0
38
determine if two strings are close
1,657
0.541
Medium
23,978
https://leetcode.com/problems/determine-if-two-strings-are-close/discuss/1661886/Python-simple-O(n)-time-O(1)-space-solution-(if-else-statements-only)
class Solution: def closeStrings(self, word1: str, word2: str) -> bool: cnt1, cnt2 = defaultdict(int), defaultdict(int) n1, n2 = defaultdict(int), defaultdict(int) s1, s2 = set(), set() for w in word1: cnt1[w] += 1 s1.add(w) for w in word2: cnt2[w] += 1 s2.add(w) for w in word1: if w not in word2: return False for w in word2: if w not in word1: return False for k in cnt1: v = cnt1[k] n1[v] += 1 for k in cnt2: v = cnt2[k] n2[v] += 1 for k in n1: if k not in n2 or n1[k] != n2[k]: return False for k in n2: if k not in n1 or n2[k] != n1[k]: return False return True
determine-if-two-strings-are-close
Python simple O(n) time, O(1) space solution (if-else statements only)
byuns9334
0
87
determine if two strings are close
1,657
0.541
Medium
23,979
https://leetcode.com/problems/determine-if-two-strings-are-close/discuss/1029506/Python-84-solution-collections.Counter-method
class Solution: def closeStrings(self, word1: str, word2: str) -> bool: word1_cnt = collections.Counter(word1) word2_cnt = collections.Counter(word2) # precondition 1 if set([k for k in word1_cnt]) != set([k for k in word2_cnt]): return False # precondition 2 cnt1 = collections.defaultdict(int) for k, v in word1_cnt.items(): cnt1[v] += 1 cnt2 = collections.defaultdict(int) for k, v in word2_cnt.items(): cnt2[v] += 1 return cnt1 == cnt2
determine-if-two-strings-are-close
Python 84% solution, collections.Counter method
yilingliu
0
47
determine if two strings are close
1,657
0.541
Medium
23,980
https://leetcode.com/problems/determine-if-two-strings-are-close/discuss/1029168/python3%3A-sorting-O(no.-of-chars-*-no.-of-chars)time-and-O(no-of-chars)-space
class Solution: def closeStrings(self, word1: str, word2: str) -> bool: dp1=[0]*26 dp2=[0]*26 n1=len(word1) n2=len(word2) if(n1!=n2): return False for i in range(n1): dp1[ord(word1[i])-97]+=1 dp2[ord(word2[i])-97]+=1 for i in range(26): if(dp1[i]==0 and dp2[i]!=0) or (dp2[i]==0 and dp1[i]!=0): return False dp1.sort() dp2.sort() for i in range(26): if dp1[i]!=dp2[i]: return False return True
determine-if-two-strings-are-close
python3: sorting O(no. of chars * no. of chars)time and O(no of chars) space
_Rehan12
0
23
determine if two strings are close
1,657
0.541
Medium
23,981
https://leetcode.com/problems/determine-if-two-strings-are-close/discuss/947260/Python-7-Line-easy-solution-with-Dictionary.
class Solution(object): def closeStrings(self, word1, word2): def ans(word): dict1 ={} for i in word: if i not in dict1:dict1[i]=1 else:dict1[i]+=1 return sorted(dict1.values()) return ans(word1)==ans(word2) and set(word1)==set(word2)
determine-if-two-strings-are-close
[Python] 7 Line easy solution with Dictionary.
rachitsxn292
0
193
determine if two strings are close
1,657
0.541
Medium
23,982
https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/discuss/935986/Python3-O(N)-hash-table-of-prefix
class Solution: def minOperations(self, nums: List[int], x: int) -> int: mp = {0: 0} prefix = 0 for i, num in enumerate(nums, 1): prefix += num mp[prefix] = i ans = mp.get(x, inf) for i, num in enumerate(reversed(nums), 1): x -= num if x in mp and mp[x] + i <= len(nums): ans = min(ans, i + mp[x]) return ans if ans < inf else -1
minimum-operations-to-reduce-x-to-zero
[Python3] O(N) hash table of prefix
ye15
21
1,600
minimum operations to reduce x to zero
1,658
0.376
Medium
23,983
https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/discuss/935986/Python3-O(N)-hash-table-of-prefix
class Solution: def minOperations(self, nums: List[int], x: int) -> int: x = sum(nums) - x if not x: return len(nums) # edge case seen = {0: -1} ans = prefix = 0 for i, num in enumerate(nums): prefix += num if prefix - x in seen: ans = max(ans, i - seen[prefix - x]) seen.setdefault(prefix, i) return len(nums) - ans if ans else -1
minimum-operations-to-reduce-x-to-zero
[Python3] O(N) hash table of prefix
ye15
21
1,600
minimum operations to reduce x to zero
1,658
0.376
Medium
23,984
https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/discuss/2136561/Python-or-Prefix-Sum-and-Sliding-Window-or-With-Explanation
class Solution: def minOperations(self, nums: List[int], x: int) -> int: # find the longest subarray that sum to 'goal' s = sum(nums) n = len(nums) goal = s - x max_length = -1 left = 0 current_sum = 0 for right, num in enumerate(nums): current_sum += num # if larger, move `left` to right while current_sum > goal and left <= right: current_sum -= nums[left] left += 1 # check if equal if current_sum == goal: max_length = max(max_length, right-left+1) return n - max_length if max_length != -1 else -1
minimum-operations-to-reduce-x-to-zero
Python | Prefix Sum & Sliding Window | With Explanation
Mikey98
7
969
minimum operations to reduce x to zero
1,658
0.376
Medium
23,985
https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/discuss/2136863/python-3-oror-simple-sliding-window-solution-oror-O(n)O(1)
class Solution: def minOperations(self, nums: List[int], x: int) -> int: targetSum = sum(nums) - x if targetSum <= 0: return -1 if targetSum < 0 else len(nums) largestWindow = -1 curSum = 0 left = 0 for right, num in enumerate(nums): curSum += num while curSum > targetSum: curSum -= nums[left] left += 1 if curSum == targetSum: largestWindow = max(largestWindow, right - left + 1) return len(nums) - largestWindow if largestWindow != -1 else -1
minimum-operations-to-reduce-x-to-zero
python 3 || simple sliding window solution || O(n)/O(1)
dereky4
2
175
minimum operations to reduce x to zero
1,658
0.376
Medium
23,986
https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/discuss/2139813/Simple-Python-Solution-using-sliding-window-!!
class Solution(object): def minOperations(self, li, x): numsSum = sum(li) k = numsSum-x n = len(li) i, j, s = 0, 0, 0 l = [] maximum = float('-inf') if numsSum == x: return n if k>0: while j < n: s += li[j] if s < k: j += 1 elif s == k: maximum = max(maximum, j-i+1) j += 1 elif s > k: while s > k: s -= li[i] i += 1 if s == k: maximum = max(maximum, j-i+1) j += 1 return n-maximum if maximum != float('-inf') else -1 else: return -1
minimum-operations-to-reduce-x-to-zero
Simple Python Solution using sliding window !!
Namangarg98
1
96
minimum operations to reduce x to zero
1,658
0.376
Medium
23,987
https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/discuss/2136778/Python-90-FASTER-96-memory-EFFICIENT-OPTIMAL-solution-O(n)-time-O(1)-space
class Solution: def minOperations(self, nums: List[int], x: int) -> int: target = sum(nums) - x curr_sum, max_len = 0, 0 start_idx = 0 found = False for end_idx in range(len(nums)): curr_sum += nums[end_idx] while start_idx <= end_idx and curr_sum > target: curr_sum -= nums[start_idx] start_idx += 1 if curr_sum == target: found = True max_len = max(max_len, end_idx - start_idx + 1) return len(nums) - max_len if found else -1
minimum-operations-to-reduce-x-to-zero
Python 90% FASTER 96% memory EFFICIENT OPTIMAL solution O(n) time O(1) space
anuvabtest
1
102
minimum operations to reduce x to zero
1,658
0.376
Medium
23,988
https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/discuss/936064/Python3
class Solution: def minOperations(self, nums: List[int], x: int) -> int: ans = float("inf") dicti = {0:0} count = 0 for i in range(len(nums)): count += nums[i] if(count==x): ans = min(ans,i+1) dicti[count] = i+1 nums = nums[::-1] for i in range(len(nums)): x-=nums[i] if x in dicti and dicti.get(x)+i+1<=len(nums): ans = min(ans,1+i+dicti.get(x)) return ans if ans<inf else -1
minimum-operations-to-reduce-x-to-zero
Python3
swap2001
1
152
minimum operations to reduce x to zero
1,658
0.376
Medium
23,989
https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/discuss/2275989/Python-Prefix-Sum
class Solution: def minOperations(self, nums: List[int], x: int) -> int: if min(nums)>x or sum(nums)<x: return -1 n = len(nums) target = sum(nums)-x # we need to find the longest substring sum = target longest = 0 hash_map = {0:-1} sum_ = 0 for i,val in enumerate(nums): sum_+= val k = sum_ - target if k in hash_map: longest = max(longest, (i-hash_map[k])) if sum_ not in hash_map: hash_map[sum_] = i if longest == len(nums): return -1 return len(nums)-longest
minimum-operations-to-reduce-x-to-zero
Python Prefix Sum
Abhi_009
0
68
minimum operations to reduce x to zero
1,658
0.376
Medium
23,990
https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/discuss/2155127/Python3-Solution-with-using-two-pointers
class Solution: def minOperations(self, nums: List[int], x: int) -> int: total_sum = sum(nums) left, right = 0, 0 max_len_win = -1 current_win_sum = 0 while right < len(nums): current_win_sum += nums[right] while current_win_sum > total_sum - x and left <= right: current_win_sum -= nums[left] left += 1 if current_win_sum == total_sum - x: max_len_win = max(max_len_win, right - left + 1) right += 1 return len(nums) - max_len_win if max_len_win != -1 else -1
minimum-operations-to-reduce-x-to-zero
[Python3] Solution with using two-pointers
maosipov11
0
39
minimum operations to reduce x to zero
1,658
0.376
Medium
23,991
https://leetcode.com/problems/maximize-grid-happiness/discuss/1132982/Python3-top-down-dp
class Solution: def getMaxGridHappiness(self, m: int, n: int, introvertsCount: int, extrovertsCount: int) -> int: @cache def fn(prev, i, j, intro, extro): """Return max grid happiness at (i, j).""" if i == m: return 0 # no more position if j == n: return fn(prev, i+1, 0, intro, extro) if intro == extro == 0: return 0 prev0 = prev[:j] + (0,) + prev[j+1:] ans = fn(prev0, i, j+1, intro, extro) if intro: val = 120 if i and prev[j]: # neighbor from above val -= 30 if prev[j] == 1: val -= 30 else: val += 20 if j and prev[j-1]: # neighbor from left val -= 30 if prev[j-1] == 1: val -= 30 else: val += 20 prev0 = prev[:j] + (1,) + prev[j+1:] ans = max(ans, val + fn(prev0, i, j+1, intro-1, extro)) if extro: val = 40 if i and prev[j]: val += 20 if prev[j] == 1: val -= 30 else: val += 20 if j and prev[j-1]: val += 20 if prev[j-1] == 1: val -= 30 else: val += 20 prev0 = prev[:j] + (2,) + prev[j+1:] ans = max(ans, val + fn(prev0, i, j+1, intro, extro-1)) return ans return fn((0,)*n, 0, 0, introvertsCount, extrovertsCount)
maximize-grid-happiness
[Python3] top-down dp
ye15
1
319
maximize grid happiness
1,659
0.384
Hard
23,992
https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/discuss/944697/Python-3-or-Python-1-liner-or-No-explanation
class Solution: def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool: return ''.join(word1) == ''.join(word2)
check-if-two-string-arrays-are-equivalent
Python 3 | Python 1-liner | No explanation πŸ˜„
idontknoooo
15
1,200
check if two string arrays are equivalent
1,662
0.833
Easy
23,993
https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/discuss/2740932/Python-Simple-and-Easy-Way-to-Solve-or-99-Faster
class Solution: def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool: return True if ''.join(word1) == ''.join(word2) else False
check-if-two-string-arrays-are-equivalent
βœ”οΈ Python Simple and Easy Way to Solve | 99% Faster πŸ”₯
pniraj657
6
898
check if two string arrays are equivalent
1,662
0.833
Easy
23,994
https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/discuss/1163967/Python3-Simple-and-Single-Line-Solution
class Solution: def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool: return ''.join(word1) == ''.join(word2)
check-if-two-string-arrays-are-equivalent
[Python3] Simple and Single Line Solution
VoidCupboard
6
218
check if two string arrays are equivalent
1,662
0.833
Easy
23,995
https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/discuss/2060799/PYTHON-Simple-Solution
class Solution: def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool: str1=str2="" for i in word1: str1+=i for j in word2: str2+=j return(bool(str1==str2))
check-if-two-string-arrays-are-equivalent
PYTHON {Simple} Solution
tusharkhanna575
4
208
check if two string arrays are equivalent
1,662
0.833
Easy
23,996
https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/discuss/1338601/Python-O(1)-space-complexity-with-optimized-time-complexity-as-well.-EXPLAINED
class Solution: def arrayStringsAreEqual(self, word1, word2): """ The below solutions take O(n + m) time and space, as we are * Iterating through both list (Time complexity : O(n+m)) * Adding strings each time. In the backend a new string is created with increased size. (Space complexity O(n+m)) However, we can optimized it. Suppose if the first character doesnot match than the whole concatenation was unecessary. So the Idea is to compare the character in the strings on the fly. We can skip building the strings and only compare the individual characters using space O(1). It also saves time as we will not be going through the whole list if any characters mismatched. We can use a generator or a pointer approach to solve this problem. Time complexity : O(n) if n<m else O(m) Space complexity: O(1) """ def gen(word): for w in word: for c in w: yield c yield None for c1, c2 in zip(gen(word1), gen(word2)): if c1 != c2: return False return True """Brute Force approach Time complexity : O(n^2 + m^2) Space complexity: O(n+m) #debatable """ # str1 = str2 = "" # for s in word1: # str1 += s # for s in word2: # str2 += s # return str1==str2 """One liner Time complexity : O(n+m) Space complexity : O(1) """ # return ''.join(word1) == ''.join(word2)
check-if-two-string-arrays-are-equivalent
Python O(1) space complexity with optimized time complexity as well. EXPLAINED
er1shivam
4
256
check if two string arrays are equivalent
1,662
0.833
Easy
23,997
https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/discuss/2743669/Python-oror-Easy-to-Understand-oror-Faster-than-93
class Solution: def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool: s1 = "" s2 = "" for i in word1: s1+=i for i in word2: s2+=i return s1 == s2
check-if-two-string-arrays-are-equivalent
Python || Easy to Understand || Faster than 93%
aniketbhamani
1
4
check if two string arrays are equivalent
1,662
0.833
Easy
23,998
https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/discuss/2741440/Python3ororO(N)
class Solution: def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool: s1="" for i in word1: s1+=i s2="" for j in word2: s2+=j return s1==s2
check-if-two-string-arrays-are-equivalent
Python3||O(N)
Sneh713
1
45
check if two string arrays are equivalent
1,662
0.833
Easy
23,999