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/maximum-number-of-occurrences-of-a-substring/discuss/1135091/Python3-freq-table
class Solution: def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int: freq = {} temp = {} for i in range(len(s)): temp[s[i]] = 1 + temp.get(s[i], 0) if i >= minSize: temp[s[i-minSize]] -= 1 if temp[s[i-minSize]] == 0: temp.pop(s[i-minSize]) if i >= minSize-1 and len(temp) <= maxLetters: key = s[i-minSize+1: i+1] freq[key] = 1 + freq.get(key, 0) return max(freq.values(), default=0)
maximum-number-of-occurrences-of-a-substring
[Python3] freq table
ye15
2
301
maximum number of occurrences of a substring
1,297
0.52
Medium
19,300
https://leetcode.com/problems/maximum-number-of-occurrences-of-a-substring/discuss/2826891/Python-3-Solution
class Solution: def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int: md=Counter() l=0 ans=Counter() for ind,ch in enumerate(s): md[ch]+=1 while len(md.keys())>maxLetters: md[s[l]]-=1 if not md[s[l]]:md.pop(s[l]) l+=1 for j in range(l,ind+1): if minSize<=ind-j+1<=maxSize:ans[s[j:ind+1]]+=1 return max(ans.values()) if ans else 0
maximum-number-of-occurrences-of-a-substring
Python 3 Solution
Burak1069711851
0
4
maximum number of occurrences of a substring
1,297
0.52
Medium
19,301
https://leetcode.com/problems/maximum-number-of-occurrences-of-a-substring/discuss/2136470/Python-3-Interview-Answer-or-Clean-and-Easy-Readability
class Solution: def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int: seen = {} for i in range(len(s) - minSize + 1): check = s[i : i + minSize] if check not in seen: # we don't need to have conditions for "minSize" and "maxSize" # because check is always keeping a size of minSize if len(Counter(check)) <= maxLetters: seen[check] = 1 else: seen[check] += 1 return max(seen.values()) if seen else 0
maximum-number-of-occurrences-of-a-substring
[Python 3] Interview Answer | Clean & Easy Readability
Cut
0
152
maximum number of occurrences of a substring
1,297
0.52
Medium
19,302
https://leetcode.com/problems/maximum-number-of-occurrences-of-a-substring/discuss/457611/Python-3-(three-lines)-(beats-100)
class Solution: def maxFreq(self, s: str, M: int, m: int, _: int) -> int: L, D = len(s), collections.defaultdict(int) for j in range(L+1-m): D[s[j:j+m]] += (len(set(s[j:j+m])) <= M) return max(D.values()) - Junaid Mansuri - Chicago, IL
maximum-number-of-occurrences-of-a-substring
Python 3 (three lines) (beats 100%)
junaidmansuri
-3
423
maximum number of occurrences of a substring
1,297
0.52
Medium
19,303
https://leetcode.com/problems/maximum-candies-you-can-get-from-boxes/discuss/2841531/Easy-to-understand-BFS-Solution-(with-explanation)
class Solution: def maxCandies(self, status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]], initialBoxes: List[int]) -> int: myKeys = set() canVisit = set(initialBoxes) q = initialBoxes[:] # Check [all keys we can get] and [all boxes we can visit] while q: box = q.pop(0) myKeys.update(set((keys[box]))) # Add the keys in box into "myKeys" canVisit.add(box) # Add current box into "canVisit" newBoxes = containedBoxes[box] # Add next boxes to the queue for nb in newBoxes: q.append(nb) ans = 0 # Visit all boxes we can visit for i in canVisit: # We can open the box only if we have the key or box's status is open(1) if i in myKeys or status[i] == 1: ans += candies[i] return ans
maximum-candies-you-can-get-from-boxes
Easy to understand BFS Solution (with explanation)
child70370636
0
1
maximum candies you can get from boxes
1,298
0.609
Hard
19,304
https://leetcode.com/problems/maximum-candies-you-can-get-from-boxes/discuss/457585/Python-3-(five-lines)-(beats-100)
class Solution: def maxCandies(self, S: List[int], C: List[int], K: List[List[int]], CB: List[List[int]], I: List[int]) -> int: t, I, S, B = 0, set(I), set([i for i,v in enumerate(S) if v]), 1 while B: B = 0 for b in I &amp; S: t, I, S, B = t + C[b], I.union(set(CB[b]))-{b}, S.union(set(K[b])), 1 return t - Junaid Mansuri - Chicago, IL
maximum-candies-you-can-get-from-boxes
Python 3 (five lines) (beats 100%)
junaidmansuri
-1
120
maximum candies you can get from boxes
1,298
0.609
Hard
19,305
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/1058153/Easy-and-simple-python-solution-or-O(n)
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: mx = arr[-1] arr[-1] = -1 for i in range(len(arr) - 2, -1, -1): temp = arr[i] arr[i] = mx if mx < temp: mx = temp return arr
replace-elements-with-greatest-element-on-right-side
Easy and simple python solution | O(n)
vanigupta20024
5
510
replace elements with greatest element on right side
1,299
0.747
Easy
19,306
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/463645/Python-3-(two-lines)-(72-ms)-(beats-100)-(With-Explanation)-(-O(n)-time-)-(-O(1)-space-)
class Solution: def replaceElements(self, A: List[int]) -> List[int]: for i in range(len(A)-2,-1,-1): A[i] = max(A[i],A[i+1]) return A[1:]+[-1] - Junaid Mansuri - Chicago, IL
replace-elements-with-greatest-element-on-right-side
Python 3 (two lines) (72 ms) (beats 100%) (With Explanation) ( O(n) time ) ( O(1) space )
junaidmansuri
5
881
replace elements with greatest element on right side
1,299
0.747
Easy
19,307
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/1583372/Python-3-O(n)-time-O(1)-memory
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: curMax = -1 for i in range(len(arr)-1, -1, -1): arr[i], curMax = curMax, max(arr[i], curMax) return arr
replace-elements-with-greatest-element-on-right-side
Python 3 O(n) time, O(1) memory
dereky4
4
287
replace elements with greatest element on right side
1,299
0.747
Easy
19,308
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/463572/Python3-backward-scan
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: m = -1 for i in reversed(range(len(arr))): arr[i], m = m, max(m, arr[i]) return arr
replace-elements-with-greatest-element-on-right-side
[Python3] backward scan
ye15
3
175
replace elements with greatest element on right side
1,299
0.747
Easy
19,309
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2080041/Python3-Runtime%3A-133ms-82.42-memory%3A-15.2mb-64.02
class Solution: def replaceElements(self, array: List[int]) -> List[int]: return self.optimalSolution(array) # O(N) || O(1) 133ms 82.42% def optimalSolution(self, array): rightMax = -1 for i in reversed(range(len(array))): maxVal = max(rightMax, array[i]) array[i] = rightMax rightMax = maxVal return array # O(n^2) || O(1) TLE def bruteForce(self, array): if not array: return array for i in range(len(array)): maxVal = 0 for j in range(i+1, len(array)): maxVal = max(maxVal, array[j]) array[i] = maxVal array[-1] = -1 return array
replace-elements-with-greatest-element-on-right-side
Python3 Runtime: 133ms 82.42% memory: 15.2mb 64.02%
arshergon
2
94
replace elements with greatest element on right side
1,299
0.747
Easy
19,310
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/1887228/Python-beginner-friendly-solution
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: res = [-1] * len(arr) for i in range(len(arr)-1): res[i] = max(arr[i+1:]) return res
replace-elements-with-greatest-element-on-right-side
Python beginner friendly solution
alishak1999
2
112
replace elements with greatest element on right side
1,299
0.747
Easy
19,311
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/1580431/Python-with-explanation
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: if len(arr) == 1: return [-1] largest = arr[-1] idx = len(arr) - 2 while idx >= 0: temp = arr[idx] arr[idx] = largest largest = max(largest, temp) idx -= 1 arr[-1] = -1 return arr
replace-elements-with-greatest-element-on-right-side
Python with explanation
SleeplessChallenger
2
129
replace elements with greatest element on right side
1,299
0.747
Easy
19,312
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2797050/Python3-O(n)-simple-to-understand
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: rev, maximum = arr[::-1], -1 for i in range(len(rev)): rev[i], maximum = maximum, max(maximum, rev[i]) return rev[::-1]
replace-elements-with-greatest-element-on-right-side
Python3, O(n) simple to understand
rschevenin
1
292
replace elements with greatest element on right side
1,299
0.747
Easy
19,313
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2547910/Easy-Python-Solution
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: maxi=-1 n=len(arr) for i in range(n-1, -1, -1): temp=arr[i] arr[i]=maxi maxi=max(maxi, temp) return arr
replace-elements-with-greatest-element-on-right-side
Easy Python Solution
Siddharth_singh
1
86
replace elements with greatest element on right side
1,299
0.747
Easy
19,314
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2395022/Python-In-place-simple-execution
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: maxright = arr[-1] for i in range(len(arr) -1,-1,-1): temp = arr[i] arr[i] = maxright if temp > maxright: maxright = temp arr[-1] = -1 return arr
replace-elements-with-greatest-element-on-right-side
Python, In place, simple execution
Abhi_-_-
1
57
replace elements with greatest element on right side
1,299
0.747
Easy
19,315
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2155582/Python-Easy
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: max_so_far = -1 for i in range(len(arr)-1, -1, -1): curr = arr[i] arr[i] = max_so_far max_so_far = max(max_so_far, curr) return arr
replace-elements-with-greatest-element-on-right-side
Python Easy
lokeshsenthilkumar
1
162
replace elements with greatest element on right side
1,299
0.747
Easy
19,316
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2114100/Python-simple-solution
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: ans = [] for i in range(1, len(arr)): ans.append(max(arr[i:])) ans.append(-1) return ans
replace-elements-with-greatest-element-on-right-side
Python simple solution
StikS32
1
103
replace elements with greatest element on right side
1,299
0.747
Easy
19,317
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/1204090/PythonPython3-Replace-Elements-with-Greatest-Element-on-Right-Side
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: out = [] if len(arr) == 1: return [-1] for idx in range(len(arr))[::-1]: if idx == len(arr)-1: out.append(-1) else: out.append(max(arr[idx+1], out[-1])) return out[::-1]
replace-elements-with-greatest-element-on-right-side
[Python/Python3] Replace Elements with Greatest Element on Right Side
newborncoder
1
166
replace elements with greatest element on right side
1,299
0.747
Easy
19,318
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2841211/Python-simple-without-max()-keyword
class Solution(object): def replaceElements(self, arr): max_ = -1 for i in range(len(arr) - 1, -1, -1): save = arr[i] arr[i] = max_ if save > max_: max_ = save return arr
replace-elements-with-greatest-element-on-right-side
Python - simple without max() keyword
Nematulloh
0
3
replace elements with greatest element on right side
1,299
0.747
Easy
19,319
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2825389/Fast-Easy-Solution-Python
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: mx=-1 for i in range(len(arr)-1,-1,-1): arr[i],mx = mx,max(mx,arr[i]) return arr
replace-elements-with-greatest-element-on-right-side
Fast Easy Solution Python
parthjain9925
0
3
replace elements with greatest element on right side
1,299
0.747
Easy
19,320
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2814773/Easy-and-Readable-solution-in-Python3-Time%3A-O(n)-Space%3A-O(n)
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: for i in range(len(arr) -1, -1, -1): if i == len(arr) - 1: maxRightElement = arr[i] arr[i] = -1 else: curValue = arr[i] arr[i] = maxRightElement maxRightElement = max(maxRightElement, curValue) return arr
replace-elements-with-greatest-element-on-right-side
Easy and Readable solution in Python3 - Time: O(n) Space: O(n)
Simon-Huang-1
0
4
replace elements with greatest element on right side
1,299
0.747
Easy
19,321
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2811465/Easy-to-understand-oror-python
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: n = len(arr) ans = [-1 for i in range(0,n)] max_ = arr[-1] for i in range(n-2,-1,-1): ans[i] = max_ max_ = max(max_ , arr[i]) return ans
replace-elements-with-greatest-element-on-right-side
Easy to understand || python
MB16biwas
0
8
replace elements with greatest element on right side
1,299
0.747
Easy
19,322
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2726695/Very-simple-and-short-Python-solution
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: max_sofar = -1 for i in range(len(arr)-1, -1, -1): tmp = arr[i] arr[i] = max_sofar max_sofar = max(max_sofar, tmp) return arr
replace-elements-with-greatest-element-on-right-side
✅Very simple and short Python solution
jyotirsai28
0
5
replace elements with greatest element on right side
1,299
0.747
Easy
19,323
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2691895/Simple-python
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: if not arr: return arr currentMax = -1 for i, current in reversed(list(enumerate(arr))): arr[i] = currentMax currentMax = max(currentMax, current) return arr
replace-elements-with-greatest-element-on-right-side
Simple python
jamaxack
0
1
replace elements with greatest element on right side
1,299
0.747
Easy
19,324
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2681985/Easybeginner-friendlybrute-force-solution
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: l=[] for i in range(len(arr)-1): s=arr[i] l.append(max(arr[i+1:])) l.append(-1) return l
replace-elements-with-greatest-element-on-right-side
Easy,beginner friendly,brute force solution
liontech_123
0
17
replace elements with greatest element on right side
1,299
0.747
Easy
19,325
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2681291/Python-3%3A-Beats-99.69
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: curr_max = -1 previous_num = -1 for i in range(len(arr)-1, -1, -1): previous_num = arr[i] arr[i] = curr_max curr_max = max(curr_max, previous_num) return arr
replace-elements-with-greatest-element-on-right-side
Python 3: Beats 99.69%
NautillusSs
0
3
replace elements with greatest element on right side
1,299
0.747
Easy
19,326
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2679850/Python-solution-from-a-newbie!-Hope-it-works!!
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: for i in range(len(arr)): if i + 1 < len(arr): arr[i] = max(arr[i + 1:]) else: arr[-1] = -1 return arr
replace-elements-with-greatest-element-on-right-side
Python solution from a newbie! Hope it works!!
countachie
0
2
replace elements with greatest element on right side
1,299
0.747
Easy
19,327
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2677166/simple-iteration
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: n=len(arr) for i in range(n-1): arr[i]=max(arr[i+1:]) arr[n-1]=-1 return arr
replace-elements-with-greatest-element-on-right-side
simple iteration
insane_me12
0
1
replace elements with greatest element on right side
1,299
0.747
Easy
19,328
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2647590/Python-Simple-O(N)-solution
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: ge = arr[-1] arr[-1] = -1 for i in range(len(arr)-2, -1, -1): if arr[i] > ge: arr[i], ge = ge, arr[i] else: arr[i] = ge return arr
replace-elements-with-greatest-element-on-right-side
Python Simple O(N) solution
dos_77
0
4
replace elements with greatest element on right side
1,299
0.747
Easy
19,329
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2640442/O(n)-solution-for-python
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: for i in range(len(arr) - 1): arr[i] = max(arr[i+1:]) arr[len(arr) - 1] = -1 return arr
replace-elements-with-greatest-element-on-right-side
O(n) solution for python
Anonymous84
0
5
replace elements with greatest element on right side
1,299
0.747
Easy
19,330
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2489718/Python3-Straightforward-One-liner
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: return [max(arr[i+1:]) for i in range(len(arr)-1)] + [-1]
replace-elements-with-greatest-element-on-right-side
[Python3] Straightforward One-liner
ivnvalex
0
35
replace elements with greatest element on right side
1,299
0.747
Easy
19,331
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2422561/(PYTHON3)-tgreater91
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: m = arr[-1] arr[-1] = -1 for i in range(1, len(arr)): tmp = arr[~i] arr[~i] = m if m < tmp: m = tmp return arr
replace-elements-with-greatest-element-on-right-side
(PYTHON3) t>91
savas_karanli
0
11
replace elements with greatest element on right side
1,299
0.747
Easy
19,332
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2309765/simple-python3-solution
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: maxRight = -1 for i in range(len(arr)-1,-1,-1): maxi = max(maxRight,arr[i]) arr[i] = maxRight maxRight = maxi return arr
replace-elements-with-greatest-element-on-right-side
simple python3 solution
TUSHARRAINA
0
14
replace elements with greatest element on right side
1,299
0.747
Easy
19,333
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2220954/Python-O(n)-and-O(n2)-solutions..............
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: temp=-1 for i in range(len(arr)-1,-1,-1): current=arr[i] arr[i]=temp temp=max(temp,current) return arr
replace-elements-with-greatest-element-on-right-side
Python O(n) and O(n^2) solutions..............
guneet100
0
56
replace elements with greatest element on right side
1,299
0.747
Easy
19,334
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2220954/Python-O(n)-and-O(n2)-solutions..............
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: for i in range(0,len(arr)-1): max1=max(arr[i+1:]) arr[i]=max1 arr[-1]=-1 return arr
replace-elements-with-greatest-element-on-right-side
Python O(n) and O(n^2) solutions..............
guneet100
0
56
replace elements with greatest element on right side
1,299
0.747
Easy
19,335
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/2095064/PYTHON-or-Simple-python-solution
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: for i in range(len(arr)): if i != (len(arr) - 1): arr[i] = max(arr[i+1:]) else: arr[i] = -1 return arr
replace-elements-with-greatest-element-on-right-side
PYTHON | Simple python solution
shreeruparel
0
52
replace elements with greatest element on right side
1,299
0.747
Easy
19,336
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/1853099/Python-(Simple-approach-and-beginner-friendly)
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: new_arr = [] for i in range(0,len(arr)-1): new_arr.append(max(arr[i+1:])) new_arr.append(-1) return new_arr
replace-elements-with-greatest-element-on-right-side
Python (Simple approach and beginner-friendly)
vishvavariya
0
65
replace elements with greatest element on right side
1,299
0.747
Easy
19,337
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/1755805/Replace-Elements-with-Greatest-Element-on-Right-Side-easy-python-solution
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: lst=[arr[i+1:len(arr)+1] for i in range(len(arr))] lst.pop(-1) flst=[] for ls in lst: flst.append(max(ls)) flst.insert(len(arr),-1) return flst
replace-elements-with-greatest-element-on-right-side
Replace Elements with Greatest Element on Right Side easy python solution
seabreeze
0
55
replace elements with greatest element on right side
1,299
0.747
Easy
19,338
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/1729977/Python-dollarolution
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: x, m, y = len(arr), 0, arr[-1] arr[-1] = -1 for i in range(1,x): if y > m: m = y y = arr[-i - 1] arr[-i - 1] = m return arr
replace-elements-with-greatest-element-on-right-side
Python $olution
AakRay
0
79
replace elements with greatest element on right side
1,299
0.747
Easy
19,339
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/1616119/Simple-Python-Solution%3A-O(n)
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: if len(arr)==1: return [-1] m = -1 for i in range(len(arr)-1,-1,-1): temp = arr[i] arr[i] = m m = max(temp,m) return arr
replace-elements-with-greatest-element-on-right-side
Simple Python Solution: O(n)
smaranjitghose
0
119
replace elements with greatest element on right side
1,299
0.747
Easy
19,340
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/1205641/Python3-Solution
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: i = 1 ans = [] while len(arr)>i: ans.append(max(arr[i:])) i = i+1 ans.append(-1) return ans
replace-elements-with-greatest-element-on-right-side
Python3 Solution
Sanyamx1x
0
89
replace elements with greatest element on right side
1,299
0.747
Easy
19,341
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/1145997/Easy-Python-Solution
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: final=[] #for any arr with small length than 1 if len(arr)<1: return [-1] else: for i in range(len(arr)): final.append(max(arr[i:])) #rightmost indexed element won't have any higher value final.append(-1) #when you are selecting max it will consider from first index but in our case we are only looking at greatest element on right side return(final[1:])
replace-elements-with-greatest-element-on-right-side
Easy Python Solution
YashashriShiral
0
139
replace elements with greatest element on right side
1,299
0.747
Easy
19,342
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/1031016/Python3-solution
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: x = arr[-1] arr[-1] = -1 for i in range(len(arr)-2,-1,-1): c = max(arr[i],x) arr[i] = x x = c return arr
replace-elements-with-greatest-element-on-right-side
Python3 solution
EklavyaJoshi
0
89
replace elements with greatest element on right side
1,299
0.747
Easy
19,343
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/975719/Easy-Solution-beats-98
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: max1 = arr[-1] for i in range(len(arr) - 1, -1, -1): x = arr[i] arr[i] = max1 if x > max1: max1 = x arr[-1] = -1 return arr
replace-elements-with-greatest-element-on-right-side
Easy Solution beats 98%
Aditya380
0
66
replace elements with greatest element on right side
1,299
0.747
Easy
19,344
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/564559/Python-Scan-right-to-left-with-commentary
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: length, result, max = len(arr), [], arr[-1] # Right to Left approach # Process last element and check for length of 1 case result.insert(0, -1) if length == 1: return result result.insert(0,arr[-1]) # Process second to last element and check for length of 2 case if length == 2: return result if arr[-2] > max: max = arr[-2] # Check for a new max for number in arr[(length-3)::-1]: result.insert(0, max) if number > max: max = number return result
replace-elements-with-greatest-element-on-right-side
[Python] Scan right to left with commentary
dentedghost
0
144
replace elements with greatest element on right side
1,299
0.747
Easy
19,345
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/474871/Easy-Python-Solution
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: res = [-1] for i in range(len(arr)-1, 0, -1): res.append(max(res[-1], arr[i])) return res[::-1]
replace-elements-with-greatest-element-on-right-side
Easy Python Solution
Yaxe522
0
277
replace elements with greatest element on right side
1,299
0.747
Easy
19,346
https://leetcode.com/problems/sum-of-mutated-array-closest-to-target/discuss/463586/Python3-Sort-and-scan
class Solution: def findBestValue(self, arr: List[int], target: int) -> int: arr.sort() s, n = 0, len(arr) for i in range(n): ans = round((target - s)/n) if ans <= arr[i]: return ans s += arr[i] n -= 1 return arr[-1]
sum-of-mutated-array-closest-to-target
[Python3] Sort & scan
ye15
20
1,700
sum of mutated array closest to target
1,300
0.431
Medium
19,347
https://leetcode.com/problems/sum-of-mutated-array-closest-to-target/discuss/749333/Python-solution-with-video-explanation
class Solution: def findBestValue(self, arr: List[int], target: int) -> int: arr.sort() length = len(arr) for x in range(length): sol = round(target / length) if arr[x] >= sol: return sol target -= arr[x] length -= 1 return arr[-1]
sum-of-mutated-array-closest-to-target
Python solution with video explanation
spec_he123
5
889
sum of mutated array closest to target
1,300
0.431
Medium
19,348
https://leetcode.com/problems/sum-of-mutated-array-closest-to-target/discuss/1278006/WEEB-DOES-PYTHON-USING-BINARY-SEARCH
class Solution: def findBestValue(self, arr: List[int], target: int) -> int: arr.sort() low, high = 0, arr[-1] memo = {} while low<=high: mid = low + (high-low) // 2 count=0 for i in range(len(arr)): if arr[i]>mid: count+= mid * (len(arr)-i) break else: count+=arr[i] if count == target: return mid if count < target: low = mid + 1 else: high = mid - 1 memo[mid] = abs(count-target) return min(sorted(zip(memo.values(), memo.keys())))[1]
sum-of-mutated-array-closest-to-target
WEEB DOES PYTHON USING BINARY SEARCH
Skywalker5423
2
283
sum of mutated array closest to target
1,300
0.431
Medium
19,349
https://leetcode.com/problems/sum-of-mutated-array-closest-to-target/discuss/2549536/Python-easy-to-read-and-understand-or-binary-search
class Solution: def findBestValue(self, arr: List[int], target: int) -> int: start, end = 0, max(arr) res, mn, val = float("inf"), float("inf"), -1 while start <= end: mid = (start + end)//2 sums = 0 for i in arr: sums += min(mid, i) val = abs(sums-target) if val == mn: res = min(res, mid) if val < mn: mn = val res = mid if sums >= target: end = mid-1 else: start = mid+1 return res
sum-of-mutated-array-closest-to-target
Python easy to read and understand | binary-search
sanial2001
1
209
sum of mutated array closest to target
1,300
0.431
Medium
19,350
https://leetcode.com/problems/sum-of-mutated-array-closest-to-target/discuss/463470/Python-3-(four-lines)-(Math-Solution)-(28-ms)-(beats-100)-(-O(n-log-n)-)-(-O(1)-space-)
class Solution: def findBestValue(self, A: List[int], t: int) -> int: L, A, y = len(A), [0]+sorted(A), 0 for i in range(L): y += (A[i+1]-A[i])*(L-i) if y >= t: return round(A[i+1] + (t-y)/(L-i) - 0.01) - Junaid Mansuri - Chicago, IL
sum-of-mutated-array-closest-to-target
Python 3 (four lines) (Math Solution) (28 ms) (beats 100%) ( O(n log n) ) ( O(1) space )
junaidmansuri
1
305
sum of mutated array closest to target
1,300
0.431
Medium
19,351
https://leetcode.com/problems/sum-of-mutated-array-closest-to-target/discuss/2825155/Python3-or-Sorting-%2B-Binary-Search
class Solution: def findBestValue(self, arr: List[int], target: int) -> int: arr = sorted(arr) n = len(arr) suffixSum = [0 for i in range(n)] totalSum = 0 for i in range(n-1,-1,-1): suffixSum[i] = suffixSum[i+1] + arr[i] if i < n-1 else arr[i] totalSum += arr[i] low,high = 0,max(arr) ans = math.inf diff = math.inf while low <= high: mid = (low+high)//2 ind = bisect.bisect_right(arr,mid) currentSum = totalSum - suffixSum[ind] + (n-ind) * mid if ind < n else totalSum if currentSum >= target: high = mid - 1 else: low = mid + 1 if abs(currentSum - target) < diff: ans = mid diff = abs(currentSum - target) elif abs(currentSum - target) == diff: ans = min(mid,ans) return ans
sum-of-mutated-array-closest-to-target
[Python3] | Sorting + Binary Search
swapnilsingh421
0
5
sum of mutated array closest to target
1,300
0.431
Medium
19,352
https://leetcode.com/problems/sum-of-mutated-array-closest-to-target/discuss/2312785/Python-3-Binary-Search-oror-prefix-sum
class Solution: def findBestValue(self, arr: List[int], target: int) -> int: def search(i): max_diff=float('inf') l,r=arr[i-1] if i-1>=0 else 0,arr[i] while l<=r: mid=l+(r-l)//2 v=pre+(n-i)*mid if abs(target-v)<max_diff: max_diff=abs(target-v) res=mid if v>target: r=mid-1 else: l=mid+1 return res arr.sort() pre,n=0,len(arr) for i,x in enumerate(arr): v=pre+(n-i)*x if v<target: pre+=x continue return x if v==target else search(i) return arr[-1]
sum-of-mutated-array-closest-to-target
[Python 3] Binary Search || prefix sum
gabhay
0
68
sum of mutated array closest to target
1,300
0.431
Medium
19,353
https://leetcode.com/problems/sum-of-mutated-array-closest-to-target/discuss/1714936/Binary-Search-Solution-or-Python3
class Solution: def solve(self,arr,k): # returns the sum of arr , when replaced with k by fallowing # the given conditions i=0 while i<len(arr): if arr[i]>k: break i=i+1 d=len(arr)-i d=d*k d=d+sum(arr[:i]) return d def findBestValue(self, arr: List[int], target: int) -> int: end=max(arr) start=1 x=0 res=0 rx=0 arr.sort() while start<=end: mid=start+(end-start)//2 a=list(arr) x=self.solve(a,mid) if x<target: start=mid+1 else: end=mid-1 if abs(rx-target)>abs(target-x): rx=x res=mid elif abs(rx-target)==abs(target-x): res=min(res,mid) rx=min(rx,x) return res #rx is the sum of previous minimum number replaced in the array # mid is the number we are storing in the res which is the number we are replacing in the array # every time we store sum of arr and mid (mid is the number we are replacing in the arr to get that sum) considering the minimum
sum-of-mutated-array-closest-to-target
Binary Search Solution | Python3
_SID_
0
88
sum of mutated array closest to target
1,300
0.431
Medium
19,354
https://leetcode.com/problems/number-of-paths-with-max-score/discuss/463581/Python3-Bottom-up-DP
class Solution: def pathsWithMaxScore(self, board: List[str]) -> List[int]: """bottom-up dp""" n = len(board) #dimension #count > 0 also indicates state is reachable dp = [[0, 0] for _ in range(n+1)] #score-count (augment by 1 for convenience) for i in reversed(range(n)): #not assuming reachability while updating state copy = [[0, 0] for _ in range(n+1)] #to be updated to new dp for j in reversed(range(n)): if board[i][j] == "X": continue #skip obstacle if board[i][j] == "S": #initialize "S" copy[j] = [0, 1] continue #find max score from neighbors for candidate in (copy[j+1], dp[j], dp[j+1]): #right/below/right-below if not candidate[1]: continue #not reachable if copy[j][0] < candidate[0]: copy[j] = candidate[:] elif copy[j][0] == candidate[0]: copy[j][1] = (copy[j][1] + candidate[1])%(10**9+7) #update with board number if board[i][j] != "E": copy[j][0] += int(board[i][j]) dp = copy return dp[0]
number-of-paths-with-max-score
[Python3] Bottom-up DP
ye15
1
65
number of paths with max score
1,301
0.387
Hard
19,355
https://leetcode.com/problems/number-of-paths-with-max-score/discuss/1250536/Python-3-solution-faster-than-70-of-solutions-2d-dynamic-programming
class Solution: def pathsWithMaxScore(self, board: List[str]) -> List[int]: n = len(board)-1 self.board = [[int(_) if _.isdigit() else _ for _ in x] for x in board] self.board[n][n] = 0 self.board[0][0] = 0 self.scores = [[0 for _ in range(n+2)] for x in range(n+2)] self.counts = [[0 for _ in range(n+2)] for x in range(n+2)] self.counts[n][n] = 1 for i in range(n, -1, -1): for j in range(n, -1, -1): if self.board[i][j] == 'X': continue highest_score = max(self.scores[i+1][j], self.scores[i+1][j+1], self.scores[i][j+1]) score = highest_score + self.board[i][j] self.scores[i][j] = score for i_x, j_x in [[i+1, j], [i+1, j+1], [i, j+1]]: if self.scores[i_x][j_x] == highest_score: self.counts[i][j] += self.counts[i_x][j_x] if self.counts[0][0] == 0: return [0, 0] else: return [self.scores[0][0], self.counts[0][0] % (10**9+7)]
number-of-paths-with-max-score
Python 3 solution, faster than 70% of solutions - 2d dynamic programming
mhviraf
0
80
number of paths with max score
1,301
0.387
Hard
19,356
https://leetcode.com/problems/number-of-paths-with-max-score/discuss/463674/Three-Solutions-in-Python-3-(DP)-(DFS-Without-Memo)-(DFS-With-Memo)-(ten-lines)
class Solution: def pathsWithMaxScore(self, B: List[str]) -> List[int]: L, B, m = len(B), [list(b) for b in B], 10**9 + 7 B[0][0], B[-1][-1], DP = '0', '0', [[(0,0) for _ in range(L)] for _ in range(L)] DP[-1][-1] = (0,1) for n in range(L-2,-1,-1): if B[L-1][n] == 'X': break DP[L-1][n] = (int(DP[L-1][n+1][0])+int(B[L-1][n]), 1) for n in range(L-2,-1,-1): if B[n][L-1] == 'X': break DP[n][L-1] = (int(DP[n+1][L-1][0])+int(B[n][L-1]), 1) for i,j in itertools.product(range(L-2,-1,-1),range(L-2,-1,-1)): if B[i][j] == 'X': continue M = max(DP[x][y][0] for x,y in [(i,j+1),(i+1,j+1),(i+1,j)]) P = sum(DP[x][y][1] for x,y in [(i,j+1),(i+1,j+1),(i+1,j)] if DP[x][y][0]==M) DP[i][j] = (int(B[i][j])*(P>0) + M, P) return [DP[0][0][0], DP[0][0][1] % m]
number-of-paths-with-max-score
Three Solutions in Python 3 (DP) (DFS Without Memo) (DFS With Memo) (ten lines)
junaidmansuri
0
198
number of paths with max score
1,301
0.387
Hard
19,357
https://leetcode.com/problems/number-of-paths-with-max-score/discuss/463674/Three-Solutions-in-Python-3-(DP)-(DFS-Without-Memo)-(DFS-With-Memo)-(ten-lines)
class Solution: def pathsWithMaxScore(self, B: List[str]) -> List[int]: L, A, B[-1], m = len(B), [0,0], B[-1][:-1]+'0', 10**9 + 7 def dfs(i,j,s): if (i,j) == (0,0): [A[0],A[1]] = [s,1] if s > A[0] else [s,A[1]+1] if s == A[0] else A elif B[i][j] != 'X': [0<=x<L and 0<=y<L and dfs(x,y,s+int(B[i][j])) for x,y in [(i-1,j),(i,j-1),(i-1,j-1)]] dfs(L-1,L-1,0) return [A[0], A[1] % m]
number-of-paths-with-max-score
Three Solutions in Python 3 (DP) (DFS Without Memo) (DFS With Memo) (ten lines)
junaidmansuri
0
198
number of paths with max score
1,301
0.387
Hard
19,358
https://leetcode.com/problems/number-of-paths-with-max-score/discuss/463674/Three-Solutions-in-Python-3-(DP)-(DFS-Without-Memo)-(DFS-With-Memo)-(ten-lines)
class Solution: def pathsWithMaxScore(self, B: List[str]) -> List[int]: L, D, B[-1], m = len(B), {(0,0):(0,1)}, B[-1][:-1]+'0', 10**9 + 7 def dfs(i,j): if (i,j) in D: return D[(i,j)] if i < 0 or j < 0 or B[i][j] == "X": return (0,0) SP = [dfs(x,y) for x,y in [(i-1,j),(i,j-1),(i-1,j-1)]] S = max(SP[i][0] for i in range(3)) D[(i,j)] = (int(B[i][j]) + S, sum(y for x,y in SP if x == S)) return D[(i,j)] (MS,MP) = dfs(L-1,L-1) return [[MS,0][MP == 0], MP % m] - Junaid Mansuri - Chicago, IL
number-of-paths-with-max-score
Three Solutions in Python 3 (DP) (DFS Without Memo) (DFS With Memo) (ten lines)
junaidmansuri
0
198
number of paths with max score
1,301
0.387
Hard
19,359
https://leetcode.com/problems/deepest-leaves-sum/discuss/1763924/Python-Simple-Level-Order-Traversal
class Solution: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: q = [(root, 0)] ans = 0 curr_level = 0 # Maintains the current level we are at while len(q) != 0: # Do a simple Level Order Traversal current, max_level = q.pop(0) if max_level > curr_level: # Update the ans as curr_level gets outdated curr_level = max_level # Update curr_level ans = 0 # Ans needs to be constructed for the new level i.e. max_level ans += current.val if current.left is not None: q.append((current.left, max_level + 1)) if current.right is not None: q.append((current.right, max_level + 1)) return ans
deepest-leaves-sum
Python Simple Level Order Traversal
anCoderr
3
139
deepest leaves sum
1,302
0.868
Medium
19,360
https://leetcode.com/problems/deepest-leaves-sum/discuss/463578/Python3-Level-order-traversal
class Solution: def deepestLeavesSum(self, root: TreeNode) -> int: queue = [root] while queue: front = [] ans = 0 for node in queue: ans += node.val if node.left: front.append(node.left) if node.right: front.append(node.right) queue = front return ans
deepest-leaves-sum
[Python3] Level-order traversal
ye15
2
100
deepest leaves sum
1,302
0.868
Medium
19,361
https://leetcode.com/problems/deepest-leaves-sum/discuss/463578/Python3-Level-order-traversal
class Solution: def deepestLeavesSum(self, root: TreeNode) -> int: ans = 0 queue = deque([root]) while queue: val = 0 n = len(queue) for _ in range(n): node = queue.popleft() if node: val += node.val queue.append(node.left) queue.append(node.right) if val: ans = val return ans
deepest-leaves-sum
[Python3] Level-order traversal
ye15
2
100
deepest leaves sum
1,302
0.868
Medium
19,362
https://leetcode.com/problems/deepest-leaves-sum/discuss/2042579/Simple-Python-DFS-Solution-Explained
class Solution(object): def deepestLeavesSum(self, root): levels = {} def dfs(curr,prevVal,level): if curr==None: return level+=1 if level in levels: levels[level]+=curr.val else: levels[level]=curr.val dfs(curr.left,curr.val,level) dfs(curr.right,curr.val,level) dfs(root,0,0) return levels[max(levels)]
deepest-leaves-sum
Simple Python DFS Solution Explained
NathanPaceydev
1
99
deepest leaves sum
1,302
0.868
Medium
19,363
https://leetcode.com/problems/deepest-leaves-sum/discuss/2040435/99.10-faster-very-easy-BFS-7-lines-solution
class Solution: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: q = [root] level = [] while q and root: res = 0 for node in q: # We keep on adding node.val and resetting it to get last level value. res += node.val if node.left: level.append(node.left) if node.right: level.append(node.right) q = level level = [] return res
deepest-leaves-sum
99.10% faster very easy BFS 7 lines solution
ankurbhambri
1
108
deepest leaves sum
1,302
0.868
Medium
19,364
https://leetcode.com/problems/deepest-leaves-sum/discuss/2040223/Python3-Not-the-fastest-but-very-intuitive
class Solution: def __init__(self): self.total = 0 self.depth = 0 def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: def helperdepth(root): if not root: return 0 return 1 + max(helperdepth(root.left), helperdepth(root.right)) def helpersum(root,current): if root: if not root.left and not root.right and self.depth == current: self.total += root.val helpersum(root.left, current + 1) helpersum(root.right, current + 1) else: return self.depth = helperdepth(root) helpersum(root, 1) return self.total
deepest-leaves-sum
Python3 Not the fastest, but very intuitive
Chakchishing
1
50
deepest leaves sum
1,302
0.868
Medium
19,365
https://leetcode.com/problems/deepest-leaves-sum/discuss/2039605/Python-Solution-with-Explanation
class Solution: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: def dfs_(node, lvl, hm): ## function with argument if node is None: return hm ## If the node is null if lvl not in hm: hm[lvl] = [node.val] else: hm[lvl].append(node.val) hm = dfs_(node.left, lvl+1, hm) ## level increases with each recursion hm = dfs_(node.right, lvl+1, hm) return hm hm = dfs_(root, 0, {}) ## Get the hashmap using root ( initial level 0 and blank hashmap) return sum(hm[max(hm.keys())]) ## Get the sum of hashmap with maximum level
deepest-leaves-sum
Python Solution with Explanation
prithuls
1
17
deepest leaves sum
1,302
0.868
Medium
19,366
https://leetcode.com/problems/deepest-leaves-sum/discuss/2039303/Python-Simple-Recursion-Beats-~-97-(with-Explanation)
class Solution: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: deepest = (-1 , []) def deepestLeavesSumInner(node, depth): nonlocal deepest if node: if not node.left and not node.right: # if leave node if deepest[0]<depth: # check if its deepest leave deepest = (depth, [node.val]) elif deepest[0] == depth: deepest[1].append(node.val) else: deepestLeavesSumInner(node.left, depth + 1) deepestLeavesSumInner(node.right, depth + 1) deepestLeavesSumInner(root, 0) return sum(deepest[1])
deepest-leaves-sum
Python Simple Recursion Beats ~ 97% (with Explanation)
constantine786
1
45
deepest leaves sum
1,302
0.868
Medium
19,367
https://leetcode.com/problems/deepest-leaves-sum/discuss/1490160/Python-Clean-Recursive-Preorder
class Solution: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: def preorder(node = root, depth = 0): nonlocal maxd, total if not node: return if depth > maxd: maxd = depth total = 0 if depth == maxd: total += node.val preorder(node.left, depth+1) preorder(node.right, depth+1) maxd, total = -1, 0 preorder() return total
deepest-leaves-sum
[Python] Clean Recursive Preorder
soma28
1
226
deepest leaves sum
1,302
0.868
Medium
19,368
https://leetcode.com/problems/deepest-leaves-sum/discuss/1453567/python-level-order-traversal
class Solution: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: level=[] queue=[root] next_queue=[] ans=[] while queue: for root in queue: if root.left is not None: next_queue.append(root.left) if root.right is not None: next_queue.append(root.right) level.append(root.val) queue=next_queue next_queue=[] ans.append(level) level=[] return sum(ans[-1])
deepest-leaves-sum
python level order traversal
minato_namikaze
1
163
deepest leaves sum
1,302
0.868
Medium
19,369
https://leetcode.com/problems/deepest-leaves-sum/discuss/1447007/Python-7-lines-DFS-with-dictionary
class Solution: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: self.dict = collections.defaultdict(list) self.dfs(root, 0) return sum(self.dict[max(self.dict.keys())]) def dfs(self, node, level): if not node.right and not node.left: self.dict[level].append(node.val) if node.left: self.dfs(node.left, level+1) if node.right: self.dfs(node.right, level+1)
deepest-leaves-sum
Python 7 lines DFS with dictionary
SmittyWerbenjagermanjensen
1
159
deepest leaves sum
1,302
0.868
Medium
19,370
https://leetcode.com/problems/deepest-leaves-sum/discuss/1375941/bfs-with-list-and-recursion-85-95-faster
class Solution: def deepestLeavesSum(self, root: TreeNode,l=[]) -> int: if root==None: return [] if l==[]: l=[root] l2=[] for i in range(len(l)): lleaf=l[i].left rleaf=l[i].right if lleaf: l2.append(lleaf) if rleaf: l2.append(rleaf) if l2==[]: return sum([l[i].val for i in range(len(l))]) else: l=l2 return self.deepestLeavesSum(root,l)
deepest-leaves-sum
bfs with list & recursion 85-95% faster
pavanto3d
1
97
deepest leaves sum
1,302
0.868
Medium
19,371
https://leetcode.com/problems/deepest-leaves-sum/discuss/1331633/All-solutions-with-simple-explanations.-Different-intuitions-using-MAP-DFS-and-BFS.
class Solution: res = 0 def count(self, root, n): if not root: return n return max(self.count(root.left, n+1), self.count(root.right, n+1)) def sum(self, root, n): if not root: return if n == 1: self.res += root.val self.sum(root.left, n-1) self.sum(root.right, n-1) def deepestLeavesSum(self, root: TreeNode) -> int: n = self.count(root, 0) self.sum(root, n) return self.res
deepest-leaves-sum
All solutions, with simple explanations. Different intuitions using MAP, DFS and BFS.
deleted_user
1
114
deepest leaves sum
1,302
0.868
Medium
19,372
https://leetcode.com/problems/deepest-leaves-sum/discuss/1331633/All-solutions-with-simple-explanations.-Different-intuitions-using-MAP-DFS-and-BFS.
class Solution: def sum(self, root, n, lvl_map): if not root: return lvl_map if not lvl_map.get(n): lvl_map[n] = root.val else: lvl_map[n] += root.val self.sum(root.left, n+1, lvl_map) self.sum(root.right, n+1, lvl_map) return lvl_map def deepestLeavesSum(self, root: TreeNode) -> int: lvl_map = self.sum(root, 0, {}) return lvl_map[len(lvl_map)-1]
deepest-leaves-sum
All solutions, with simple explanations. Different intuitions using MAP, DFS and BFS.
deleted_user
1
114
deepest leaves sum
1,302
0.868
Medium
19,373
https://leetcode.com/problems/deepest-leaves-sum/discuss/471057/Python-3-(three-lines)-(beats-~99)
class Solution: def deepestLeavesSum(self, R: TreeNode) -> int: B = [R] while B: A, B = B, [c for n in B for c in [n.left,n.right] if c != None] return sum(a.val for a in A if a.val != None) - Junaid Mansuri - Chicago, IL
deepest-leaves-sum
Python 3 (three lines) (beats ~99%)
junaidmansuri
1
490
deepest leaves sum
1,302
0.868
Medium
19,374
https://leetcode.com/problems/deepest-leaves-sum/discuss/463285/BFS-Python-%3A-100-Efficient
class Solution: def deepestLeavesSum(self, root: TreeNode) -> int: q = collections.deque([root]) sm = prevsm = root.val while q: sm = prevsm sz = len(q) prevsm = 0 while sz: node = q.popleft() if node.left: q.append(node.left) prevsm += node.left.val if node.right: q.append(node.right) prevsm += node.right.val sz -= 1 return sm
deepest-leaves-sum
BFS Python : 100% Efficient
fallenranger
1
180
deepest leaves sum
1,302
0.868
Medium
19,375
https://leetcode.com/problems/deepest-leaves-sum/discuss/2777035/Level-Order-Way-in-Python
class Solution: def level_order(self, root: Optional[TreeNode]) -> List[List[int]]: queue = [root] level_order_numbers = [] while queue: size = len(queue) level = [] for _ in range(size): node = queue.pop(0) if node.left: queue.append(node.left) if node.right: queue.append(node.right) level.append(node.val) level_order_numbers.append(level) return level_order_numbers def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: level_order = self.level_order(root) return sum(level_order[-1])
deepest-leaves-sum
Level Order Way in Python
namashin
0
1
deepest leaves sum
1,302
0.868
Medium
19,376
https://leetcode.com/problems/deepest-leaves-sum/discuss/2687341/Simple-Python3-Solution
class Solution: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: self.d = defaultdict(int) def DFS(r, lvl): if r: if not r.left and not r.right: self.d[lvl] += r.val DFS(r.left, lvl + 1) DFS(r.right, lvl + 1) DFS(root, 0) m = max(self.d.keys()) return self.d[m]
deepest-leaves-sum
Simple Python3 Solution
mediocre-coder
0
6
deepest leaves sum
1,302
0.868
Medium
19,377
https://leetcode.com/problems/deepest-leaves-sum/discuss/2490557/Simple-BFS-faster-than-95
class Solution: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: if root is None: return 0 queue = collections.deque() queue.append(root) while queue: levelSize = len(queue) levelSum = 0 for _ in range(levelSize): currentNode = queue.popleft() levelSum += currentNode.val if currentNode.left: queue.append(currentNode.left) if currentNode.right: queue.append(currentNode.right) return levelSum
deepest-leaves-sum
Simple BFS faster than 95%
aruj900
0
32
deepest leaves sum
1,302
0.868
Medium
19,378
https://leetcode.com/problems/deepest-leaves-sum/discuss/2438322/DFS-%2B-HASHMAP
class Solution: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: depthTable = {} maxD = self.dfs(root,depthTable,0) return sum([x[0] for x in depthTable.values() if x[1] == maxD]) def dfs(self,node,depthTable,depth): if not node: return depth-1 depthTable[node] = (node.val,depth) return max(self.dfs(node.left,depthTable,depth+1),self.dfs(node.right,depthTable,depth+1))
deepest-leaves-sum
DFS + HASHMAP
alfredadjei2012
0
12
deepest leaves sum
1,302
0.868
Medium
19,379
https://leetcode.com/problems/deepest-leaves-sum/discuss/2199841/Short-Clean-Easy-and-very-Intuitive-with-Explanation
class Solution: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: if not root: return 0 q=deque() q.append(root) while len(q)!=0: total=0 # this will keep the sum of value of nodes of current level #the pointer will come back to the total as soon after finishing the each level #for the last level the pointer will not comeback to total so total will preserve the totalsum of nodes #of last level for i in range(len(q)): node=q.popleft() if node.right: q.append(node.right) if node.left: q.append(node.left) total+=node.val return total
deepest-leaves-sum
Short, Clean, Easy and very Intuitive with Explanation
Taruncode007
0
34
deepest leaves sum
1,302
0.868
Medium
19,380
https://leetcode.com/problems/deepest-leaves-sum/discuss/2043662/3-solutions-in-Python-using-DFS-BFS-and-literal-level-order-traversal
class Solution: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: from collections import deque max_depth = ans = 0 q = deque([(root, max_depth)]) while q: n, depth = q.popleft() if depth == max_depth: ans += n.val elif depth > max_depth: ans, max_depth = n.val, depth q += ((c, depth + 1) for c in (n.left, n.right) if c) return ans
deepest-leaves-sum
3 solutions in Python, using DFS, BFS and literal level-order traversal
mousun224
0
36
deepest leaves sum
1,302
0.868
Medium
19,381
https://leetcode.com/problems/deepest-leaves-sum/discuss/2043662/3-solutions-in-Python-using-DFS-BFS-and-literal-level-order-traversal
class Solution: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: lv, prev_lv = [root], [] while lv: prev_lv, lv = lv, [c for n in lv for c in (n.left, n.right) if c] return sum(n.val for n in prev_lv)
deepest-leaves-sum
3 solutions in Python, using DFS, BFS and literal level-order traversal
mousun224
0
36
deepest leaves sum
1,302
0.868
Medium
19,382
https://leetcode.com/problems/deepest-leaves-sum/discuss/2043662/3-solutions-in-Python-using-DFS-BFS-and-literal-level-order-traversal
class Solution: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: max_depth = ans = 0 def dfs(n: TreeNode = root, depth: int = 0): nonlocal max_depth, ans if depth == max_depth: ans += n.val elif depth > max_depth: ans = n.val max_depth = depth if n.left: dfs(n.left, depth + 1) if n.right: dfs(n.right, depth + 1) dfs() return ans
deepest-leaves-sum
3 solutions in Python, using DFS, BFS and literal level-order traversal
mousun224
0
36
deepest leaves sum
1,302
0.868
Medium
19,383
https://leetcode.com/problems/deepest-leaves-sum/discuss/2043094/Beats-80-Easy-to-understand-Beginner-DFS-Python-Solution
class Solution: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: leaveSum = {} def dfs(root, depth=0): if root is None: return if root.left is None and root.right is None: if depth in leaveSum: leaveSum[depth] = leaveSum[depth] + root.val else: leaveSum[depth] = root.val dfs(root.left, depth + 1) dfs(root.right, depth + 1) dfs(root) keys = leaveSum.keys() maxDepth = max(keys) return leaveSum[maxDepth]
deepest-leaves-sum
Beats 80% - Easy to understand - Beginner DFS Python Solution
7yler
0
23
deepest leaves sum
1,302
0.868
Medium
19,384
https://leetcode.com/problems/deepest-leaves-sum/discuss/2043031/Python-or-Commented-or-Recursion-or-O(n)-or-DFS
# Recursive Solution # Time: O(n) : Loops through each node once. # Space: O(d), d = tree depth : List containing sum for each depth (plus recursion stack). class Solution: def dfs(self, root: Optional[TreeNode]) -> List[int]: if not root: return [0] # No node, thus add 0 to current depth sum. if not root.left and not root.right: return [root.val] # No children, thus only retun current node value. leftDepthSums = self.dfs(root.left) # Gets depth sums from left children. rightDepthSums = self.dfs(root.right) # Gets depth sums from right children. depthSums = [root.val] # Adds current node's value to depth sums. minDepth = min(len(leftDepthSums), len(rightDepthSums)) # Gets the minimun depth of children. for index in range(minDepth): depthSums.append(leftDepthSums[index] + rightDepthSums[index]) # Sums sub depths and appends to list. depthSums.extend(leftDepthSums[minDepth:]) # If there are remaining depths in either list, extend list with depth sums. depthSums.extend(rightDepthSums[minDepth:]) return depthSums # Returns list containing sums for each sub depth. def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: return self.dfs(root)[-1] # Returns last depth sum (List: [sumDepth0, sumDepth1, ...])
deepest-leaves-sum
Python | Commented | Recursion | O(n) | DFS
bensmith0
0
25
deepest leaves sum
1,302
0.868
Medium
19,385
https://leetcode.com/problems/deepest-leaves-sum/discuss/2042366/Python-Solution-Using-BFS
class Solution: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: def bfs(node): res = [] if node is None: res.append([0]) return res nodes = [node] level_order = [] while len(nodes) > 0: size = len(nodes) cur_level = [] while size > 0: cur_node = nodes.pop(0) size -= 1 cur_level.append(cur_node.val) if cur_node.left: nodes.append(cur_node.left) if cur_node.right: nodes.append(cur_node.right) level_order.append(cur_level) return level_order if root.left is None and root.right is None: return root.val left = bfs(root.left) right = bfs(root.right) if len(right) > len(left): return sum(right[-1]) elif len(left) > len(right): return sum(left[-1]) return sum(left[-1]) + sum(right[-1])
deepest-leaves-sum
Python Solution Using BFS
pradeep288
0
13
deepest leaves sum
1,302
0.868
Medium
19,386
https://leetcode.com/problems/deepest-leaves-sum/discuss/2041063/Python3-Solution-with-using-dfs
class Solution: def __init__(self): self.res = 0 def find_max_lvl(self, node): if not node: return 0 return max(self.find_max_lvl(node.left), self.find_max_lvl(node.right)) + 1 def traversal(self, node, cur_lvl, max_lvl): if not node: return False if not self.traversal(node.left, cur_lvl + 1, max_lvl) and not self.traversal(node.right, cur_lvl + 1, max_lvl) and cur_lvl == max_lvl: self.res += node.val def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: max_lvl = self.find_max_lvl(root) self.traversal(root, 1, max_lvl) return self.res
deepest-leaves-sum
[Python3] Solution with using dfs
maosipov11
0
4
deepest leaves sum
1,302
0.868
Medium
19,387
https://leetcode.com/problems/deepest-leaves-sum/discuss/2040930/Python-easy-solution
class Solution: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: height = self.get_height_of_tree(root) return self.sum_of_leaves(root, height, 1) def get_height_of_tree(self, root): if root == None: return 0 return 1 + max(self.get_height_of_tree(root.left), self.get_height_of_tree(root.right)) def sum_of_leaves(self, root, height, pos): if root == None: return 0 if pos == height: return root.val return self.sum_of_leaves(root.left, height, pos+1) + self.sum_of_leaves(root.right, height, pos+1)
deepest-leaves-sum
Python - easy solution
TrueJacobG
0
11
deepest leaves sum
1,302
0.868
Medium
19,388
https://leetcode.com/problems/deepest-leaves-sum/discuss/2040391/Python-3-Interview-Answer-or-Clean-w-comment-and-complexity
class Solution: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: queue, count = deque([root]), 0 while queue: # reset the count on each new level, we only keep the count of the last level count = 0 for i in range(len(queue)): node = queue.popleft() count += node.val if node.left: queue.append(node.left) if node.right: queue.append(node.right) return count # Time Complexity: O(n) # Space Complexity: O(h)
deepest-leaves-sum
[Python 3] Interview Answer | Clean w/ comment and complexity
Cut
0
20
deepest leaves sum
1,302
0.868
Medium
19,389
https://leetcode.com/problems/deepest-leaves-sum/discuss/2039681/python-3-oror-simple-recursive-solution
class Solution: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: self.maxDepth = 0 self.res = 0 def helper(root, depth): if root is None: return if depth == self.maxDepth: self.res += root.val elif depth > self.maxDepth: self.maxDepth = depth self.res = root.val helper(root.left, depth + 1) helper(root.right, depth + 1) helper(root, 0) return self.res
deepest-leaves-sum
python 3 || simple recursive solution
dereky4
0
36
deepest leaves sum
1,302
0.868
Medium
19,390
https://leetcode.com/problems/deepest-leaves-sum/discuss/2039296/Python-DFS
class Solution: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: def dfs(node, level): if not node: return if level == self.deepest_level: self.deepest_sum += node.val elif level > self.deepest_level: self.deepest_level = level self.deepest_sum = node.val dfs(node.left, level + 1) dfs(node.right, level + 1) self.deepest_level = 0 self.deepest_sum = 0 dfs(root, 0) return self.deepest_sum
deepest-leaves-sum
Python, DFS
blue_sky5
0
59
deepest leaves sum
1,302
0.868
Medium
19,391
https://leetcode.com/problems/deepest-leaves-sum/discuss/2039283/Python-Solution-using-BFS-Level-Order-Traversal-or-O(N)
class Solution: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: if root is None: return 0 queue = deque() queue.append(root) res = [] while queue: temp = [] for _ in range(len(queue)): node = queue.popleft() temp.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) res.append(temp) return sum(res[-1])
deepest-leaves-sum
Python Solution using BFS Level Order Traversal | O(N)
PythonicLava
0
44
deepest leaves sum
1,302
0.868
Medium
19,392
https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/discuss/463818/Two-Solutions-in-Python-3-(one-line)-(beats-100)-(24-ms)
class Solution: def sumZero(self, n: int) -> List[int]: return list(range(1,n))+[-n*(n-1)//2]
find-n-unique-integers-sum-up-to-zero
Two Solutions in Python 3 (one line) (beats 100%) (24 ms)
junaidmansuri
12
1,300
find n unique integers sum up to zero
1,304
0.771
Easy
19,393
https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/discuss/463818/Two-Solutions-in-Python-3-(one-line)-(beats-100)-(24-ms)
class Solution: def sumZero(self, n: int) -> List[int]: return list(range(-(n//2), 0)) + [0]*(n % 2) + list(range(1, n//2 + 1)) - Junaid Mansuri - Chicago, IL
find-n-unique-integers-sum-up-to-zero
Two Solutions in Python 3 (one line) (beats 100%) (24 ms)
junaidmansuri
12
1,300
find n unique integers sum up to zero
1,304
0.771
Easy
19,394
https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/discuss/1597486/Python-3-simple-solution
class Solution: def sumZero(self, n: int) -> List[int]: res = [0] if n % 2 else [] for i in range(1, n // 2 + 1): res.append(i) res.append(-i) return res
find-n-unique-integers-sum-up-to-zero
Python 3 simple solution
dereky4
3
282
find n unique integers sum up to zero
1,304
0.771
Easy
19,395
https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/discuss/907626/Python-Faster-than-100
class Solution: def sumZero(self, n: int) -> List[int]: mid = n // 2 if (n &amp; 1): return [num for num in range(-mid, mid + 1)] else: return [num for num in range(-mid, mid + 1) if num != 0]
find-n-unique-integers-sum-up-to-zero
Python - Faster than 100%
JuanRodriguez
3
455
find n unique integers sum up to zero
1,304
0.771
Easy
19,396
https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/discuss/1516454/Python3-easy-to-udnerstand-solution
class Solution: def sumZero(self, n: int) -> List[int]: if n % 2 == 1: res = [0] else: res = [] i = 1 while len(res) != n: res = [-i] + res res.append(i) i += 1 return res
find-n-unique-integers-sum-up-to-zero
Python3 easy to udnerstand solution
GiorgosMarga
2
103
find n unique integers sum up to zero
1,304
0.771
Easy
19,397
https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/discuss/464043/One-Line-Solution
class Solution: def sumZero(self, n: int) -> List[int]: return list(range(1,n//2+1))+[0]*(n&amp;1)+list(range(-(n//2),0))
find-n-unique-integers-sum-up-to-zero
One Line Solution
fallenranger
2
235
find n unique integers sum up to zero
1,304
0.771
Easy
19,398
https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/discuss/2523817/Easy-Python-Solution
class Solution: def sumZero(self, n: int) -> List[int]: ans=[] if n%2==0: k=n//2 for i in range(k): ans.append(-i-1) for i in range(k): ans.append(i+1) else: k=n//2 for i in range(k): ans.append(-i-1) ans.append(0) for i in range(k): ans.append(i+1) return ans
find-n-unique-integers-sum-up-to-zero
Easy Python Solution
Siddharth_singh
1
116
find n unique integers sum up to zero
1,304
0.771
Easy
19,399