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/reformat-phone-number/discuss/1158993/Python-with-comment-94.44-faster-92.63-space
class Solution: def reformatNumber(self, number: str) -> str: res = "" # step 1: removing all non number characters number = re.sub('[^0-9]','',number) # step 2: grouping the digits from left to right until there are 4 or fewer digits while len(number) > 4: res += number[:3] + '-' number = number[3:] # step 3: 3 digits and 2 digits logic is the same if len(number) == 4: res += number[:2] + '-' + number[2:] else: res += number return res
reformat-phone-number
Python with comment // 94.44 faster 92.63 space
keewook2
2
190
reformat phone number
1,694
0.649
Easy
24,500
https://leetcode.com/problems/reformat-phone-number/discuss/2483922/Python-Solution-using-Minimal-New-Variables-(%2B-Explanation-for-Logic)
class Solution: def reformatNumber(self, number: str) -> str: # Written by LeetCode user DyHorowitz # remove the unnecessary characters - we don't care about the dashes nor spaces number = number.replace('-', '') number = number.replace(' ', '') # set up a return string to store our answer into returnString = "" # So long as there are more than 4 digits in number, # we want to group the first 3 into our return string # followed by a dash, then remove those 3 from the initial string while len(number) > 4: returnString += number[0:3] + "-" number = number[3:] # If there are only three digits left, we just put them all into # the return string and are done if len(number) == 3: returnString += number[0:3] # A remainder of 4 or 2 will result in blocks of 2, so # we might as well combine these two possibilities # for the first part and save some computing time else: returnString += number[0:2] number = number[2:] # This is where we test if there were 4 or 2 digits # left over. If there were 2, then removing the last # 2 in the step above should leave us with a string # of length 0 if len(number) > 0: returnString += "-" + number # Note that we only created ONE new variable in this entire function: # "returnString". By having 'number' overwrite itself, we save # significantly on memory space (you could probably save even more) # by using recursion to avoid storing any variables, however # that may come at the cost of processing time return returnString
reformat-phone-number
Python Solution using Minimal New Variables (+ Explanation for Logic)
DyHorowitz
1
46
reformat phone number
1,694
0.649
Easy
24,501
https://leetcode.com/problems/reformat-phone-number/discuss/1129084/Solution-in-Python-or-Faster-than-95
class Solution: def reformatNumber(self, number: str) -> str: number = ''.join(number.split('-')) number = ''.join(number.split()) if len(number)<=3: return number if len(number) == 4: return number[:2]+'-'+number[2:] i = 0 s = '' while(i<len(number)): s += number[i:i+3]+'-' i += 3 if len(number)-(i)<=4: if len(number)-(i) == 4: return s+number[i:(i+2)]+'-'+number[(i+2):] return s+number[i:] return s[:-1]
reformat-phone-number
Solution in Python | Faster than 95%
Annushams
1
202
reformat phone number
1,694
0.649
Easy
24,502
https://leetcode.com/problems/reformat-phone-number/discuss/2742444/Python3-Easy-commented-Solution
class Solution: def reformatNumber(self, number: str) -> str: result = [] counter = 0 for char in number: # only care for numbers if char.isdigit(): # check the counter if counter == 3: result.append('-') counter = 0 # append the number to the string result.append(char) # increase the counter counter += 1 # switch the last dash if there is a single numebr # at the end if result[-2] == '-': result[-3], result[-2] = result[-2], result[-3] return "".join(result)
reformat-phone-number
[Python3] - Easy, commented Solution
Lucew
0
9
reformat phone number
1,694
0.649
Easy
24,503
https://leetcode.com/problems/reformat-phone-number/discuss/2236067/Python-Solution
class Solution: def reformatNumber(self, number: str) -> str: ns=''.join([i for i in number if 48<=ord(i)<=57]) # Here we are extracting numbers from the input string rslt=[] while True: if len(ns)>4: rslt.append(ns[:3]) ns=ns[3:] else: if len(ns)==2: rslt.append(ns[:2]) ns=ns[2:] if len(ns)==3: rslt.append(ns[:3]) ns=ns[3:] if len(ns)==4: rslt.append(ns[:2]) rslt.append(ns[2:]) ns='' if len(ns)==0: break return '-'.join(rslt)
reformat-phone-number
Python Solution
DonaldReddy
0
43
reformat phone number
1,694
0.649
Easy
24,504
https://leetcode.com/problems/reformat-phone-number/discuss/2220184/Python-Solution
class Solution: def reformatNumber(self, number: str) -> str: st="" for i in number: if i !='-' and i!=' ': st=st+i if len(st)==4: return st[0:2]+'-'+st[2:4] i=0 stt="" while(i!=len(st)): stt=stt+st[i] i+=1 if i%3==0 and i!=len(st): stt=stt+'-' if len(st)-i==2 and len(st)%3!=0 and stt[-1]=='-': return stt+st[len(st)-2:len(st)] if len(st)-i==4 and len(st)%3!=0 and stt[-1]=='-': return stt+st[len(st)-4:len(st)-2]+'-'+st[len(st)-2:len(st)] if len(st)-i==5 and len(st)%3!=0 and stt[-1]=='-': return stt+st[len(st)-5:len(st)-2]+'-'+st[len(st)-2:len(st)] return stt
reformat-phone-number
Python Solution
T1n1_B0x1
0
33
reformat phone number
1,694
0.649
Easy
24,505
https://leetcode.com/problems/reformat-phone-number/discuss/2160879/python-O(n)
class Solution: def reformatNumber(self, number: str) -> str: digits = number digits = digits.replace(" " , "") digits = digits.replace("-","") res = [] i = 0 while i < len(digits)-4: res.append(digits[i:i+3]) i = i + 3 if len(digits[i:]) == 4: res.append(digits[i:i+2]) res.append(digits[i+2:]) else: res.append(digits[i:]) return "-".join(res)
reformat-phone-number
python O(n)
akashp2001
0
63
reformat phone number
1,694
0.649
Easy
24,506
https://leetcode.com/problems/reformat-phone-number/discuss/1983769/Recursive-solution-with-f-strings
class Solution: def reformatNumber(self, number: str) -> str: number = "".join([c for c in number if c.isdigit()]) size = len(number) if len(number) > 4: return f"{number[:3]}-{self.reformatNumber(number[3:])}" if len(number) == 4: return f"{number[:2]}-{number[2:]}" return number # remove all dashes, and spaces # if the digits size if greater than 4, create a 3 digit block # if the digit size is 4, create two 2 digit blocks # if it's none of the above it's two so just add it to the end # put a dash only after a 3 digit block or between a block of 2
reformat-phone-number
Recursive solution with f strings
andrewnerdimo
0
25
reformat phone number
1,694
0.649
Easy
24,507
https://leetcode.com/problems/reformat-phone-number/discuss/1906824/Python-Solution
class Solution: def reformatNumber(self, number: str) -> str: number = number.replace(' ', '').replace('-', '') result = '' number_len = len(number) while number: if number_len > 4: result += number[:3] + '-' number = number[3:] number_len -= 3 elif number_len == 4: return result + number[:2] + '-' + number[2:] else: return result + number
reformat-phone-number
Python Solution
hgalytoby
0
57
reformat phone number
1,694
0.649
Easy
24,508
https://leetcode.com/problems/reformat-phone-number/discuss/1896333/Python-clean-easy-code-for-beginners
class Solution: def reformatNumber(self, number: str) -> str: dig = "" for i in number: if i.isnumeric(): dig += i splits = [] if len(dig) % 3 == 0: for i in range(0, len(dig), 3): splits.append(dig[i:i+3]) elif len(dig) % 3 == 1: pos = 0 for i in range((len(dig) // 3) - 1): splits.append(dig[pos:pos+3]) pos += 3 last_group = dig[-4:] splits.extend([last_group[0:2], last_group[2:]]) else: pos = 0 for i in range((len(dig) // 3)): splits.append(dig[pos:pos+3]) pos += 3 splits.append(dig[-2:]) return '-'.join(splits)
reformat-phone-number
Python clean, easy code for beginners
alishak1999
0
36
reformat phone number
1,694
0.649
Easy
24,509
https://leetcode.com/problems/reformat-phone-number/discuss/1814808/Python-dollarolution
class Solution: def reformatNumber(self, number: str) -> str: s = '' for i in number: if i == '-' or i == ' ': continue s += i x, i, k = len(s), 0, 0 while x > 4: s = s[0:3+k+i] + '-' + s[3+i+k:] x -= 3 i += 3 k += 1 if x == 4: s = s[0:2+k+i] + '-' + s[2+k+i:] return s
reformat-phone-number
Python $olution
AakRay
0
56
reformat phone number
1,694
0.649
Easy
24,510
https://leetcode.com/problems/reformat-phone-number/discuss/1482964/Instinctive-solution-in-Python
class Solution: def reformatNumber(self, number: str) -> str: digits, s = [d for d in number if d.isdigit()], [] n = len(digits) d, r = divmod(n, 3) if r == 1: # the amount of trailing digits must be 2 or 4 d -= 1 r += 3 # concat the joined digits in length 3 and 2 respectively for i in range(0, n - r, 3): s += ''.join(digits[i:(i + 3)]), if r: for i in range(n - r, n, 2): s += ''.join(digits[i:(i + 2)]), return "-".join(s)
reformat-phone-number
Instinctive solution in Python
mousun224
0
66
reformat phone number
1,694
0.649
Easy
24,511
https://leetcode.com/problems/reformat-phone-number/discuss/1405954/Python3-Faster-Than-95.05
class Solution: def reformatNumber(self, number: str) -> str: import re s = re.findall("[0-9]", number) l, ss, i = len(s), "", 0 while(i < len(s)): if l > 4: ss += s[i] + s[i + 1] + s[i + 2] + '-' i += 3 l -= 3 elif l == 4: ss += s[i] + s[i + 1] + '-' + s[i + 2] + s[i + 3] return ss elif l == 3: ss += s[i] + s[i + 1] + s[i + 2] return ss else: ss += s[i] + s[i + 1] return ss
reformat-phone-number
Python3 Faster Than 95.05%
Hejita
0
82
reformat phone number
1,694
0.649
Easy
24,512
https://leetcode.com/problems/reformat-phone-number/discuss/1236300/python-noob-solution
class Solution: def reformatNumber(self, number: str) -> str: s=number s=s.replace(" ","") s=s.replace("-","") if len(s)<3: return s elif len(s)==4: return (s[:2]+"-"+s[2:]) ans=[] while len(s) >4: ans.append(s[0:3]) s=s.replace(s[0:3],"",1) if len(s) ==4: ans.append(s[:2]+"-"+s[2:]) else: ans.append(s) return "-".join(ans)
reformat-phone-number
python noob solution
Beastchariot
0
94
reformat phone number
1,694
0.649
Easy
24,513
https://leetcode.com/problems/reformat-phone-number/discuss/1235067/Python3Easy-understanding
class Solution: def reformatNumber(self, number: str) -> str: number = number.replace(" ","").replace("-","") i = 0 length = len(number) output = [] while i < length: if length - i == 4: output.append(number[i:i+2]) i += 2 elif length - i >= 3: output.append(number[i:i+3]) i += 3 else: output.append(number[i:i+2]) i += 2 return "-".join(output)
reformat-phone-number
【Python3】Easy-understanding
qiaochow
0
103
reformat phone number
1,694
0.649
Easy
24,514
https://leetcode.com/problems/reformat-phone-number/discuss/1055465/Python3-simple-and-easy-to-understand-solution
class Solution: def reformatNumber(self, number: str) -> str: num = (number.replace('-','')).replace(' ','') l = [] i = 0 while i < len(num): if len(num) - i > 4: l.append(num[i:i+3]) i += 3 elif len(num) - i <= 3: l.append(num[i:i+3]) i += 3 else: l.append(num[i:i+2]) i += 2 return '-'.join(l)
reformat-phone-number
Python3 simple and easy to understand solution
EklavyaJoshi
0
73
reformat phone number
1,694
0.649
Easy
24,515
https://leetcode.com/problems/reformat-phone-number/discuss/989251/Python-20-ms-14.3-MB-(12-ms13.2MB-by-Python2)
class Solution: def reformatNumber(self, number: str) -> str: digits = list(number.replace(" ", "").replace('-', "")) n = len(digits) grouplen = 2 if n == 4 else 3 groupctr = grouplen result = [] for d in digits: result.append(d) groupctr, n = groupctr - 1, n - 1 if groupctr == 0 and n != 0: result.append('-') if n == 4: grouplen = 2 groupctr = grouplen return ''.join(result)
reformat-phone-number
Python 20 ms, 14.3 MB (12 ms/13.2MB by Python2)
vashik
0
80
reformat phone number
1,694
0.649
Easy
24,516
https://leetcode.com/problems/reformat-phone-number/discuss/988705/Intuitive-approach-by-ifelse-to-group-numbers
class Solution: def reformatNumber(self, number: str) -> str: numbers = list(filter(lambda e: e in '1234567890', number)) group_numbers = [] while numbers: number_size = len(numbers) if number_size > 4: group_numbers.append(''.join(numbers[:3])) numbers = numbers[3:] elif number_size == 4: group_numbers.append(''.join(numbers[:2])) group_numbers.append(''.join(numbers[2:])) break else: group_numbers.append(''.join(numbers)) break return '-'.join(group_numbers)
reformat-phone-number
Intuitive approach by if/else to group numbers
puremonkey2001
0
31
reformat phone number
1,694
0.649
Easy
24,517
https://leetcode.com/problems/reformat-phone-number/discuss/979926/Python-O(N)-solution-faster-than-100
class Solution: def reformatNumber(self, number: str): pure_digits = number.replace(' ', '').replace('-', '') pure_digits_lengh = len(pure_digits) if pure_digits_lengh > 2: new_array = [] count = 0 temp = "" for d in pure_digits: if pure_digits_lengh - len("".join(new_array)) == 4 and temp == "": new_array.append(pure_digits[-4:-2]) new_array.append(pure_digits[-2:]) break count += 1 temp += d if count == 3: count = 0 new_array.append(temp) temp = "" if temp: new_array.append(temp) return '-'.join(new_array) else: return pure_digits
reformat-phone-number
Python O(N) solution faster than 100%
WiseLin
0
123
reformat phone number
1,694
0.649
Easy
24,518
https://leetcode.com/problems/maximum-erasure-value/discuss/2140512/Python-Easy-2-approaches
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: counter=defaultdict(int) # track count of elements in the window res=i=tot=0 for j in range(len(nums)): x=nums[j] tot+=x counter[x]+=1 # adjust the left bound of sliding window until you get all unique elements while i < j and counter[x]>1: counter[nums[i]]-=1 tot-=nums[i] i+=1 res=max(res, tot) return res
maximum-erasure-value
✅ Python Easy 2 approaches
constantine786
15
1,400
maximum erasure value
1,695
0.577
Medium
24,519
https://leetcode.com/problems/maximum-erasure-value/discuss/2140512/Python-Easy-2-approaches
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: seen=set() # track visited elements in the window res=i=tot=0 for j in range(len(nums)): x=nums[j] # adjust the left bound of sliding window until you get all unique elements while i < j and x in seen: seen.remove(nums[i]) tot-=nums[i] i+=1 tot+=x seen.add(x) res=max(res, tot) return res
maximum-erasure-value
✅ Python Easy 2 approaches
constantine786
15
1,400
maximum erasure value
1,695
0.577
Medium
24,520
https://leetcode.com/problems/maximum-erasure-value/discuss/1645653/WEEB-DOES-PYTHON-SLIDING-WINDOW-(BEATS-98.41)
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: low = 0 visited = set() result = 0 curSum = 0 for high in range(len(nums)): while nums[high] in visited: visited.remove(nums[low]) curSum -= nums[low] low+=1 visited.add(nums[high]) curSum += nums[high] if curSum > result: result = curSum return result
maximum-erasure-value
WEEB DOES PYTHON SLIDING WINDOW (BEATS 98.41%)
Skywalker5423
4
150
maximum erasure value
1,695
0.577
Medium
24,521
https://leetcode.com/problems/maximum-erasure-value/discuss/1378614/Python3-solution-or-set-or-faster-than-88
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: msf = -9999 # max sum so far meh = 0 # max sum ending here s = set() j = 0 i = 0 while j < len(nums): meh += nums[j] while nums[j] in s: meh -= nums[i] s.remove(nums[i]) i += 1 s.add(nums[j]) if msf < meh: msf = meh j += 1 return msf
maximum-erasure-value
Python3 solution | set | faster than 88%
FlorinnC1
3
238
maximum erasure value
1,695
0.577
Medium
24,522
https://leetcode.com/problems/maximum-erasure-value/discuss/2143503/Python-O(n)-Sliding-Window-%2B-Prefix-Sum-(75-faster)
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: if not nums: return 0 lastpos = {nums[0]: 0} maxsum = nums[0] left = -1 for i in range(1, len(nums)): # Find index of item if already met if nums[i] in lastpos: left = max(left, lastpos[nums[i]]) #Save save value's index to dictionary, as we're going from left to right lastpos[nums[i]] = i # Update the current nums[i] via prefix sum nums[i] += nums[i-1] # So it can be nums[i] (which is prefix sum from 0 to i) # Or it can be subarray sum from nums[left: i] if duplicate met -> # then formula becomes nums[i] - nums[left] sub_arr_sum = nums[i] - nums[left] if left != -1 else nums[i] maxsum = max(maxsum, sub_arr_sum) return maxsum
maximum-erasure-value
Python O(n) - Sliding Window + Prefix Sum (75 % faster)
muctep_k
1
32
maximum erasure value
1,695
0.577
Medium
24,523
https://leetcode.com/problems/maximum-erasure-value/discuss/2143432/Python-3-Solution-oror-O(n)-Time-and-Space-Complexity-oror-Two-Pointer-Approach
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: # Firstly left and right pointer are created for maintaing maximum sub array window left, right = 0, 0 # A set is created for for maintaing unique element subarray sub_array = set() # A variable for storing current sun_array sum sum_subarray = 0 # This variable will store max_sum of the max_sub_array result = 0 # Now we will loop throught our list/array while right < len(nums): # If element is not in our set then we will add it in our set and also update our current sum if nums[right] not in sub_array: sub_array.add(nums[right]) sum_subarray += nums[right] right += 1 # But if it is in our set then we will start removing elements from array using left pointer until the program goes back to if condition else: sum_subarray -= nums[left] sub_array.remove(nums[left]) left += 1 # In every loop we will keep updating our resultant sum result = max(result,sum_subarray) return result
maximum-erasure-value
✅ Python 3 Solution || O(n) Time and Space Complexity || Two Pointer Approach
mitchell000
1
31
maximum erasure value
1,695
0.577
Medium
24,524
https://leetcode.com/problems/maximum-erasure-value/discuss/2143162/Easy-to-understand-solution-in-python.
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: queue, setSum,maxSum= deque([]),0,0 for i in nums: if i not in queue: queue.append(i) setSum += i else: while queue[0] != i: popped = queue.popleft() setSum -= popped queue.popleft() queue.append(i) maxSum = max(setSum,maxSum) return maxSum
maximum-erasure-value
Easy to understand solution in python.
AY_
1
19
maximum erasure value
1,695
0.577
Medium
24,525
https://leetcode.com/problems/maximum-erasure-value/discuss/2142532/Python-Simple-Python-Solution-Using-Sliding-Window-and-Dictionary(HashMap)
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: current_sum =0 index = {} result = 0 j = 0 for i in range(len(nums)): current_sum = current_sum + nums[i] while nums[i] in index and j<index[nums[i]]+1: current_sum = current_sum - nums[j] j=j+1 index[nums[i]] = i result= max(result,current_sum) return result
maximum-erasure-value
[ Python ] ✅✅ Simple Python Solution Using Sliding Window and Dictionary(HashMap) 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
1
105
maximum erasure value
1,695
0.577
Medium
24,526
https://leetcode.com/problems/maximum-erasure-value/discuss/2141011/Python-O(n)-97.81-Faster-solution-Sliding-window-optimal-solution(WITH-COMMENTS)
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: HS=set() #declare a hash set to keep track of all unique values ans=0 #create ans variable to store the answer CS=0 #create current sum (CS) variable to store the current sum of the HASH SET i=0 #declare i as Left pointer for j in range(len(nums)): #iterate the array nums using j as a right pointer while nums[j] in HS: #check if there is a duplicate in the set if there is remove it HS.remove(nums[i]) CS-=nums[i] #decrease the current sum by substracting the duplicate value i+=1 #increase the left pointer HS.add(nums[j]) #while iterating using the right pointer add the values to the hash set CS+=nums[j] #maintain the current sum of the hash set ans=max(ans,CS) #use max function to keep track of the maximum ans return ans
maximum-erasure-value
Python O(n) 97.81% Faster solution Sliding window optimal solution(WITH COMMENTS)
anuvabtest
1
24
maximum erasure value
1,695
0.577
Medium
24,527
https://leetcode.com/problems/maximum-erasure-value/discuss/2140713/Python3-or-Very-Easy-or-Sliding-window-or-Dictionary
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: ans, curr_sum = 0, 0 ele_map={} arr = [] for e in nums: if ele_map.get(e, False): while arr and arr[0]!=e: v = arr.pop(0) curr_sum -= v del ele_map[v] arr.pop(0) arr.append(e) else: arr.append(e) ele_map[e] = 1 curr_sum += e ans = max(ans, curr_sum) return ans
maximum-erasure-value
Python3 | Very Easy | Sliding window | Dictionary
H-R-S
1
77
maximum erasure value
1,695
0.577
Medium
24,528
https://leetcode.com/problems/maximum-erasure-value/discuss/2140534/Python-or-Sliding-Window-and-Hash-Set-or-Easy-to-Understand
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: s = set() left = 0 max_sum = 0 cur_sum = 0 for right, num in enumerate(nums): # check the element that pointed by 'left' while num in s: s.remove(nums[left]) cur_sum -= nums[left] left += 1 cur_sum += num s.add(num) max_sum = max(max_sum, cur_sum) return max_sum
maximum-erasure-value
Python | Sliding Window & Hash Set | Easy to Understand
Mikey98
1
28
maximum erasure value
1,695
0.577
Medium
24,529
https://leetcode.com/problems/maximum-erasure-value/discuss/978539/Python3-sliding-window
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: prefix = [0] for x in nums: prefix.append(prefix[-1] + x) ans = ii = 0 seen = {} for i, x in enumerate(nums): ii = max(ii, seen.get(x, -1) + 1) ans = max(ans, prefix[i+1] - prefix[ii]) seen[x] = i return ans
maximum-erasure-value
[Python3] sliding window
ye15
1
128
maximum erasure value
1,695
0.577
Medium
24,530
https://leetcode.com/problems/maximum-erasure-value/discuss/978539/Python3-sliding-window
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: freq = defaultdict(int) ans = ii = val = 0 for x in nums: val += x freq[x] += 1 while freq[x] > 1: val -= nums[ii] freq[nums[ii]] -= 1 ii += 1 ans = max(ans, val) return ans
maximum-erasure-value
[Python3] sliding window
ye15
1
128
maximum erasure value
1,695
0.577
Medium
24,531
https://leetcode.com/problems/maximum-erasure-value/discuss/2836438/sliding-window
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: # use a current sum and overall sum to find best sum of # sub arrays # use two pointers to keep track of the sub arrays # use left pointer to define start of sub # use right to define end of sub # add elements at right two the set # if the value at right is in the set already # increment the left pointer until this is no longer # valid # while doing so, subtract the value at the left # pointer too and remove that value from the set # otherwise add the element at the right two the set # add the value at right to the current sum # find best sum between current sum and overall sum # time O(n) space O(n) res = curr = 0 l = r = 0 s = set() while r < len(nums): while nums[r] in s: s.remove(nums[l]) curr -= nums[l] l += 1 s.add(nums[r]) curr += nums[r] res = max(res, curr) r += 1 return res
maximum-erasure-value
sliding window
andrewnerdimo
0
2
maximum erasure value
1,695
0.577
Medium
24,532
https://leetcode.com/problems/maximum-erasure-value/discuss/2722322/python3-oror-Two-pointer-solution
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: windowDict = defaultdict(int) i = 0;j = 0;n = len(nums) windowSum = 0 ans = 0 while(i<n): while(windowDict[nums[j]]==0): windowDict[nums[j]]+=1 windowSum+=nums[j] j+=1 if(j==n): return max(ans,windowSum) ans = max(ans,windowSum) while(nums[i]!=nums[j]): windowDict[nums[i]]-=1 windowSum-=nums[i] i+=1 if(i==n): break windowDict[nums[i]]-=1 windowSum-=nums[i] i+=1 return ans
maximum-erasure-value
python3 || Two pointer solution
ty2134029
0
4
maximum erasure value
1,695
0.577
Medium
24,533
https://leetcode.com/problems/maximum-erasure-value/discuss/2646361/Python3-Solution-oror-O(N)-Time-and-O(1)-Space-Complexity
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: s=set() currSum=0 maxSum=0 start=0 for i in range(len(nums)): if nums[i] in s: while nums[i] in s: currSum-=nums[start] s.remove(nums[start]) start+=1 s.add(nums[i]) currSum+=nums[i] if maxSum<currSum: maxSum=currSum return maxSum
maximum-erasure-value
Python3 Solution || O(N) Time & O(1) Space Complexity
akshatkhanna37
0
2
maximum erasure value
1,695
0.577
Medium
24,534
https://leetcode.com/problems/maximum-erasure-value/discuss/2615418/Python-Sliding-Window-Solution-or-with-explanation
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: if len(set(nums)) == len(nums): # if the length of the set equals to the arr given that means there is no duplicate number so we will return their sums return sum(nums) res = 0 l = r = 0 #left and right pointers visit = set() #to control if there is a duplicate sum_ = 0 #sum() python builtin takes O(n) so to minimize that manually doing it saves some time for r in range(len(nums)): while nums[r] in visit and l <= r: #while we have a duplicate we will increment left pointer shrinking our window and also removing it from the visited set sum_-=nums[l] #also decrement the sum visit.remove(nums[l]) l+=1 sum_+=nums[r] res = max(res, sum_) visit.add(nums[r]) return res
maximum-erasure-value
Python Sliding Window Solution | with explanation
pandish
0
6
maximum erasure value
1,695
0.577
Medium
24,535
https://leetcode.com/problems/maximum-erasure-value/discuss/2447018/Python-3-or-Hashmap-or-with-explanation
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: if len(nums) <= 1: return nums[0] if nums else 0 map_index = defaultdict(int) # {number: its index} map_index[nums[0]] = 0 max_score = -float('inf') score = nums[0] i, j = 0, 1 while j < len(nums): score += nums[j] if nums[j] in map_index: id_dup = map_index[nums[j]] for k in range(i, id_dup + 1): # Delete num up to the duplicate number from the hash del map_index[nums[k]] for k in range(i, id_dup + 1): # Subtract the val from the score score -= nums[k] i = id_dup + 1 # Reset the starting position to be a position after the duplicating number map_index[nums[j]] = j max_score = max(max_score, score) j += 1 return max_score
maximum-erasure-value
Python 3 | Hashmap | with explanation
Ploypaphat
0
24
maximum erasure value
1,695
0.577
Medium
24,536
https://leetcode.com/problems/maximum-erasure-value/discuss/2310453/Python3-Solution-Using-Sliding-Window-Technique
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: #based on constraints of problem, since each integer is never negative, the sum will be predictable! #sliding window technique can work here1 #Time-Complexity: O(n^2) #Space-Complexity: O(n), in worst case, hashmap will store each and every element from nums #if all elements of numbs are unqiue! L = 0 hashmap = {} cur_sum = 0 ans = 0 #right pointer will traverse linearly throughout nums array expanding the cur_sliding_window! for R in range(len(nums)): #add to current sum regardless! cur_sum += nums[R] #here, hashmap keeps track of numbers seen and its frequency(at most it can be 2 at any given #time) #if cur_number already in hashmap, cur_number is a duplicate(stopped condition!) if(nums[R] in hashmap): hashmap[nums[R]] += 1 #stopping condition: as long as duplicate element remains in current window, keep shrinking! #in worst case, the sliding window has to be shrinked from one end to other end of array! while hashmap[nums[R]] > 1: #process left element before shrinking! left_element = nums[L] #cur_left_element is not duplicate we're looking for! if(left_element != nums[R]): hashmap.pop(left_element) else: hashmap[nums[R]] -= 1 #decrease from cur_sum the left value! cur_sum -= left_element #shift left pointer one right every time we have to shrink! L += 1 #once stopping condition is no longer met, we can continue expanding! else: hashmap[nums[R]] = 1 ans = max(ans, cur_sum) return ans
maximum-erasure-value
Python3 Solution Using Sliding Window Technique
JOON1234
0
29
maximum erasure value
1,695
0.577
Medium
24,537
https://leetcode.com/problems/maximum-erasure-value/discuss/2144842/Python-or-Commented-or-Sliding-Window-or-O(n)
# Sliding Window Solution with Set # Time: O(n), Iterates through input list at most twice (once to add to subsequence, once to remove from subsequence). # Space: O(n), Set containing subsequence from input list. class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: subsequence = set() # Set containing unique elements in a subsequence of nums. removeIndex = 0 # Index of element in nums to remove from subsequence if duplicate is found. score, maxScore = 0, 0 for element in nums: # Iterates through the elements in nums. while element in subsequence: # Loop to remove elements from subsequence window until element is not in set. subsequence.remove(nums[removeIndex]) # Remove element from set. score -= nums[removeIndex] # Subtract element value from score. removeIndex += 1 # Increase the index to remove (Adjusts the window by 1). subsequence.add(element) # Add unique element to subsequence. score += element # Add element value to current score. maxScore = max(maxScore, score) # Update maxScore with current score. return maxScore # Return highest score found from a subsequence.
maximum-erasure-value
Python | Commented | Sliding Window | O(n)
bensmith0
0
23
maximum erasure value
1,695
0.577
Medium
24,538
https://leetcode.com/problems/maximum-erasure-value/discuss/2144595/Python3-oror-Fast-And-Easy-oror-Sliding-Window-%2B-HashMap-oror-O(N)-O(N)
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: hmap = {} l, r, x, sm = 0, 0, 0, 0 maxval = -99999999 sums = [] for i in range(len(nums)): x += nums[i] sums.append(x) while r < len(nums): if nums[r] not in hmap or l > hmap[nums[r]]: hmap[nums[r]] = r sm += nums[r] else: maxval = max(maxval, sm) l = hmap[nums[r]]+1 sm = sums[r]-sums[l]+nums[l] hmap[nums[r]] = r maxval = max(maxval, sm) r+=1 return maxval
maximum-erasure-value
Python3✔️ || Fast And Easy || Sliding Window + HashMap || O(N) O(N)
Dewang_Patil
0
10
maximum erasure value
1,695
0.577
Medium
24,539
https://leetcode.com/problems/maximum-erasure-value/discuss/2144244/Sliding-window-made-easy-with-Python3
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: res=0 s=set() d=collections.Counter() n=len(nums) i=j=0 su=0 while i<n and j<n: t=nums[j] if t in s: while i<j and d[t]>0: d[nums[i]]-=1 su-=nums[i] i+=1 d[t]+=1 su+=nums[j] s.add(nums[j]) res=max(res,su) j+=1 return res
maximum-erasure-value
Sliding window made easy with Python3
atm1504
0
8
maximum erasure value
1,695
0.577
Medium
24,540
https://leetcode.com/problems/maximum-erasure-value/discuss/2142928/Python-solution
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: final_list = set() j = 0 final_sum = sum_ = 0 for i in range(len(nums)): while nums[i] in final_list: sum_ -= nums[j] final_list.remove(nums[j]) j += 1 final_list.add(nums[i]) sum_ += nums[i] #print(final_list) final_sum = max(sum_,final_sum) return final_sum
maximum-erasure-value
Python solution
NiketaM
0
24
maximum erasure value
1,695
0.577
Medium
24,541
https://leetcode.com/problems/maximum-erasure-value/discuss/2142216/Python-or-94-faster-or-Easy-and-same-approach-and-code-used-to-solve-leetcode-problem-3
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: # Solution 1 using set and using the same code used to solve leetcode # https://leetcode.com/submissions/detail/718847661/ just a little modification res = 0 subArrSum = 0 numSet = set() l = 0 for r in range(len(nums)): while nums[r] in numSet: subArrSum -= nums[l] numSet.remove(nums[l]) l += 1 numSet.add(nums[r]) subArrSum += nums[r] res = max(res,subArrSum) return res
maximum-erasure-value
Python | 94% faster | Easy and same approach and code used to solve leetcode problem 3
__Asrar
0
27
maximum erasure value
1,695
0.577
Medium
24,542
https://leetcode.com/problems/maximum-erasure-value/discuss/2141719/java-python-hash-and-sliding-window
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: table = set() l, r, summ, ans = 0, 0, 0, 0 while True : while r != len(nums) and nums[r] not in table : table.add(nums[r]) summ += nums[r] r += 1 ans = max(ans, summ) if r == len(nums): return ans while True : table.remove(nums[l]) summ -= nums[l] l += 1 if nums[l-1] == nums[r] : break
maximum-erasure-value
java, python - hash & sliding window
ZX007java
0
50
maximum erasure value
1,695
0.577
Medium
24,543
https://leetcode.com/problems/maximum-erasure-value/discuss/2141147/Defaultdict-%2B-Two-Pointer-or-Explained
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: start = 0 d = defaultdict(int) currSum = 0 ans = 0 for end in range(len(nums)): d[nums[end]] += 1 currSum += nums[end] if d[nums[end]] != 1: while d[nums[end]] != 1: d[nums[start]] -=1 if d[nums[start]] == 0: del d[nums[start]] currSum -= nums[start] start+=1 ans = max(ans,currSum) return ans
maximum-erasure-value
Defaultdict + Two Pointer | Explained
divyamohan123
0
19
maximum erasure value
1,695
0.577
Medium
24,544
https://leetcode.com/problems/maximum-erasure-value/discuss/2140623/python-3-oror-simple-sliding-window-solution-oror-O(n)O(n)
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: subNums = set() subSum = maxSubSum = 0 left = 0 for num in nums: while num in subNums: subNums.remove(nums[left]) subSum -= nums[left] left += 1 subNums.add(num) subSum += num maxSubSum = max(maxSubSum, subSum) return maxSubSum
maximum-erasure-value
python 3 || simple sliding window solution || O(n)/O(n)
dereky4
0
47
maximum erasure value
1,695
0.577
Medium
24,545
https://leetcode.com/problems/maximum-erasure-value/discuss/2140496/Python-two-pointers.-O(N)O(N)
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: start = result = sum_ = 0 unique = set() for num in nums: while num in unique: sum_ -= nums[start] unique.remove(nums[start]) start += 1 sum_ += num unique.add(num) result = max(result, sum_) return result
maximum-erasure-value
Python, two pointers. O(N)/O(N)
blue_sky5
0
16
maximum erasure value
1,695
0.577
Medium
24,546
https://leetcode.com/problems/maximum-erasure-value/discuss/2076784/A-O(n)-Python3-solution-without-using-additional-set()
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: ctr={} l, res = 0, 0 sums = 0 for r in range(len(nums)): sums += nums[r] ctr[nums[r]] = ctr.get(nums[r], 0) + 1 while ctr[nums[r]] != 1: ctr[nums[l]] -= 1 sums -= nums[l] l += 1 res = max(res, sums) return res
maximum-erasure-value
A O(n) Python3 solution without using additional set()
rusty_b
0
26
maximum erasure value
1,695
0.577
Medium
24,547
https://leetcode.com/problems/maximum-erasure-value/discuss/1824694/Python-easy-to-read-and-understand-or-sliding-window
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: n = len(nums) start = 0 t, sums, ans = set(), 0, 0 for i in range(n): while t and nums[i] in t: sums -= nums[start] t.remove(nums[start]) start += 1 t.add(nums[i]) sums += nums[i] ans = max(ans, sums) return ans
maximum-erasure-value
Python easy to read and understand | sliding window
sanial2001
0
58
maximum erasure value
1,695
0.577
Medium
24,548
https://leetcode.com/problems/maximum-erasure-value/discuss/1646982/Python3-Solution-or-O(n)
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: nums.append(0) D = dict() ans,left = 0,-1 for i in range(len(nums)-1): left = max(left,D.get(nums[i],-1)) D[nums[i]] = i nums[i] += nums[i-1] ans = max(ans,nums[i]-nums[left]) return ans
maximum-erasure-value
Python3 Solution | O(n)
satyam2001
0
72
maximum erasure value
1,695
0.577
Medium
24,549
https://leetcode.com/problems/maximum-erasure-value/discuss/1364697/Python3orSliding-window
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: ret=0 d=Counter() #dictionary to maintain frequency l=0 #left pointer sum_=0 for r in range(len(nums)): d[nums[r]]+=1 sum_+=nums[r] while d[nums[r]]>1: sum_-=nums[l] d[nums[l]]-=1 l+=1 ret=max(ret,sum_) return ret
maximum-erasure-value
Python3|Sliding window
atharva_shirode
0
97
maximum erasure value
1,695
0.577
Medium
24,550
https://leetcode.com/problems/maximum-erasure-value/discuss/1237564/Python-traditional-sliding-window-using-set
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: left,right,N = 0, 0, len(nums) buffer = set() current_sum = 0 maximum_sum = current_sum while right < N: if nums[right] not in buffer: buffer.add(nums[right]) current_sum += nums[right] right += 1 maximum_sum = max(current_sum, maximum_sum) else: buffer.remove(nums[left]) current_sum -= nums[left] left += 1 return maximum_sum
maximum-erasure-value
Python traditional sliding window using set
dee7
0
59
maximum erasure value
1,695
0.577
Medium
24,551
https://leetcode.com/problems/maximum-erasure-value/discuss/1236817/Python-Solution
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: n = len(nums) start = end = 0 visited = set() max_score = curr_score = 0 while end < n: if nums[end] in visited: max_score = max(max_score, curr_score) while nums[start] != nums[end]: curr_score -= nums[start] visited.remove(nums[start]) start += 1 curr_score -= nums[start] visited.remove(nums[start]) start += 1 else: visited.add(nums[end]) curr_score += nums[end] end += 1 return max(max_score, curr_score)
maximum-erasure-value
Python Solution
mariandanaila01
0
137
maximum erasure value
1,695
0.577
Medium
24,552
https://leetcode.com/problems/maximum-erasure-value/discuss/1236089/PythonPython3-Solution-with-explanation
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: visited = set() i,Sum,ans = 0,0,0 for ind in range(len(nums)): # traverse the loop till length of the nums while nums[ind] in visited: # If the number present already in the visited set visited.remove(nums[i]) # we'll remove the element from the visited set Sum -=nums[i]# subtract the element in the position of i that present in the visited set i += 1 #increment the variable i visited.add(nums[ind]) # add the numbers in the visited set Sum += nums[ind] #add the element to the Sum variable ans = max(ans,Sum) #store the maximum value of the sum return ans
maximum-erasure-value
Python/Python3 Solution with explanation
prasanthksp1009
0
85
maximum erasure value
1,695
0.577
Medium
24,553
https://leetcode.com/problems/maximum-erasure-value/discuss/1236068/Python-O(n)-solution
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: max_score, current_score, left, right, pointer, unique = 0, 0, 0, len(nums), 0, set() while right > pointer: if nums[pointer] in unique: while left < pointer: if nums[left] == nums[pointer]: left += 1 pointer += 1 break current_score -= nums[left] unique.remove(nums[left]) left += 1 else: current_score += nums[pointer] unique.add(nums[pointer]) pointer += 1 if current_score > max_score: max_score = current_score return max_score
maximum-erasure-value
Python O(n) solution
antoxa
0
62
maximum erasure value
1,695
0.577
Medium
24,554
https://leetcode.com/problems/maximum-erasure-value/discuss/1058504/Python-3-or-Easy-to-understand-sol-or-O(n)-Time
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: seen,i,j,ssum,maxs=set(),0,0,0,0 while j<len(nums): if nums[j] not in seen: seen.add(nums[j]) ssum+=nums[j] maxs=max(ssum,maxs) j+=1 else: while nums[j] in seen: seen.remove(nums[i]) ssum-=nums[i] i+=1 return maxs
maximum-erasure-value
Python 3 | Easy to understand sol | O(n) Time
rajatrai1206
0
91
maximum erasure value
1,695
0.577
Medium
24,555
https://leetcode.com/problems/maximum-erasure-value/discuss/980435/Python3-sliding-window
class Solution: def maximumUniqueSubarray(self, nums: List[int]) -> int: res = 0 start = 0 cur = 0 d = defaultdict(int) for end in range(len(nums)): item = nums[end] cur += item d[item] += 1 while d[item] > 1: d[nums[start]] -= 1 cur -= nums[start] if d[nums[start]] == 0: del d[nums[start]] start += 1 res = max(res, cur) return res
maximum-erasure-value
Python3 sliding window
ermolushka2
0
65
maximum erasure value
1,695
0.577
Medium
24,556
https://leetcode.com/problems/jump-game-vi/discuss/978563/Python3-range-max
class Solution: def maxResult(self, nums: List[int], k: int) -> int: pq = [] # max heap for i in reversed(range(len(nums))): while pq and pq[0][1] - i > k: heappop(pq) ans = nums[i] - pq[0][0] if pq else nums[i] heappush(pq, (-ans, i)) return ans
jump-game-vi
[Python3] range max
ye15
7
504
jump game vi
1,696
0.463
Medium
24,557
https://leetcode.com/problems/jump-game-vi/discuss/978563/Python3-range-max
class Solution: def maxResult(self, nums: List[int], k: int) -> int: queue = deque() for i in reversed(range(len(nums))): while queue and queue[0][1] - i > k: queue.popleft() ans = nums[i] if queue: ans += queue[0][0] while queue and queue[-1][0] <= ans: queue.pop() queue.append((ans, i)) return ans
jump-game-vi
[Python3] range max
ye15
7
504
jump game vi
1,696
0.463
Medium
24,558
https://leetcode.com/problems/jump-game-vi/discuss/2027018/3-Python-Solutions
class Solution: def maxResult(self, nums: List[int], k: int) -> int: dp=[nums[0]]+[0]*(len(nums)-1) for i in range(1,len(nums)): dp[i]=nums[i]+max(dp[max(0,i-k):i]) return dp[-1]
jump-game-vi
3 Python Solutions
Taha-C
3
328
jump game vi
1,696
0.463
Medium
24,559
https://leetcode.com/problems/jump-game-vi/discuss/2027018/3-Python-Solutions
class Solution: def maxResult(self, nums: List[int], k: int) -> int: heap=[(0,-k)] for i in range(len(nums)): while i-heap[0][1]>k: heappop(heap) nums[i]-=heap[0][0] heappush(heap,(-nums[i],i)) return nums[-1]
jump-game-vi
3 Python Solutions
Taha-C
3
328
jump game vi
1,696
0.463
Medium
24,560
https://leetcode.com/problems/jump-game-vi/discuss/2027018/3-Python-Solutions
class Solution: def maxResult(self, nums: List[int], k: int) -> int: dq=deque([(nums[0],0)]) for i in range(1,len(nums)): score=dq[0][0]+nums[i] while dq and dq[-1][0]<score: dq.pop() dq.append((score,i)) if dq[0][1]==i-k: dq.popleft() return dq[-1][0]
jump-game-vi
3 Python Solutions
Taha-C
3
328
jump game vi
1,696
0.463
Medium
24,561
https://leetcode.com/problems/jump-game-vi/discuss/2258981/Python-Multiple-Solution-1000-ms-Fast-solution
class Solution: def maxResult(self, nums: List[int], k: int) -> int: n = len(nums) deq = deque([n-1]) for i in range(n-2, -1, -1): if deq[0] - i > k: deq.popleft() nums[i] += nums[deq[0]] while len(deq) and nums[deq[-1]] <= nums[i]: deq.pop() deq.append(i) return nums[0]
jump-game-vi
Python Multiple Solution 1000 ms Fast solution
anuvabtest
2
313
jump game vi
1,696
0.463
Medium
24,562
https://leetcode.com/problems/jump-game-vi/discuss/2258981/Python-Multiple-Solution-1000-ms-Fast-solution
class Solution: def maxResult(self, A: List[int], k: int) -> int: log = deque([(0, -k)]) for i, a in enumerate(A): if i - log[0][1] > k: log.popleft() a += log[0][0] while log and log[-1][0] <= a: log.pop() log.append((a, i)) return a
jump-game-vi
Python Multiple Solution 1000 ms Fast solution
anuvabtest
2
313
jump game vi
1,696
0.463
Medium
24,563
https://leetcode.com/problems/jump-game-vi/discuss/2262971/Python3-Solution-with-using-deque
class Solution: def maxResult(self, nums: List[int], k: int) -> int: dq = collections.deque([0]) res = 0 for i in range(1, len(nums)): while dq and dq[0] < i - k: dq.popleft() nums[i] += nums[dq[0]] while dq and nums[i] >= nums[dq[-1]]: dq.pop() dq.append(i) return nums[-1]
jump-game-vi
[Python3] Solution with using deque
maosipov11
1
26
jump game vi
1,696
0.463
Medium
24,564
https://leetcode.com/problems/jump-game-vi/discuss/2257708/Cleanest-Python3-Solution-%2B-Explanation-%2B-Complexity-Analysis-Sliding-Window-DP
class Solution: def maxResult(self, nums: List[int], k: int) -> int: for i in range(1, len(nums)): nums[i] += max(nums[j] for j in range(max(i-k, 0), i)) return nums[-1]
jump-game-vi
Cleanest Python3 Solution + Explanation + Complexity Analysis / Sliding Window / DP
code-art
1
181
jump game vi
1,696
0.463
Medium
24,565
https://leetcode.com/problems/jump-game-vi/discuss/2305309/Python-Time-2076-ms-oror-Memory-28.1-MB-oror-Easy-to-understand
class Solution: def maxResult(self, nums: List[int], k: int) -> int: q = [0] i = 1 n = len(nums) while i < n: if (q[0] + k) < i: q.pop(0) nums[i] += nums[q[0]] while len(q) > 0 and nums[q[-1]] <= nums[i]: q.pop() q.append(i) i += 1 return nums.pop()
jump-game-vi
[Python] Time 2076 ms || Memory 28.1 MB || Easy to understand
Buntynara
0
99
jump game vi
1,696
0.463
Medium
24,566
https://leetcode.com/problems/jump-game-vi/discuss/2257841/Python3-or-DP-to-Heap-or-explain-4-approaches
class Solution: def maxResult(self, nums: List[int], k: int) -> int: n = len(nums) dp = [[0 for _ in range(n)] for _ in range(n)] for i in range(n-1, -1, -1): for j in range(i, n): if(i == j): dp[i][j] = nums[i] else: dp[i][j] = nums[i] + self.getMax(dp, i+1,j, min(i+k, n-1, j)) return dp[0][-1] def getMax(self, dp, startIndex, j, endIndex): x = -float("inf") for index in range(startIndex, endIndex+1): x = max(x, dp[index][j]) return x
jump-game-vi
Python3 | DP to Heap | explain 4 approaches
Sanjaychandak95
0
23
jump game vi
1,696
0.463
Medium
24,567
https://leetcode.com/problems/jump-game-vi/discuss/2257841/Python3-or-DP-to-Heap-or-explain-4-approaches
class Solution: def maxResult(self, nums: List[int], k: int) -> int: n = len(nums) dp = [0 for _ in range(n)] for i in range(n-1, -1, -1): if(i == n-1): dp[i] = nums[i] else: dp[i] = nums[i] + self.getMax(dp, i+1, min(i+k, n-1)) return dp[0] def getMax(self, dp, startIndex, endIndex): x = -float("inf") for index in range(startIndex, endIndex+1): x = max(x, dp[index]) return x
jump-game-vi
Python3 | DP to Heap | explain 4 approaches
Sanjaychandak95
0
23
jump game vi
1,696
0.463
Medium
24,568
https://leetcode.com/problems/jump-game-vi/discuss/1773983/Python-easy-to-read-and-understand-or-DP
class Solution: def maxResult(self, nums: List[int], k: int) -> int: n = len(nums) t = [0 for _ in range(n)] t[n-1] = nums[n-1] for i in range(n-2, -1, -1): start = i+1 end = min(n-1, i+k) temp = max(t[start:end+1]) t[i] = nums[i] + temp return t[0]
jump-game-vi
Python easy to read and understand | DP
sanial2001
0
208
jump game vi
1,696
0.463
Medium
24,569
https://leetcode.com/problems/checking-existence-of-edge-length-limited-paths/discuss/981352/Python3-Union-find
class Solution: def distanceLimitedPathsExist(self, n: int, edgeList: List[List[int]], queries: List[List[int]]) -> List[bool]: parent = [i for i in range(n+1)] rank = [0 for i in range(n+1)] def find(parent, x): if parent[x] == x: return x parent[x] = find(parent, parent[x]) return parent[x] def union(parent, a, b): a = find(parent, a) b = find(parent, b) if a == b: return if rank[a] < rank[b]: parent[a] = b elif rank[a] > rank[b]: parent[b] = a else: parent[b] = a rank[a] += 1 edgeList.sort(key = lambda x: x[2]) res = [0] * len(queries) queries = [[i, ch] for i, ch in enumerate(queries)] queries.sort(key = lambda x: x[1][2]) ind = 0 for i, (a, b, w) in queries: while ind < len(edgeList) and edgeList[ind][2] < w: union(parent, edgeList[ind][0], edgeList[ind][1]) ind += 1 res[i] = find(parent, a) == find(parent, b) return res
checking-existence-of-edge-length-limited-paths
Python3 Union find
ermolushka2
0
80
checking existence of edge length limited paths
1,697
0.502
Hard
24,570
https://leetcode.com/problems/checking-existence-of-edge-length-limited-paths/discuss/978567/Simple-Python-or-Union-Find
class Solution: def distanceLimitedPathsExist(self, n: int, A: List[List[int]], B: List[List[int]]) -> List[bool]: par = {} A.sort(key = lambda x: x[2]) for i, query in enumerate(B): query.append(i) B.sort(key = lambda x: x[2]) def find(a): par.setdefault(a, a) if par[a] != a: par[a] = find(par[a]) return par[a] def union(a, b): par.setdefault(a, a) par.setdefault(b, b) par[find(a)] = par[find(b)] ans = [False]*len(B) i = 0 for a, b, lim, idx in B: while i < len(A) and A[i][2] < lim: union(A[i][0], A[i][1]) i += 1 if find(a) == find(b): ans[idx] = True return ans
checking-existence-of-edge-length-limited-paths
Simple Python | Union Find
sushanthsamala
0
118
checking existence of edge length limited paths
1,697
0.502
Hard
24,571
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/1228863/Python3-32ms-Brute-Force-Solution
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: curr = 0 while students: if(students[0] == sandwiches[0]): curr = 0 students.pop(0) sandwiches.pop(0) else: curr += 1 students.append(students.pop(0)) if(curr >= len(students)): break return len(students)
number-of-students-unable-to-eat-lunch
[Python3] 32ms Brute Force Solution
VoidCupboard
11
442
number of students unable to eat lunch
1,700
0.679
Easy
24,572
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/2655855/Python-using-queue-push-pop
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: count = len(students) while(sandwiches and students and sandwiches[0] in students): if(sandwiches[0]!=students[0]): students.append(students[0]) students.pop(0) else: students.pop(0) sandwiches.pop(0) count-=1 return count
number-of-students-unable-to-eat-lunch
Python using queue push pop
liontech_123
2
268
number of students unable to eat lunch
1,700
0.679
Easy
24,573
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/2510921/Python-Queue-oror-easy-oror-approach
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: count = 0 while len(students) > count: if students[0] == sandwiches[0]: sandwiches.pop(0) count = 0 else: students.append(students[0]) count+=1 students.pop(0) return len(students) #Upvote will be encouraging.
number-of-students-unable-to-eat-lunch
Python Queue || easy || approach
anshsharma17
1
129
number of students unable to eat lunch
1,700
0.679
Easy
24,574
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/2374472/Python-Queue-Simplest-Solution-With-Explanation-or-Beg-to-adv-or-Queue
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: students = deque(students) # making provided list as queue for performing operation. sandwhiches = deque(sandwiches) # making provided list as queue for performing operation. count = 0 # taking a counter to count uneaten students. while count < len(students): # counter(uneaten) should always be less then total student. if students[0] == sandwhiches[0]: # if yes, then remove the element from both the queue. sandwhiches.popleft() # removing element from sandwiches queue. count = 0 # making counter zero as student took the sandwiches provided. else: students.append(students[0]) # if students dont take the sandwich, then its getting at the end of the queue(student queue). count += 1 # students.popleft() # there are two uses of it. 1) Once student take the sandwich and leave 2) When student dont take the sandwich and we move them to last of the queue. return len(students) # this will give us the total student how didnt eat.
number-of-students-unable-to-eat-lunch
Python Queue Simplest Solution With Explanation | Beg to adv | Queue
rlakshay14
1
127
number of students unable to eat lunch
1,700
0.679
Easy
24,575
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/2370578/Python-94.20-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Queue
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: while sandwiches: # Till the time we have sandwiches we`ll run this loop. if sandwiches[0] in students: # Now we`ll check if sandwich element are in student or not. In both the list we`ll be having 0`s and 1s, either student take a sandwich or not , either a student take a cicular sandwich or a square one. students.remove(sandwiches[0]) # Once we found remove the element from student that matches in sandwiches. sandwiches.pop(0) # Once we found remove the element from sandwiches that matches in student. else: break # in case we dont have matching elements, we`ll break the loop. return len(students) # then we`ll return how many students finally eat or not.
number-of-students-unable-to-eat-lunch
Python 94.20% faster | Simplest solution with explanation | Beg to Adv | Queue
rlakshay14
1
72
number of students unable to eat lunch
1,700
0.679
Easy
24,576
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/2077562/python3
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: students = deque(students) sandwich = sandwiches[0] while sandwich in students: if sandwich == students[0]: students.popleft() sandwiches.pop(0) if sandwiches: sandwich = sandwiches[0] else: student = students.popleft() students.append(student) if sandwiches: sandwich = sandwiches[0] return len(students)
number-of-students-unable-to-eat-lunch
python3
vgholami
1
61
number of students unable to eat lunch
1,700
0.679
Easy
24,577
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/2074116/python-or-easy
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: while sandwiches and sandwiches[0] in students: if students[0] == sandwiches[0]: del students[0] del sandwiches[0] else: students.append(students[0]) del students[0] return len(students)
number-of-students-unable-to-eat-lunch
python | easy
An_222
1
39
number of students unable to eat lunch
1,700
0.679
Easy
24,578
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/1655646/Python-intuitive-solution-using-deque-module
class Solution: from collections import deque def countStudents(self, students: List[int], sandwiches: List[int]) -> int: n = len(students) students, sandwiches = deque(students), deque(sandwiches) skips = 0 while skips < n: if len(students) == 0: return 0 elif students[0] == sandwiches[0]: students.popleft() sandwiches.popleft() skips = 0 else: s = students.popleft() students.append(s) skips += 1 return len(students)
number-of-students-unable-to-eat-lunch
Python intuitive solution using deque module
byuns9334
1
109
number of students unable to eat lunch
1,700
0.679
Easy
24,579
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/1571016/Python-faster-than-99.77
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: students = collections.deque(students) sandwhiches = collections.deque(sandwiches) skips = 0 while skips < len(students): if students[0] == sandwhiches[0]: sandwhiches.popleft() skips = 0 else: students.append(students[0]) skips += 1 students.popleft() return len(students)
number-of-students-unable-to-eat-lunch
Python faster than 99.77%
dereky4
1
372
number of students unable to eat lunch
1,700
0.679
Easy
24,580
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/1352281/Easy-Python-Solution(98.56)
class Solution: def countStudents(self, s: List[int], sa: List[int]) -> int: j=0 while j!=len(s): if(s[0]==sa[0]): j=0 s.pop(0) sa.pop(0) else: j+=1 g=s.pop(0) s.append(g) return len(s)
number-of-students-unable-to-eat-lunch
Easy Python Solution(98.56%)
Sneh17029
1
275
number of students unable to eat lunch
1,700
0.679
Easy
24,581
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/1292275/python-or-easy-or-90
class Solution: def countStudents(self, s: List[int], sa: List[int]) -> int: while s: if sa: if sa[0]==s[0]: sa.pop(0) s.pop(0) else: if sa[0] not in s: return len(s) break else: s.append(s.pop(0)) else: return len(s) break return 0
number-of-students-unable-to-eat-lunch
python | easy | 90%
chikushen99
1
158
number of students unable to eat lunch
1,700
0.679
Easy
24,582
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/1015791/Ultra-Simple-CPPPython3-Solution-or-Suggestions-for-optimization-are-welcomed-or
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: count=0 while len(students)>0 and count!=len(students): if students[0]==sandwiches[0]: students.pop(0) sandwiches.pop(0) count=0 else: temp=students[0] students.pop(0); students.append(temp); count=count+1 return len(students);
number-of-students-unable-to-eat-lunch
Ultra Simple CPP/Python3 Solution | Suggestions for optimization are welcomed |
angiras_rohit
1
58
number of students unable to eat lunch
1,700
0.679
Easy
24,583
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/1005644/Beginner-Code-or-Python3-or-Faster-then-99.94-Less-then-54.28-or-Queue-%2B-Stack
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: student = 0 stuck = False total = len(students) counter = 0 while(not stuck): counter+=1 if(len(students)==0): return 0 elif(students[0] == sandwiches[0]): sandwiches.pop(0) students.pop(0) counter = 0 elif (students[0] != sandwiches[0] and counter == len(sandwiches)): return len(students) else: students.append(students[0]) students.pop(0)
number-of-students-unable-to-eat-lunch
Beginner Code | Python3 | Faster then 99.94%, Less then 54.28% | Queue + Stack
vhso
1
140
number of students unable to eat lunch
1,700
0.679
Easy
24,584
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/2823351/Simple-while-loop
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: while sandwiches and sandwiches[0] in students: if students[0] == sandwiches[0]: students.pop(0) sandwiches.pop(0) else: students.append(students.pop(0)) return len(sandwiches)
number-of-students-unable-to-eat-lunch
Simple while loop
aruj900
0
3
number of students unable to eat lunch
1,700
0.679
Easy
24,585
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/2813614/faster-than-94-of-python
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: while True: if students[0] == sandwiches[0]: del students[0] del sandwiches[0] else: students.append(students[0]) del students[0] if (len(students) == 0 or len(students) == 0) or sandwiches[0] not in students: break return len(students)
number-of-students-unable-to-eat-lunch
faster than 94% of python
dastankg
0
3
number of students unable to eat lunch
1,700
0.679
Easy
24,586
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/2784069/Easy-to-understand
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: while(len(students) != 0 and len(sandwiches) != 0 and sandwiches[0] in students): if(students[0] == sandwiches[0]): students.pop(0) sandwiches.pop(0) else: students.append(students.pop(0)) return len(students)
number-of-students-unable-to-eat-lunch
Easy to understand
vishal02
0
2
number of students unable to eat lunch
1,700
0.679
Easy
24,587
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/2740444/Easy-Understand-Stack-Solution-Python
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: loop = 0 while loop <= len(students) and len(students)>0: if students[0]!=sandwiches[0]: front_s = students.pop(0) # print(front_s) students.append(front_s) loop +=1 elif students[0]==sandwiches[0]: students.pop(0) sandwiches.pop(0) loop=0 return len(students)
number-of-students-unable-to-eat-lunch
Easy Understand Stack Solution Python
ben_wei
0
5
number of students unable to eat lunch
1,700
0.679
Easy
24,588
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/2666691/Used-accumulator
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: # reverse sandwiches to get stack-like data structure # iterate while remaining students who want sandwiches # aren't entirely skipped # pop students off the queue and peek sandwiches. If they get # what they want, pop sandwiches and reset skipped, # otherwise append the student back and increment skipped # return len of students when once they're all skipped or empty # time O(n) space O(1) sandwiches.reverse() skipped = 0 while len(students) != skipped and students: sandwich = sandwiches[-1] pref = students.pop(0) if sandwich == pref: skipped = 0 sandwiches.pop() else: skipped += 1 students.append(pref) return len(students)
number-of-students-unable-to-eat-lunch
Used accumulator
andrewnerdimo
0
1
number of students unable to eat lunch
1,700
0.679
Easy
24,589
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/2624870/python-solution-95.56-faster
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: sandwiches.reverse() students.reverse() while sandwiches and students and sandwiches[-1] in students: if students[-1] == sandwiches[-1]: students.pop() sandwiches.pop() else: students.insert(0, students[-1]) students.pop() return len(students)
number-of-students-unable-to-eat-lunch
python solution 95.56% faster
samanehghafouri
0
14
number of students unable to eat lunch
1,700
0.679
Easy
24,590
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/2495759/Pyhton3-Solution-oror-Easy-oror-Understandable
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: curr = 0 while students : if students[0] != sandwiches[0]: curr += 1 pop = students.pop(0) students.append(pop) else: curr = 0 students.pop(0) sandwiches.pop(0) if(curr >= len(students)): break return len(students)
number-of-students-unable-to-eat-lunch
Pyhton3 Solution || Easy || Understandable
shashank_shashi
0
62
number of students unable to eat lunch
1,700
0.679
Easy
24,591
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/2297711/Python3-solution
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: d = {} ls = len(sandwiches) for stud in students: d[stud] = d.get(stud, 0) + 1 sand = 0 while sand < ls: curr = sandwiches[sand] if curr in d and d[curr] != 0: d[curr] -= 1 else: break sand += 1 return ls - sand
number-of-students-unable-to-eat-lunch
Python3 solution
mediocre-coder
0
19
number of students unable to eat lunch
1,700
0.679
Easy
24,592
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/2296225/Python-Easiest
class Solution(object): def countStudents(self, students, sandwiches): """ :type students: List[int] :type sandwiches: List[int] :rtype: int """ while not (len(set(students)) == 1 and students[0]!= sandwiches[0]): if students: st = students.pop(0) if st != sandwiches[0]: students.append(st) else: sandwiches.pop(0) else: return 0 return len(students)
number-of-students-unable-to-eat-lunch
Python Easiest
Abhi_009
0
41
number of students unable to eat lunch
1,700
0.679
Easy
24,593
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/2248058/Beginner-Friendly-Solution-oror-33ms-Faster-Than-98-oror-Python
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: # NOTE: If we mutate the argument lists, we end up also mutating any variables outside this method that may # be assigned to these lists at the time this method is called. These variables are known as aliases. # To avoid unintended consequences, we copy the arguments to use solely within this method. cp_students = students.copy() cp_sandwiches = sandwiches.copy() # We will run all operations within the while-loop below. prompts = 0 while prompts < len(cp_students): # If student takes a sandwich... if cp_students[0] == cp_sandwiches[0]: cp_students.pop(0) cp_sandwiches.pop(0) prompts = 0 # If student does NOT take a sandwich... else: cp_students.append(cp_students.pop(0)) prompts += 1 # This block of code handles both scenarios at the end of each iteration: # 1) All students currently in the queue are unable to eat. # 2) Every student has taken a sandwich. if prompts == len(cp_students): return len(cp_students)
number-of-students-unable-to-eat-lunch
Beginner Friendly Solution || 33ms, Faster Than 98% || Python
cool-huip
0
42
number of students unable to eat lunch
1,700
0.679
Easy
24,594
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/1981278/While-conditional-solution
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: while sandwiches and sandwiches[0] in students: student = students.pop(0) if sandwiches[0] == student: sandwiches.pop(0) else: students.append(student) return len(students) # explaination: # iterate the students as long as the students can grab sandwhich and while there's sandwiches to grab # pop the student, if the student wants the sandwich, pop the sandwich too. # if the student does not want to sandwich, add student to end of queue leave sanwhich
number-of-students-unable-to-eat-lunch
While conditional solution
andrewnerdimo
0
54
number of students unable to eat lunch
1,700
0.679
Easy
24,595
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/1955872/Python3-using-an-temporary-variable
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: fails = 0 while (len(students) > 0) and (fails < len(students)): stud = students.pop(0) if stud == sandwiches[0]: sandwiches.pop(0) fails = 0 else: students.append(stud) fails += 1 return fails
number-of-students-unable-to-eat-lunch
Python3 using an temporary variable
pX0r
0
60
number of students unable to eat lunch
1,700
0.679
Easy
24,596
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/1938617/Python-Easy-Solution(explained)-with-Counter
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: count = Counter(students) for s in sandwiches: if(count[s]>0): count[s] -= 1 else: break return count[0] + count[1]
number-of-students-unable-to-eat-lunch
Python Easy Solution(explained) with Counter
back2square1
0
33
number of students unable to eat lunch
1,700
0.679
Easy
24,597
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/1831833/5-Lines-Python-Solution-oror-99-Faster-oror-Memory-less-than-56
class Solution: def countStudents(self, ST: List[int], SA: List[int]) -> int: while True: if ST[0]==SA[0]: ST.pop(0) ; SA.pop(0) else: ST = ST[1:]+ST[:1] if len(ST)==0 or SA[0] not in ST: return len(ST) return 0
number-of-students-unable-to-eat-lunch
5-Lines Python Solution || 99% Faster || Memory less than 56%
Taha-C
0
91
number of students unable to eat lunch
1,700
0.679
Easy
24,598
https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/1815233/Python-dollarolution
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: x1 = sandwiches.count(1) x2 = students.count(1) if x2 == x1: return 0 else: k = len(sandwiches) if x2 > x1: a = k - x2 for i in range(k): if sandwiches[i] == 0: a -= 1 if a == -1: return (k - i) else: a = x2 for i in range(k): if sandwiches[i] == 1: a -= 1 if a == -1: return (k - i)
number-of-students-unable-to-eat-lunch
Python $olution
AakRay
0
59
number of students unable to eat lunch
1,700
0.679
Easy
24,599