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-sum-circular-subarray/discuss/1804620/Python-Very-Easy-Approach
class Solution: def maxSubarraySumCircular(self, nums: List[int]) -> int: minS = (1 << 31) minSum = 0 maxS = -(1 << 31) totSum = 0 maxSum = 0 for ele in nums: totSum += ele # Maximum Sum Subarray... maxSum += ele maxS = max(maxS, maxSum) if maxSum < 0: maxSum = 0 # ... # Minimum Sum Subarray... minSum += ele minS = min(minS, minSum) if minSum > 0: minSum = 0 # ... if(totSum == minS): return maxS return max(maxS, (totSum-minS))
maximum-sum-circular-subarray
Python - Very Easy Approach ✔
leet_satyam
3
212
maximum sum circular subarray
918
0.382
Medium
14,900
https://leetcode.com/problems/maximum-sum-circular-subarray/discuss/2388292/python-Dynamic-Programming
class Solution: def maxSubarraySumCircular(self, nums: List[int]) -> int: dp = [0] *len(nums) dp_min = [0] * len(nums) dp[0] = nums[0] dp_min[0] = nums[0] for i in range(1,len(nums)): dp[i] = max(dp[i-1]+nums[i],nums[i]) dp_min[i] = min(dp_min[i-1]+nums[i],nums[i]) if sum(nums) == min(dp_min): return max(dp) return max(max(dp),sum(nums)-min(dp_min))
maximum-sum-circular-subarray
python / Dynamic Programming
raise0915
2
27
maximum sum circular subarray
918
0.382
Medium
14,901
https://leetcode.com/problems/maximum-sum-circular-subarray/discuss/2059729/Python
class Solution: def maxSubarraySumCircular(self, nu: List[int]) -> int: ma = float("-inf") mi = float("inf") t1 = 0 t2 = 0 an = 0 nm = float("-inf") for i in range(len(nu)): if nu[i]>nm: nm = nu[i] an += nu[i] if nu[i] >= 0: t1 += nu[i] else: if t1+nu[i]>=0: t1 += nu[i] else: t1 = 0 if nu[i] <= 0: t2 += nu[i] else: if t2 + nu[i]<0: t2 += nu[i] else: t2 = 0 ma = max(ma,t1) mi = min(mi,t2) if nm<=0: return nm return max(ma,an-mi)
maximum-sum-circular-subarray
Python
Shivamk09
0
78
maximum sum circular subarray
918
0.382
Medium
14,902
https://leetcode.com/problems/maximum-sum-circular-subarray/discuss/2052025/Faster-than-99.44-of-Python3-online-submissions
class Solution: def maxSubarraySumCircular(self, nums: List[int]) -> int: z = max(nums) if z <= 0: return z sx = 0 si = 0 mi = 0 mx = 0 for a in nums: if a > a + sx: sx = a else: sx += a if sx > mx: mx = sx if a > a + si: si += a else: si = a if si < mi: mi = si return max(mx, sum(nums)-mi)
maximum-sum-circular-subarray
Faster than 99.44% of Python3 online submissions
mpekalski
0
39
maximum sum circular subarray
918
0.382
Medium
14,903
https://leetcode.com/problems/maximum-sum-circular-subarray/discuss/1775266/Python-easy-to-read-and-understand-or-kadane
class Solution: def kadane_max(self, nums): for i in range(1, len(nums)): if nums[i-1] > 0: nums[i] += nums[i-1] return max(nums) def kadane_min(self, nums): for i in range(1, len(nums)): if nums[i-1] < 0: nums[i] += nums[i-1] return min(nums) def maxSubarraySumCircular(self, nums: List[int]) -> int: x = self.kadane_max(nums[::]) y = sum(nums) - self.kadane_min(nums[::]) if y == 0: y = max(nums) return max(x, y)
maximum-sum-circular-subarray
Python easy to read and understand | kadane
sanial2001
0
140
maximum sum circular subarray
918
0.382
Medium
14,904
https://leetcode.com/problems/number-of-music-playlists/discuss/1358218/Python3-top-down-dp
class Solution: def numMusicPlaylists(self, n: int, goal: int, k: int) -> int: @cache def fn(i, x): """Return number starting from ith position with x songs already appeared.""" if i == goal: return x == n ans = 0 if x < n: ans += (n-x) * fn(i+1, x+1) # a new song if k < x: ans += (x-k) * fn(i+1, x) # an old song return ans % 1_000_000_007 return fn(0, 0)
number-of-music-playlists
[Python3] top-down dp
ye15
2
132
number of music playlists
920
0.506
Hard
14,905
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1230943/Python3-Simple-Solution
class Solution: def minAddToMakeValid(self, s: str) -> int: count = 0 x = y = 0 for i in s: if(i == '('): x += 1 else: x -= 1 if(x < 0): count += 1 x = 0 if(y < 0): count += 1 y = 0 return count + x + y
minimum-add-to-make-parentheses-valid
[Python3] Simple Solution
VoidCupboard
4
72
minimum add to make parentheses valid
921
0.762
Medium
14,906
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1393901/Python3-Super-easy-stack-implementation-1-pass
class Solution: def minAddToMakeValid(self, s: str) -> int: stack = [] for c in s: if len(stack): if stack[-1] == '(' and c == ')': stack.pop() else: stack.append(c) else: stack.append(c) return len(stack)
minimum-add-to-make-parentheses-valid
Python3, Super easy stack implementation, 1 pass
vineeth_moturu
2
84
minimum add to make parentheses valid
921
0.762
Medium
14,907
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/450636/Python-3-(six-lines)-(beats-~100)
class Solution: def minAddToMakeValid(self, S: str) -> int: S, t = ' ' + S + ' ', 0 while 1: while '()' in S: S = S.replace('()','') if len(S) <= 3: return t + len(S) - 2 while S[1] == ')': t, S = t + 1, ' ' + S[2:] while S[-2] == '(': t, S = t + 1, S[:-2] + ' ' - Junaid Mansuri - Chicago, IL
minimum-add-to-make-parentheses-valid
Python 3 (six lines) (beats ~100%)
junaidmansuri
2
303
minimum add to make parentheses valid
921
0.762
Medium
14,908
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1903721/Python-easy-to-read-and-understand-or-stack
class Solution: def minAddToMakeValid(self, s: str) -> int: ans = 0 stack = [] for i in range(len(s)): if s[i] == '(': stack.append(s[i]) else: if stack and stack[-1] == '(': stack.pop() else: ans += 1 return ans + len(stack)
minimum-add-to-make-parentheses-valid
Python easy to read and understand | stack
sanial2001
1
48
minimum add to make parentheses valid
921
0.762
Medium
14,909
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1655508/One-pass-in-Python
class Solution: def minAddToMakeValid(self, s: str) -> int: O, C = 0, 0 for char in s: if char == '(': O += 1 elif char == ')': if O > 0: O -= 1 else : C += 1 return O + C
minimum-add-to-make-parentheses-valid
One pass in Python
kryuki
1
65
minimum add to make parentheses valid
921
0.762
Medium
14,910
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/2842932/81.98-Faster-oror-Easy-Python-Solution-oror-O(N)-SolutionTw
class Solution: def minAddToMakeValid(self, s: str) -> int: open1 = 0 closing =0 stack =[] for i in range (len(s)): if stack and stack[-1] == "(" and s[i] == ")": open1-=1 closing-=1 stack.pop() if s[i] =='(': open1+=1 stack.append(s[i]) else: closing+=1 return open1+closing
minimum-add-to-make-parentheses-valid
81.98% Faster || Easy Python Solution || O(N) SolutionTw
arjuna07
0
1
minimum add to make parentheses valid
921
0.762
Medium
14,911
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/2814771/Python-Easy-Solution-(without-any-stack).
class Solution: def minAddToMakeValid(self, s: str) -> int: flag=1 while flag: if '()' in s: s=s.replace('()','') else: flag=0 return len(s)
minimum-add-to-make-parentheses-valid
Python Easy Solution (without any stack).
Abhishek004
0
2
minimum add to make parentheses valid
921
0.762
Medium
14,912
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/2784600/one-pass-python-O(n)
class Solution: def minAddToMakeValid(self, s: str) -> int: # O(n), O(1) left_count = right_count = added = 0 for char in s: if char == "(": left_count += 1 else: if right_count < left_count: right_count += 1 else: added += 1 added += left_count - right_count return added
minimum-add-to-make-parentheses-valid
one pass python O(n)
sahilkumar158
0
1
minimum add to make parentheses valid
921
0.762
Medium
14,913
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/2719155/Python3-faster-than-94
class Solution: def minAddToMakeValid(self, s: str) -> int: stack = [] for x in s: if x == "(": stack.append(x) elif x == ")": #checking if stack is empty or not if len(stack) != 0: #if last element is "(" then pop if stack[-1] == '(': stack.pop() continue #if the last element is not "(" or the stack is empty then append stack.append(x) return len(stack)
minimum-add-to-make-parentheses-valid
[Python3] faster than 94%
H_kashyap
0
1
minimum add to make parentheses valid
921
0.762
Medium
14,914
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/2701535/Beat-90
class Solution: def minAddToMakeValid(self, s: str) -> int: stack = [] counter = [0, 0] ret = 0 for char in s: if char == '(': counter[0] += 1 elif char == ')': counter[1] += 1 if counter[1] > counter[0]: ret += 1 counter = [0, 0] return ret + counter[0] - counter[1]
minimum-add-to-make-parentheses-valid
Beat 90%
Lara_Craft
0
3
minimum add to make parentheses valid
921
0.762
Medium
14,915
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/2677607/Simple-linear-solution-in-python
class Solution: def minAddToMakeValid(self, s: str) -> int: left_need, right_need = 0, 0 for i in range(len(s)): if (s[i] == '('): right_need += 1 else: # s[i] == ')' # found a new ')' so decrease right_need by 1 right_need -= 1 # when there's a ')' appearing before a '(', need to insert a '(' if (right_need == -1): right_need = 0 left_need += 1 return left_need + right_need
minimum-add-to-make-parentheses-valid
Simple linear solution in python
leqinancy
0
12
minimum add to make parentheses valid
921
0.762
Medium
14,916
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/2358733/Python-code-with-dry-run
class Solution: def minAddToMakeValid(self, s: str) -> int: """ closing - This will keep count of closing brackets opening - This will keep count of opeing brackets ( ) ) opening = 1 i ( ) ) opening = 0 i ( ) ) Since opening == 0 --> closing = 1 i Total no of unbalanced brackets = closing + opening We have to balance this ) ) ( opening == 0 --> closing = 1 i ) ) ( opening == 0 --> closing = 2 i ) ) ( opening = 1 i Total unbalanced braces = opening + closing = 3 """ closing = 0 opening = 0 for i in s: if i == '(': opening += 1 elif opening > 0: opening -= 1 else: closing += 1 return opening + closing
minimum-add-to-make-parentheses-valid
Python code with dry run
Pratyush_Priyam_Kuanr
0
11
minimum add to make parentheses valid
921
0.762
Medium
14,917
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/2255578/python-or-stackor-most-understandable
class Solution: def minAddToMakeValid(self, s: str) -> int: stack = Stack(1000) for i in s: if i == "(": stack.push(i) if i == ")" and stack.isEmpty() == True: stack.push(i) elif i == ")" and stack.peak() == ")": stack.push(i) elif i == ")" and stack.peak() == "(": stack.pop() return len(stack.data) class Stack: def __init__(self,size): self.size = size self.data = [] def isEmpty(self): if (len(self.data) ==0): return True else: return False def isFull(self): if (len(self.data) == self.size): return True else: return False def push(self,element): if self.isFull() == True: print("Stack is Full") else: self.data.append(element) def pop(self): if self.isEmpty() == True: print("Stack is empty") else: self.data.pop(-1) def peak(self): if self.isEmpty() == True: print("Stack is empty") else: return self.data[-1]
minimum-add-to-make-parentheses-valid
python | stack| most understandable
thomanani
0
24
minimum add to make parentheses valid
921
0.762
Medium
14,918
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/2131564/Python3-simple-use-of-stack
class Solution: def minAddToMakeValid(self, s: str) -> int: stack = [] for paran in s: if paran == '(': stack.append(paran) else: if stack and stack[-1] == '(': stack.pop() else: stack.append(paran) return len(stack)
minimum-add-to-make-parentheses-valid
Python3 simple use of stack
think989
0
19
minimum add to make parentheses valid
921
0.762
Medium
14,919
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/2074378/python3-or-easy
class Solution: def minAddToMakeValid(self, s: str) -> int: stack_l = [] stack_r = [] for ch in s: if ch == '(': stack_l.append(ch) elif stack_l and ch == ')': stack_l.pop() else: stack_r.append(ch) return (len(stack_l) + len(stack_r))
minimum-add-to-make-parentheses-valid
python3 | easy
An_222
0
23
minimum add to make parentheses valid
921
0.762
Medium
14,920
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/2002824/Stack-Based-Solution-Easy-to-Understand
class Solution: def minAddToMakeValid(self, s: str) -> int: opened, closed = "(", ")" n = len(s) stack = [] ans = 0 for i in range(n): if s[i] in opened: stack.append(s[i]) elif s[i] in closed: if stack: # If we find a matching parantheses - pop from stack stack.pop() else: # If we don't find a matching parantheses - add 1 to answer ans += 1 # Finally check if there is something remaining in stack - For example if s is: "(((" if stack: ans += len(stack) return ans
minimum-add-to-make-parentheses-valid
Stack Based Solution - Easy to Understand
cppygod
0
24
minimum add to make parentheses valid
921
0.762
Medium
14,921
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1968650/Python-easy-solution-for-beginners-using-stacks
class Solution: def minAddToMakeValid(self, s: str) -> int: stack = [] count = 0 for i in s: if i == '(': stack.append("(") elif i == ')': if stack == []: count += 1 elif stack[-1] == "(": stack.pop(-1) count += stack.count("(") return count
minimum-add-to-make-parentheses-valid
Python easy solution for beginners using stacks
alishak1999
0
43
minimum add to make parentheses valid
921
0.762
Medium
14,922
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1797530/python-solution
class Solution: def minAddToMakeValid(self, s: str) -> int: openm = 0 temp = [] for i in range(len(s)-1,-1,-1): if s[i] == '(': if temp: temp.pop() else: openm += 1 elif s[i] == ')': temp.append(s[i]) return openm + len(temp)
minimum-add-to-make-parentheses-valid
python solution
MS1301
0
19
minimum add to make parentheses valid
921
0.762
Medium
14,923
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1751923/Easy-Python3-faster-than-99.48-and-Memory-less-than-94.30
class Solution: def minAddToMakeValid(self, s: str) -> int: add_open = 0 add_close = 0 for i in range(len(s)): if s[i] == '(': add_open += 1 elif s[i] == ')': if add_open > 0: add_open -=1 else: add_close += 1 return add_open + add_close
minimum-add-to-make-parentheses-valid
Easy Python3, faster than 99.48% and Memory less than 94.30%
user1078Z
0
14
minimum add to make parentheses valid
921
0.762
Medium
14,924
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1705678/Python3%3A-Simple-O(N)-time-O(1)-space-no-Stacks
class Solution: def minAddToMakeValid(self, s: str) -> int: opening = add = 0 for c in s: if c == '(': opening += 1 elif c == ')': if opening: # can remove a pair of balanced parenthesis opening -= 1 else: add += 1 # can't match, have to add one '(' earlier return add + opening # number of unmatched ')' + '('
minimum-add-to-make-parentheses-valid
[Python3]: Simple O(N) time, O(1) space, no Stacks
smoothpineberry
0
47
minimum add to make parentheses valid
921
0.762
Medium
14,925
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1665114/One-pass-with-2-stacks
class Solution: def minAddToMakeValid(self, s: str) -> int: open_stack = [] closed_stack = [] S = list(s) for i in S: if i == '(': open_stack.append(i) elif i == ')': if open_stack: open_stack.pop() else: closed_stack.append(i) return len(open_stack) + len(closed_stack)
minimum-add-to-make-parentheses-valid
One pass with 2 stacks
KoalaKeys
0
18
minimum add to make parentheses valid
921
0.762
Medium
14,926
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1633841/It's-basically-stack-problem-even-though-we-can-further-optimize-to-O(1)-space.
class Solution: def minAddToMakeValid(self, s: str) -> int: stack = [] for c in s: if len(stack) == 0: stack.append(c) elif stack[-1] == "(": if c == ")": stack.pop() else: stack.append(c) else: ## stack[-1] == ")" stack.append(c) return len(stack)
minimum-add-to-make-parentheses-valid
It's basically stack problem, even though we can further optimize to O(1) space.
byuns9334
0
62
minimum add to make parentheses valid
921
0.762
Medium
14,927
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1590553/Easy-python
class Solution: def minAddToMakeValid(self, s: str) -> int: stack = [] final = [] for i in s: if i == '(': stack.append(i) try: if i == ')': stack.pop() except: final.append(i) return len(final) + len(stack)
minimum-add-to-make-parentheses-valid
Easy python
japnitS
0
51
minimum add to make parentheses valid
921
0.762
Medium
14,928
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1568854/Easy-to-understand-or-Python3
class Solution: def minAddToMakeValid(self, s: str) -> int: stack=[] c=0 if s=='': return 0 s=list(s) for i in range(len(s)): if s[i]=='(': stack.append(i) elif s[i]==')' and len(stack)>0: stack.pop() elif s[i]==')' and len(stack)<=0: c+=1 return c+len(stack)
minimum-add-to-make-parentheses-valid
Easy to understand | Python3
n4gb07
0
23
minimum add to make parentheses valid
921
0.762
Medium
14,929
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1530562/Python3-Time%3A-O(n)-and-Space%3A-O(n)-with-stack-and-Space%3A-O(1)-without-stack
class Solution: def minAddToMakeValid(self, s: str) -> int: # count left counts and right counts that does not have matching parentheses # return sum of it # Time: O(n) # Space: O(n) # Optimize Space by removing stack # Time: O(n) # Space: O(1) stack = [] lc = rc = 0 for c in s: if c == '(': stack.append(c) # lc += 1 else: if len(stack) > 0: stack.pop() # if lc > 0: # lc -= 1 else: rc += 1 lc = len(stack) return lc + rc
minimum-add-to-make-parentheses-valid
[Python3] Time: O(n) & Space: O(n) with stack and Space: O(1) without stack
jae2021
0
39
minimum add to make parentheses valid
921
0.762
Medium
14,930
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1530562/Python3-Time%3A-O(n)-and-Space%3A-O(n)-with-stack-and-Space%3A-O(1)-without-stack
class Solution: def minAddToMakeValid(self, s: str) -> int: # count left counts and right counts that does not have matching parentheses # return sum of it # Time: O(n) # Space: O(n) # Optimize Space by removing stack # Time: O(n) # Space: O(1) # stack = [] lc = rc = 0 for c in s: if c == '(': # stack.append(c) lc += 1 else: # if len(stack) > 0: # stack.pop() if lc > 0: lc -= 1 else: rc += 1 # lc = len(stack) return lc + rc
minimum-add-to-make-parentheses-valid
[Python3] Time: O(n) & Space: O(n) with stack and Space: O(1) without stack
jae2021
0
39
minimum add to make parentheses valid
921
0.762
Medium
14,931
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1453122/PyPy3-Simple-solution-using-stack-w-comments
class Solution: def minAddToMakeValid(self, s: str) -> int: # Init stack = [] count = 0 # For each char for c in s: # If "(" is encountered, append if c == "(": stack.append(c) else: # if ")" is encountered, pop if stack: stack.pop() else: # for no matching "(" increment count count += 1 count += len(stack) # for no matching ")" increment count return count
minimum-add-to-make-parentheses-valid
[Py/Py3] Simple solution using stack w/ comments
ssshukla26
0
44
minimum add to make parentheses valid
921
0.762
Medium
14,932
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1386919/Simple-Python-Solution
class Solution: def minAddToMakeValid(self, s: str) -> int: stack=0 stack1=0 for i in s: if i=="(": stack+=1 elif i ==")": if stack==0: stack1+=1 else: stack-=1 return stack+stack1
minimum-add-to-make-parentheses-valid
Simple Python Solution
sangam92
0
76
minimum add to make parentheses valid
921
0.762
Medium
14,933
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1385107/Python3-Clean-solution-with-O(n)-and-O(1)-space
class Solution: def minAddToMakeValid(self, s: str) -> int: stack = [] #fake elem stack.append('#') for elem in s: if elem == '(': stack.append(elem) if elem == ')': if stack[-1] == '(': stack.pop() else: stack.append(elem) return len(stack) - 1 class Solution: def minAddToMakeValid(self, s: str) -> int: open_count = 0 close_count = 0 for symbol in s: if symbol == '(': open_count += 1 if symbol == ')': if open_count > 0: open_count -= 1 else: close_count += 1 return open_count + close_count
minimum-add-to-make-parentheses-valid
[Python3] Clean solution with O(n) and O(1) space
maosipov11
0
54
minimum add to make parentheses valid
921
0.762
Medium
14,934
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1315545/Python3-faster-than-86.22-O(n)-Time
class Solution: def minAddToMakeValid(self, s: str) -> int: stack = "" for cha in s: stack += cha if stack[len(stack) - 2:] == "()": stack = stack[:len(stack) - 2] return len(stack)
minimum-add-to-make-parentheses-valid
Python3 - faster than 86.22%, O(n) Time
CC_CheeseCake
0
34
minimum add to make parentheses valid
921
0.762
Medium
14,935
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1284628/Python3-solution-one-pass
class Solution: def minAddToMakeValid(self, s: str) -> int: o = c = 0 count = 0 for i,j in enumerate(s): if j == '(': o += 1 elif o == 0 and j == ')': count += 1 elif j == ')' and o != 0: c += 1 if o == c: o = c = 0 return count + o - c
minimum-add-to-make-parentheses-valid
Python3 solution one pass
EklavyaJoshi
0
27
minimum add to make parentheses valid
921
0.762
Medium
14,936
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1265293/python-or-95.55-or-two-approaches
class Solution: def minAddToMakeValid(self, s: str) -> int: p=[] for i in s: if i=='(': p.append(i) else: if p and p[-1]=='(': p.pop() else: p.append(i) return len(p)
minimum-add-to-make-parentheses-valid
python | 95.55% | two approaches
chikushen99
0
66
minimum add to make parentheses valid
921
0.762
Medium
14,937
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1265293/python-or-95.55-or-two-approaches
**class Solution: def minAddToMakeValid(self, s: str) -> int: bal=0 ans=0 for i ,c in enumerate(s): if c=='(': bal+=1 else: bal-=1 if u<0: ans-=bal bal=0 if bal<0: ans-=bal else: ans+=bal return ans **
minimum-add-to-make-parentheses-valid
python | 95.55% | two approaches
chikushen99
0
66
minimum add to make parentheses valid
921
0.762
Medium
14,938
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1240621/One-pass-easy-straight-forward-python3-solution-96-faster
class Solution: def minAddToMakeValid(self, s: str) -> int: l = [] for i in s: if i=='(': l.append(i) elif i==')': if '(' in l: l.pop() else: l.append(i) return (len(l))
minimum-add-to-make-parentheses-valid
One pass easy straight forward python3 solution 96% faster
Sanyamx1x
0
44
minimum add to make parentheses valid
921
0.762
Medium
14,939
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1167846/Python-O(N)-Stack-Solution-with-Explanation
class Solution: def minAddToMakeValid(self, S: str) -> int: if not S: #if blank string then return 0 return 0 stack = [] c = 0 #return c as final answer for i in S: """ Check if stack is empty. If empty then push character onto the stack and c += 1. We increment c because the parantheses are unbalanced when character is '(' or ')' and stack == [] """ if stack == []: if i == '(': stack.append(i) c += 1 if i == ')': stack.append(i) c += 1 else: #There are 4 cases when stack != [] """ Case 1: Top of stack is ')' and character is '(' Append '(' and c += 1 because parantheses after appending will be like ')('. No opening and closing pair of parenthesis found. Hence c += 1 """ if i == '(' and stack[-1] and stack[-1] == ')': c += 1 stack.append(i) """ Case 2: Top of stack is '(' and character is '(' Append '(' and c += 1 because parantheses after appending will be like '(('. No opening and closing pair of parenthesis found. Hence c += 1 """ elif i == '(' and stack[-1] and stack[-1] == '(': c += 1 stack.append(i) """ Case 3: Top of stack is ')' and character is ')' Append ')' and c += 1 because parantheses after appending will be like '))'. No opening and closing pair of parenthesis found. Hence c += 1 """ elif i == ')' and stack[-1] and stack[-1] == ')': c += 1 stack.append(i) """ Case 4: Top of stack is '(' and character is ')' Append ')' and c -= 1 because parantheses after appending will be like '()'. OPENING AND CLOSING PAIR OF PARENTHESIS FOUND! Hence c -= 1 Also, pop the top of the stack! """ elif i == ')' and stack[-1] and stack[-1] == '(': c -= 1 stack.pop() return c
minimum-add-to-make-parentheses-valid
Python O(N) Stack Solution with Explanation
user9677k
0
41
minimum add to make parentheses valid
921
0.762
Medium
14,940
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1077992/Python-Solution-or-Pythonic-or-Stack
class Solution: def minAddToMakeValid(self, S: str) -> int: # Check if the parenthesis is s a left parenthesis: # # 1. If it's a left parenthesis": # 2. If there's nothing inside the stack: # 1. If the parenthesis is '(' you add the left parenthesis to the list # 2. If the parenthesis is ')', you add 1 in variable 'result', since there will be a right parenthesis can never be valid # 3. If there's one in your stack, you take the parenthesis away. # 4. return the length of the parentheses + the variable term 'result' stack = [] result = 0 for parenthesis in S: if parenthesis == '(': stack.append(parenthesis) elif stack: stack.pop() else: result+=1 return result + len(stack)
minimum-add-to-make-parentheses-valid
Python Solution | Pythonic | Stack
sphilip1206
0
29
minimum add to make parentheses valid
921
0.762
Medium
14,941
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1055441/Ultra-Simple-CppPython3-Solution-or-0ms-or-Suggestions-for-optimization-are-welcomed-or
class Solution: def minAddToMakeValid(self, S: str) -> int: if len(S)==0: return 0; elif len(S)==1: return 1; st=[S[0]] print(st) for i in range(1,len(S)): if len(st)!=0 and st[len(st)-1]=='(' and S[i]==')': st.pop(len(st)-1); else: st.append(S[i]) print(st) return len(st);
minimum-add-to-make-parentheses-valid
Ultra Simple Cpp/Python3 Solution | 0ms | Suggestions for optimization are welcomed |
angiras_rohit
0
38
minimum add to make parentheses valid
921
0.762
Medium
14,942
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/818338/Python-easiest-and-simplest-answer-(2-lines-faster-than-95)
class Solution: def minAddToMakeValid(self, s: str) -> int: while "()" in s: s = s.replace("()", "") return len(s)
minimum-add-to-make-parentheses-valid
Python easiest and simplest answer (2 lines, faster than 95%)
domrusch
0
42
minimum add to make parentheses valid
921
0.762
Medium
14,943
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/485887/Python3-super-simple-solution-using-a-for()-loop
class Solution: def minAddToMakeValid(self, S: str) -> int: temp = [] for p in S: if temp and temp[-1] == "(" and p == ")": temp.pop() else: temp.append(p) return len(temp)
minimum-add-to-make-parentheses-valid
Python3 super simple solution using a for() loop
jb07
0
43
minimum add to make parentheses valid
921
0.762
Medium
14,944
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/338305/Python-Solution-using-Stack-with-excellent-comments-to-help-you-understand
class Solution: ''' O(n) time | O(n) space, where n is the length of "S" ''' def minAddToMakeValid(self, S: str) -> int: st = [] d = {"(": ")"} ct = 0 for char in S: # Opening parenthesis: Add it to the stack if char in d: st.append(char) else: # Closing parenthesis: Pop opening parenthesis from stack if stack has elements # Else, if the stack is empty we need to add a closing parenthesis here to make it valid so increment ct if st: st.pop() else: ct += 1 # Return the number of closing parenthesis needed + number of opening parenthesis that couldn't be closed return ct + len(st)
minimum-add-to-make-parentheses-valid
Python Solution using Stack, with excellent comments to help you understand
ajrator123
0
47
minimum add to make parentheses valid
921
0.762
Medium
14,945
https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/957358/Python3-greedy-O(N)
class Solution: def minAddToMakeValid(self, S: str) -> int: op = cl = 0 # open and closed parenthesis needed for c in S: cl += 1 if c == "(" else -1 # need ) to balance extra ( if cl < 0: cl = 0 op += 1 # need ( to balance extra ) return op + cl
minimum-add-to-make-parentheses-valid
[Python3] greedy O(N)
ye15
-1
57
minimum add to make parentheses valid
921
0.762
Medium
14,946
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/1490850/Simple-to-understand-oror-For-Beginners-oror-91-faster
class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: odd,even = [],[] for n in nums: if n%2: odd.append(n) else: even.append(n) o,e = 0,0 for i in range(len(nums)): if i%2==0: nums[i]=even[e] e+=1 else: nums[i]=odd[o] o+=1 return nums
sort-array-by-parity-ii
📌📌 Simple to understand || For Beginners || 91% faster 🐍
abhi9Rai
6
283
sort array by parity ii
922
0.707
Easy
14,947
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/1490850/Simple-to-understand-oror-For-Beginners-oror-91-faster
class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: e = 0 #even_index o = 1 #odd_index while e<len(nums) and o<len(nums): if nums[e]%2==0: e+=2 else: if nums[o]%2!=0: o+=2 else: nums[e],nums[o] = nums[o],nums[e] e+=2 o+=2 return num
sort-array-by-parity-ii
📌📌 Simple to understand || For Beginners || 91% faster 🐍
abhi9Rai
6
283
sort array by parity ii
922
0.707
Easy
14,948
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/2169529/Python3-O(n)-oror-O(1)
class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: even, odd = 0, 1 while even < len(nums) and odd < len(nums): while even < len(nums) and nums[even] % 2 == 0: even += 2 while odd < len(nums) and nums[odd] % 2 != 0: odd += 2 if even < len(nums) and odd < len(nums): nums[even], nums[odd] = nums[odd], nums[even] even += 2 odd += 2 return nums
sort-array-by-parity-ii
Python3 O(n) || O(1)
arshergon
2
87
sort array by parity ii
922
0.707
Easy
14,949
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/1694517/python-easy-solution-using-two-pointers-beats-90-solutions
class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: l,r=0,len(nums)-1 while l<len(nums) and r>0: if nums[l]%2==0: l+=2 elif nums[r]%2!=0: r-=2 else: nums[l],nums[r]=nums[r],nums[l] l+=2 r-=2 return nums
sort-array-by-parity-ii
python easy solution using two pointers beats 90% solutions
redux1779
2
137
sort array by parity ii
922
0.707
Easy
14,950
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/2351547/Sort-Array-By-Parity-II
class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: n = len(nums) for i in range(n-1): swapped= False for j in range(n-i-1): if nums[j]%2==0 and j%2!=0 : for k in range(j+1,n): if k%2==0 and nums[k]%2!=0: x = nums[j] nums[j]= nums[k] nums[k]= x swapped= True break; elif nums[j]%2!=0 and j%2==0 : for k in range(j+1,n): if k%2!=0 and nums[k]%2==0: x = nums[j] nums[j]= nums[k] nums[k]= x swapped= True break; if not swapped : return nums return nums
sort-array-by-parity-ii
Sort Array By Parity II
dhananjayaduttmishra
1
15
sort array by parity ii
922
0.707
Easy
14,951
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/2244432/Easiest-solution-for-beginners
class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: odd = [] ev = [] for i in nums: if i % 2 == 0: ev.append(i) else: odd.append(i) ans = [] for i in range(len(nums)//2): ans.append(ev[i]) ans.append(odd[i]) return ans
sort-array-by-parity-ii
Easiest solution for beginners
EbrahimMG
1
43
sort array by parity ii
922
0.707
Easy
14,952
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/1891606/Python-solution-good-for-beginners
class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: res = [] odd = [] even = [] odd_pos = 0 even_pos = 0 for i in nums: if i % 2 == 0: even.append(i) else: odd.append(i) for i in range(len(nums)): if i % 2 == 0: res.append(even[even_pos]) even_pos += 1 else: res.append(odd[odd_pos]) odd_pos += 1 return res
sort-array-by-parity-ii
Python solution good for beginners
alishak1999
1
50
sort array by parity ii
922
0.707
Easy
14,953
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/1847271/Python3-Two-Pointers
class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: odd = 1 for even in range(0, len(nums), 2): while nums[even] % 2 == 1: # if even place is odd nums[even], nums[odd] = nums[odd], nums[even] # swap with an odd place odd += 2 # fix one odd place, move to the next return nums
sort-array-by-parity-ii
Python3 Two Pointers
SilverCHN
1
30
sort array by parity ii
922
0.707
Easy
14,954
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/1816847/Fast-and-simple-Python-solution-using-list-comprehensions
class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: # Collect results in this list ret = [] # Filter by elements that are divisible by 2 evens = [n for n in nums if not x % 2] # Elements that are not divisible odds = [n for n in nums if x % 2] while len(odds) != 0 or len(evens) != 0: # Remove elements from parity lists and append to result list ret.append(evens.pop()) ret.append(odds.pop()) return ret
sort-array-by-parity-ii
Fast and simple Python solution using list comprehensions
kyrtap5
1
27
sort array by parity ii
922
0.707
Easy
14,955
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/466853/O(n)-soltuion
class Solution: def sortArrayByParityII(self, A: List[int]) -> List[int]: result=[0 for _ in range(len(A))] i=0 j=1 for x in A: if x % 2==0: result[i]=x i+=2 else: result[j]=x j+=2 return result
sort-array-by-parity-ii
O(n) soltuion
jerryqiushiyu
1
148
sort array by parity ii
922
0.707
Easy
14,956
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/300836/extremely-easy-understand-Python3-solution
class Solution: def sortArrayByParityII(self, A: List[int]) -> List[int]: ind=0 tem1=[] tem2=[] for i in A: if i%2==0: tem1.append(i) else: tem2.append(i) for i in tem1: tem2.insert(ind,i) ind+=2 return tem2
sort-array-by-parity-ii
extremely easy understand Python3 solution
JasperZhou
1
74
sort array by parity ii
922
0.707
Easy
14,957
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/2808260/Continue-from-905.-Sort-Array-By-Parity
class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: l, r = 0, len(nums) - 1 while l <= r: if nums[l]%2 == 0: l += 1 elif nums[r]%2 != 0: r -= 1 else: # nums[l]%2 != 0 and nums[r]%2 == 0: nums[l], nums[r] = nums[r], nums[l] l += 1 r -= 1 l, r = 0, len(nums) - 1 while l < r: if l %2 == 0: l += 1 elif r %2 == 1: r -= 1 else: nums[l], nums[r] = nums[r], nums[l] l += 1 r -= 1 return nums
sort-array-by-parity-ii
Continue from 905. Sort Array By Parity
champ-
0
2
sort array by parity ii
922
0.707
Easy
14,958
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/2806748/Python-Simple-Solution
class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: odd_index = 1 even_index = 0 result = [None for _ in range(len(nums))] for num in nums: if num % 2 == 0: result[even_index] = num even_index += 2 else: result[odd_index] = num odd_index += 2 return result
sort-array-by-parity-ii
Python Simple Solution
namashin
0
1
sort array by parity ii
922
0.707
Easy
14,959
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/2794072/simple-python-solution-O(n)-time-and-space-complexity
class Solution: def sortArrayByParityII(self, e: List[int]) -> List[int]: o, i = [], 0 while i<len(e): if e[i]%2==1: o.append(e.pop(i)) else: i+=1 j = 1 while o: e.insert(j, o.pop(0)) j+=2 return e
sort-array-by-parity-ii
simple python solution O(n) time and space complexity
gizawaait
0
1
sort array by parity ii
922
0.707
Easy
14,960
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/2794071/simple-python-solution-O(n)-time-and-space-complexity
class Solution: def sortArrayByParityII(self, e: List[int]) -> List[int]: o, i = [], 0 while i<len(e): if e[i]%2==1: o.append(e.pop(i)) else: i+=1 j = 1 while o: e.insert(j, o.pop(0)) j+=2 return e
sort-array-by-parity-ii
simple python solution O(n) time and space complexity
gizawaait
0
1
sort array by parity ii
922
0.707
Easy
14,961
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/2770073/Simple-Python-Solution
class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: odd = [x for x in nums if x%2!=0] even = [x for x in nums if x%2==0] nums = [] for x,y in zip(odd,even): nums.append(y) nums.append(x) return nums
sort-array-by-parity-ii
Simple Python Solution
dnvavinash
0
1
sort array by parity ii
922
0.707
Easy
14,962
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/2687102/Easy-python-solution
class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: res=[0]*len(nums) i=0 j=i+1 for el in nums: if(el%2==0): res[i]=el i+=2 else: res[j]=el j+=2 return res
sort-array-by-parity-ii
Easy python solution
liontech_123
0
7
sort array by parity ii
922
0.707
Easy
14,963
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/2659229/Python-Two-Pointers-O(N)-time-complexity-beats-98
class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: i=0 j=1 ans=[0]*len(nums) for k in range(len(nums)): if nums[k]%2==0: ans[i]=nums[k] i+=2 else: ans[j]=nums[k] j+=2 return ans
sort-array-by-parity-ii
Python - Two Pointers O(N) time complexity beats 98%
utsa_gupta
0
11
sort array by parity ii
922
0.707
Easy
14,964
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/2430914/Python3-Linear-Solution-with-Two-Pointers-O(n)
class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: #even to even index and odd to odd index means (even numbers == odd numbers) #Step bring even numbers to the left and odd to the right of the array or list l=0 r= len(nums)-1 while(l<r): if nums[l]%2 ==0 and nums[r]%2==0: l+=1 elif nums[l]%2 == 0 and nums[r]%2!=0: l+=1 r-=1 elif nums[l]%2!=0 and nums[r]%2 !=0: r-=1 elif nums[l]%2!=0 and nums[r]%2==0: nums[l],nums[r]=nums[r],nums[l] l+=1 r-=1 # Find out the index of First odd element of the array flag=0 for i in range(len(nums)): if nums[i]%2!=0: flag = i break # itrate i with odd index and flag by 1 if flag is odd then swap with nums[i] i=1 while(i<len(nums)): if nums[i]%2==0 and nums[flag]%2!=0: nums[i],nums[flag] = nums[flag], nums[i] i+=2 flag+=1 return nums
sort-array-by-parity-ii
Python3 Linear Solution with Two Pointers O(n)
aditya_maskar
0
12
sort array by parity ii
922
0.707
Easy
14,965
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/2217252/Easy-and-Simple-Approach-oror-Clean-Code
class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: i = 0 j = 1 temp = [-1]*len(nums) for num in nums: if num%2 == 0: temp[i] = num i += 2 else: temp[j] = num j += 2 return temp
sort-array-by-parity-ii
Easy and Simple Approach || Clean Code
Vaibhav7860
0
38
sort array by parity ii
922
0.707
Easy
14,966
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/2139771/Two-Solutions-Using-Pointers
# Solution - 2 class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: i, j = 0, 1 #[4, 2, 5, 7] # | | # i j while i < len(nums) and j < len(nums): if nums[i] % 2 == 0: i += 2 elif nums[j] % 2 != 0: j += 2 else: nums[i], nums[j] = nums[j], nums[i] i += 2 j += 2 return nums
sort-array-by-parity-ii
Two Solutions Using Pointers
yash921
0
20
sort array by parity ii
922
0.707
Easy
14,967
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/2076428/Python-in-place-explained-solution
class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: odd = 1 even = 0 while max(odd, even) < len(nums): # for the termination contition, if all odd numbers are in correct places, the even numbers must also have been correctly placed. # thus, when one of them are done, we can say with confidence that the other one is also done if nums[odd] % 2: odd += 2 else: # nums[odd] is even. needs to be swapped with an odd number. for i in range(odd + 1, len(nums), 2): # the step is 2 because we're swapping odd numbers with even index to this place. # this means we're correcting a misplaced odd number and a misplaced even number at the same time # if the step is 1, it is possible that we put the even number (nums[odd]) into an odd index, which would require at least one extra swap to fix. # The same principle applies to below. if nums[i] % 2: nums[odd], nums[i] = nums[i], nums[odd] odd += 2 break if nums[even] % 2 == 0: even += 2 else: for i in range(even + 1, len(nums), 2): if nums[i] % 2 == 0: nums[even], nums[i] = nums[i], nums[even] even += 2 break return nums
sort-array-by-parity-ii
Python in-place explained solution
Davidyz
0
16
sort array by parity ii
922
0.707
Easy
14,968
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/2047803/Python-one-liner
class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: return [item for sublist in zip([e for e in nums if not e%2],[o for o in nums if o%2]) for item in sublist]
sort-array-by-parity-ii
Python one-liner
ahmedyarub
0
37
sort array by parity ii
922
0.707
Easy
14,969
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/2004786/Python-3-Solution-Two-Pointers-O(1)-Space
class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: even, odd = 0, 1 while even < len(nums) and odd < len(nums): if nums[even] % 2 != 0 and nums[odd] % 2 == 0: nums[even], nums[odd] = nums[odd], nums[even] elif nums[even] % 2 == 0 and nums[odd] % 2 == 0: even += 2 elif nums[even] % 2 != 0 and nums[odd] % 2 != 0: odd += 2 else: even += 2 odd += 2 return nums
sort-array-by-parity-ii
Python 3 Solution, Two-Pointers, O(1) Space
AprDev2011
0
53
sort array by parity ii
922
0.707
Easy
14,970
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/1807712/1-Line-Python-Solution-oror-Not-very-Fast-oror-Memory-less-than-60
class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: return reduce(add, zip_longest([i for i in nums if i%2==0],[i for i in nums if i%2==1]))[:len(nums)]
sort-array-by-parity-ii
1-Line Python Solution || Not very Fast || Memory less than 60%
Taha-C
0
29
sort array by parity ii
922
0.707
Easy
14,971
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/1492563/Sort-Array-By-Parity-II-or-54-and-74-runtime-or-Easy-Understand-or-Python3
class Solution: def sortArrayByParityII(self, nums): evens = [x for x in nums if x%2 == 0] # if the number is even put in list odds = [x for x in nums if x%2 != 0] # if number is not even put in list arr = [] # extra list for i in range(len(evens)): # go through length of evens or odds because they are the same (nums.length is even) arr.append(evens[i]) # add the even first to the list arr.append(odds[i]) # and then the odd return arr # return the list
sort-array-by-parity-ii
Sort Array By Parity II | 54% and 74% runtime | Easy Understand | Python3
StarStalkX827
0
43
sort array by parity ii
922
0.707
Easy
14,972
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/1492563/Sort-Array-By-Parity-II-or-54-and-74-runtime-or-Easy-Understand-or-Python3
class Solution: def sortArrayByParityII(self, nums): evens = [x for x in nums if x%2 == 0] # same as above solution odds = [x for x in nums if x%2 != 0] # same as above solution count = 0 # what index to insert into nums for i in range(len(evens)): nums[count] = evens[i] # put the first even into the correct index nums[count+1] = odds[i] # put the first ODD into the correct index count += 2 # add two because I put count+1 for the odds because I don't want to put two count += 1's return nums # return the edited nums list
sort-array-by-parity-ii
Sort Array By Parity II | 54% and 74% runtime | Easy Understand | Python3
StarStalkX827
0
43
sort array by parity ii
922
0.707
Easy
14,973
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/1153934/Python-two-pointer-faster-than-97
class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: e=0 o=1 l=len(nums) while e<l and o<l: while e<l and o<l and nums[e]%2==0 : e+=2 while e<l and o<l and nums[o]%2==1: o+=2 if nums[o]%2==0 and nums[e]%2==1: nums[o],nums[e]=nums[e],nums[o] o+=2 e+=2 return nums
sort-array-by-parity-ii
Python two pointer faster than 97%
Anurag_Tiwari
0
150
sort array by parity ii
922
0.707
Easy
14,974
https://leetcode.com/problems/sort-array-by-parity-ii/discuss/952541/Python-and-Go-solutions-inplace-and-not
class Solution: def sortArrayByParityII(self, A: List[int]) -> List[int]: ev, od = 0, 1 sol = [0] * len(A) for el in A: if el % 2 == 0: sol[ev] = el ev += 2 else: sol[od] = el od += 2 return sol
sort-array-by-parity-ii
Python and Go solutions, inplace and not
modusV
-1
46
sort array by parity ii
922
0.707
Easy
14,975
https://leetcode.com/problems/3sum-with-multiplicity/discuss/1918718/Python-3Sum-Approach-with-Explanation
class Solution: def threeSumMulti(self, arr: List[int], target: int) -> int: arr.sort() # the rest of the code here
3sum-with-multiplicity
[Python] 3Sum Approach with Explanation
zayne-siew
89
5,500
3sum with multiplicity
923
0.454
Medium
14,976
https://leetcode.com/problems/3sum-with-multiplicity/discuss/1918718/Python-3Sum-Approach-with-Explanation
class Solution: def threeSumMulti(self, arr: List[int], target: int) -> int: arr.sort() for i in range(len(arr)-2): # do something pass # the rest of the code here
3sum-with-multiplicity
[Python] 3Sum Approach with Explanation
zayne-siew
89
5,500
3sum with multiplicity
923
0.454
Medium
14,977
https://leetcode.com/problems/3sum-with-multiplicity/discuss/1918718/Python-3Sum-Approach-with-Explanation
class Solution(object): def threeSumMulti(self, arr: List[int], target: int) -> int: arr.sort() res, l = 0, len(arr) for i in range(l-2): # Initialise the 2-sum pointers j, k = i+1, l-1 while j < k: if arr[j]+arr[k] < target-arr[i]: # arr[j] is too small j += 1 elif arr[j]+arr[k] > target-arr[i]: # arr[k] is too large k -= 1 else: # arr[i]+arr[j]+arr[k] == target res += 1 # Shift both pointers by 1 j += 1 k -= 1 return res%1000000007
3sum-with-multiplicity
[Python] 3Sum Approach with Explanation
zayne-siew
89
5,500
3sum with multiplicity
923
0.454
Medium
14,978
https://leetcode.com/problems/3sum-with-multiplicity/discuss/1918718/Python-3Sum-Approach-with-Explanation
class Solution: def threeSumMulti(self, arr: List[int], target: int) -> int: arr.sort() cnt = Counter(arr) # obtain the number of instances of each number res, i, l = 0, 0, len(arr) while i < l: # in replacement of the for-loop, so that we can increment i by more than 1 j, k = i, l-1 # j should be the leftmost index, hence j=i instead of j=i+1 while j < k: # i <= j < k; arr[i] <= arr[j] <= arr[k] if arr[i]+arr[j]+arr[k] < target: j += cnt[arr[j]] elif arr[i]+arr[j]+arr[k] > target: k -= cnt[arr[k]] else: # arr[i]+arr[j]+arr[k] == target if arr[i] != arr[j] != arr[k]: # Case 1: All the numbers are different res += cnt[arr[i]]*cnt[arr[j]]*cnt[arr[k]] elif arr[i] == arr[j] != arr[k]: # Case 2: The smaller two numbers are the same res += cnt[arr[i]]*(cnt[arr[i]]-1)*cnt[arr[k]]//2 # math.comb(cnt[arr[i]], 2)*cnt[arr[k]] elif arr[i] != arr[j] == arr[k]: # Case 3: The larger two numbers are the same res += cnt[arr[i]]*cnt[arr[j]]*(cnt[arr[j]]-1)//2 # math.comb(cnt[arr[j]], 2)*cnt[arr[i]] else: # Case 4: All the numbers are the same res += cnt[arr[i]]*(cnt[arr[i]]-1)*(cnt[arr[i]]-2)//6 # math.comb(cnt[arr[i]], 3) # Shift pointers by the number of instances of the number j += cnt[arr[j]] k -= cnt[arr[k]] i += cnt[arr[i]] # Shift pointer by the number of instances of the number return res%1000000007
3sum-with-multiplicity
[Python] 3Sum Approach with Explanation
zayne-siew
89
5,500
3sum with multiplicity
923
0.454
Medium
14,979
https://leetcode.com/problems/3sum-with-multiplicity/discuss/2032524/Python3-Solution-with-using-%223Sum-approach%22
class Solution: def threeSumMulti(self, arr: List[int], target: int) -> int: MOD = 10**9 + 7 res = 0 c = collections.Counter(arr) keys = sorted(c) for i, k in enumerate(keys): left, right = i, len(keys) - 1 new_target = target - k while left <= right: left_v, right_v = keys[left], keys[right] if left_v + right_v < new_target: left += 1 elif left_v + right_v > new_target: right -= 1 else: if i < left < right: res += c[k] * c[left_v] * c[right_v] elif i == left and left < right: res += c[k] * (c[k] - 1) // 2 * c[right_v] elif i < left and left == right: res += c[k] * c[left_v] * (c[left_v] - 1) // 2 else: res += c[k] * (c[k] - 1) * (c[k] - 2) // 6 left += 1 right -= 1 return res % MOD
3sum-with-multiplicity
[Python3] Solution with using "3Sum approach"
maosipov11
0
47
3sum with multiplicity
923
0.454
Medium
14,980
https://leetcode.com/problems/3sum-with-multiplicity/discuss/2007262/Easy-Python-or-High-Speed-or-O(N-%2B-unique2)-time-complexity
class Solution: def threeSumMulti(self, A, target): C = Counter(A) keys = sorted(C.keys()) MOD = 10**9 + 7 self.n = 0 def add(val): self.n = (self.n+val)%MOD nk = lambda n,k: factorial(n)//factorial(n-k)//factorial(k) for i,x in enumerate(keys): # check x x x if (3*x)>target: break elif C[x]>=3 and (3*x)==target: add(nk(C[x],3)) # check x x y y = target-2*x if not (x<y): break elif C[x]>=2 and (y in C): add(nk(C[x],2)*C[y]) for j in range(i+1,len(keys)): y = keys[j] # check x y y if (x+2*y)>target: break elif C[y]>=2 and (x+y*2)==target: add(C[x]*nk(C[y],2)) # check x y z z = target-x-y if not (y<z): break elif z in C: add(C[x]*C[y]*C[z]) return self.n
3sum-with-multiplicity
Easy Python | High Speed | O(N + unique^2) time complexity
Aragorn_
0
79
3sum with multiplicity
923
0.454
Medium
14,981
https://leetcode.com/problems/3sum-with-multiplicity/discuss/1923530/7-Lines-Python-Solution-oror-50-Faster
class Solution: def threeSumMulti(self, A: List[int], target: int) -> int: n=len(A) ; ans=0 ; C=Counter(A) ; S=set() for i,j in combinations_with_replacement(C,2): S.add(tuple(sorted([i,j,target-i-j]))) for i,j,k in S: x=1 for v,d in Counter([i,j,k]).items(): x*=comb(C[v],d) ans+=x return ans%1000000007
3sum-with-multiplicity
7-Lines Python Solution || 50% Faster
Taha-C
0
51
3sum with multiplicity
923
0.454
Medium
14,982
https://leetcode.com/problems/3sum-with-multiplicity/discuss/957765/Python3-freq-table-O(N2)
class Solution: def threeSumMulti(self, arr: List[int], target: int) -> int: ans = 0 seen = {} for i, x in enumerate(arr): ans += seen.get(target - x, 0) for ii in range(i): sm = arr[ii] + arr[i] seen[sm] = 1 + seen.get(sm, 0) return ans % 1_000_000_007
3sum-with-multiplicity
[Python3] freq table O(N^2)
ye15
0
168
3sum with multiplicity
923
0.454
Medium
14,983
https://leetcode.com/problems/3sum-with-multiplicity/discuss/957765/Python3-freq-table-O(N2)
class Solution: def threeSumMulti(self, arr: List[int], target: int) -> int: freq = {} for x in arr: freq[x] = 1 + freq.get(x, 0) ans = 0 vals = list(freq) for i in range(len(vals)): for ii in range(i+1): x = target - vals[i] - vals[ii] if x in freq: if vals[i] == vals[ii] == x: ans += comb(freq[x], 3) elif vals[i] == vals[ii] != x: ans += comb(freq[vals[i]], 2) * freq[x] elif vals[i] < x and vals[ii] < x: ans += freq[vals[i]] * freq[vals[ii]] * freq[x] return ans % 1_000_000_007
3sum-with-multiplicity
[Python3] freq table O(N^2)
ye15
0
168
3sum with multiplicity
923
0.454
Medium
14,984
https://leetcode.com/problems/minimize-malware-spread/discuss/1934636/Simple-Python-DFS-with-no-Hashmap
class Solution: def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int: initial = set(initial) def dfs(i): nodes.add(i) for j, conn in enumerate(graph[i]): if conn and j not in nodes: dfs(j) maxRemoval, minNode = -1, float('inf') for node in initial: nodes = set() dfs(node) if nodes &amp; initial == {node}: l = len(nodes) if l > maxRemoval or (l == maxRemoval and node < minNode): minNode = node maxRemoval = l return minNode if maxRemoval > -1 else min(initial)
minimize-malware-spread
Simple Python DFS with no Hashmap
totoslg
0
29
minimize malware spread
924
0.421
Hard
14,985
https://leetcode.com/problems/long-pressed-name/discuss/1343001/Python3-2-pointers
class Solution: def isLongPressedName(self, name: str, typed: str) -> bool: ni = 0 # index of name ti = 0 # index of typed while ni <= len(name) and ti < len(typed): if ni < len(name) and typed[ti] == name[ni]: ti += 1 ni += 1 elif typed[ti] == name[ni-1] and ni != 0: ti += 1 else: return False return ni == len(name) and ti == len(typed)
long-pressed-name
[Python3] 2 pointers
samirpaul1
6
521
long pressed name
925
0.337
Easy
14,986
https://leetcode.com/problems/long-pressed-name/discuss/1380410/28-ms-faster-than-87.66-of-Python3-online-submissions
class Solution: def isLongPressedName(self, name: str, typed: str) -> bool: n=len(name) m=len(typed) if m<n: return False i=j=0 while(True): print(i,j) if i==n and j==m: return True if i<n and j<m and name[i]==typed[j]: i+=1 j+=1 elif j>0 and j<m and typed[j-1]==typed[j]: j+=1 else: return False ```
long-pressed-name
28 ms, faster than 87.66% of Python3 online submissions
harshmalviya7
3
329
long pressed name
925
0.337
Easy
14,987
https://leetcode.com/problems/long-pressed-name/discuss/1944902/Python3-10-line-code-using-2-pointers
class Solution: def isLongPressedName(self, name: str, typed: str) -> bool: i, j, m, n = 0, 0, len(name), len(typed) if n < m: return False while i < m and j < n: if name[i] == typed[j]: i += 1 j += 1 elif j == 0 or typed[j] != typed[j - 1]: return False else: j += 1 return i == m and typed[j:] == typed[j - 1] * (n - j)
long-pressed-name
Python3 10-line code using 2-pointers
gulugulugulugulu
2
319
long pressed name
925
0.337
Easy
14,988
https://leetcode.com/problems/long-pressed-name/discuss/664415/Unexpectedly-long-answer.-Please-don't-judge-%3A)
class Solution: def isLongPressedName(self, name: str, typed: str) -> bool: if len(set(name)) == len(set(typed)): i,j = 0,0 while i < len(name): char = name[i] cnt_i = 1 while i+1 < len(name) and name[i] == name[i+1]: i += 1 cnt_i += 1 if j < len(typed) and char == typed[j]: cnt_j = 0 while j < len(typed): if char == typed[j]: j += 1 cnt_j += 1 else: break else: return False if cnt_i > cnt_j: return False i += 1 return True return False
long-pressed-name
Unexpectedly long answer. Please don't judge :)
realslimshady
1
128
long pressed name
925
0.337
Easy
14,989
https://leetcode.com/problems/long-pressed-name/discuss/664415/Unexpectedly-long-answer.-Please-don't-judge-%3A)
class Solution: def isLongPressedName(self, name: str, typed: str) -> bool: g1 = [(k, len(list(grp))) for k, grp in itertools.groupby(name)] g2 = [(k, len(list(grp))) for k, grp in itertools.groupby(typed)] if len(g1) != len(g2): return False for i in range(len(g1)): if g1[i][0] != g2[i][0] or g1[i][1] > g2[i][1]: return False return True
long-pressed-name
Unexpectedly long answer. Please don't judge :)
realslimshady
1
128
long pressed name
925
0.337
Easy
14,990
https://leetcode.com/problems/long-pressed-name/discuss/612813/Python-O(t)-by-two-pointers.-90-w-Comment
class Solution: def isLongPressedName(self, name: str, typed: str) -> bool: idx_src= 0 size_src, size_type = len(name), len(typed) for idx_type, char_type in enumerate(typed): if idx_src < size_src and name[idx_src] == char_type: # current type char is matched with friend's name char idx_src += 1 elif idx_type == 0 or typed[idx_type] != typed[idx_type-1]: # If first character mismatch, or it is not long-pressed repeated characters # Reject return False # Accept if all character is matched with friend name return idx_src == size_src
long-pressed-name
Python O(t) by two-pointers. 90% [w/ Comment]
brianchiang_tw
1
432
long pressed name
925
0.337
Easy
14,991
https://leetcode.com/problems/long-pressed-name/discuss/2830105/Python-Solution-Two-Pointers-Approach-oror-Explained-100
class Solution: def isLongPressedName(self, name: str, typed: str) -> bool: n=len(name) #length of name m=len(typed) #length of typed #if name is shorter than typed means keys arent enough pressed in typed to become equal to name if m<n: return False #if first elements are differnt means that first element in name is never be #pressed at first position of typed if name[0]!=typed[0]: return False #remaining code i=0 #index for name j=0 #index for typed #need to check if all chracters of name are present in typed #that's why only running loop till the name's length while i<n: if name[i]==typed[j]: #if characters found same i+=1 #move forward in name j+=1 #and move forward in typed else: #if characters not found same at those positions #check if name's previous element is long pressing in typed (i.e, #current element of typed equal to previous name's element) if typed[j]==name[i-1]: j+=1 #if above condition goes true, now move further in typed #otherwise it means the current charcter of typed is different #or not available in whole name string else: return False #if on moving the indeces of j , somehow reached to typed's end but names indeces are # still not fully traversed means name string is not present in typed in any condition if j==m and i!=n: return False #AFTER WHILE LOOP CHECK- #if name string completely traversed but typed isnt means we need to check remaining characters of typed if j!=m: while j<m: #traversing remainings #if last character of name is long pressed then all the remainings of typed #would be equal to names last character, but in case they arent equal (differnt # charcters found in typed) then return false if typed[j]!=name[n-1]: return False j+=1 #moving indeces of typed return True #if nothing goes wrong , return true
long-pressed-name
Python Solution - Two Pointers Approach || Explained 100%✔
T1n1_B0x1
0
4
long pressed name
925
0.337
Easy
14,992
https://leetcode.com/problems/long-pressed-name/discuss/2824912/Python-solution-with-comments
class Solution: def isLongPressedName(self, name: str, typed: str) -> bool: if len(typed) < len(name): return False name_pointer = 0 typed_pointer = 0 res = '' while name_pointer < len(name) and typed_pointer < len(typed): # if two characters are the same, then move the pointers one step if name[name_pointer] == typed[typed_pointer]: res += name[name_pointer] name_pointer += 1 typed_pointer += 1 # if they're not the same, check if it's a duplicate character that was lastly added to res #(make sure to check if res has at least one character). If not, return false elif name[name_pointer] != typed[typed_pointer]: # if it's a duplicate letter if len(res) > 0 and typed[typed_pointer] == res[-1]: typed_pointer += 1 else: return False # checking if there are any remining characters in typed that we didn't check # if the last characters are not the same, then return false if typed[-1] != name[-1]: return False if typed_pointer < len(typed) and typed[typed_pointer:] != res[-1] * len(typed[typed_pointer:]): return False return res == name
long-pressed-name
Python solution with comments
youssefyzahran
0
2
long pressed name
925
0.337
Easy
14,993
https://leetcode.com/problems/long-pressed-name/discuss/2819737/Python%3A-Two-Pointers
class Solution: def isLongPressedName(self, name: str, typed: str) -> bool: i,j=0,0 if name[0]!=typed[0]: return False if name[-1]!=typed[-1]: return False while i<len(name): if name[i]==typed[j]: i+=1 j+=1 else: if typed[j]==name[i-1]: j+=1 else: return False if j==len(typed) and i<len(name): return False if j!=len(typed): if typed[j]==name[-1]: j+=1 else: return False return True
long-pressed-name
Python: Two Pointers
utsa_gupta
0
4
long pressed name
925
0.337
Easy
14,994
https://leetcode.com/problems/long-pressed-name/discuss/2805045/Python-Solution
class Solution: def isLongPressedName(self, name: str, typed: str) -> bool: j = 0 name_len = len(name) if name[0] != typed[0]: return False for i in range(len(typed)): if j == 0 and name[j] == typed[i]: j = 1 elif j < name_len and name[j] == typed[i]: j += 1 elif j == name_len and typed[i] != name[name_len-1]: return False else: if j > 0 and name[j-1] == typed[i]: continue else: j = 0 if j == name_len: return True else: return False
long-pressed-name
Python Solution
asiffmahmudd
0
4
long pressed name
925
0.337
Easy
14,995
https://leetcode.com/problems/long-pressed-name/discuss/2554310/EASY-PYTHON3-SOLUTION-O)N)
class Solution: def isLongPressedName(self, name: str, typed: str) -> bool: for i in range(0, len(name)): counter = 0 for c in typed: if name[i] == c: counter += 1 typed = typed[1:] if name.find(name[i], i+1, i+2) != -1: break else: break if counter == 0: return False if typed: return False return True
long-pressed-name
✅✔🔥 EASY PYTHON3 SOLUTION 🔥✅✔ O)N)
rajukommula
0
94
long pressed name
925
0.337
Easy
14,996
https://leetcode.com/problems/long-pressed-name/discuss/2357332/Python-DP-(DFS-%2B-Memoization)
class Solution: def isLongPressedName(self, name: str, typed: str) -> bool: #dic for memoization dic = {} def dfs(i, j): if (i, j) in dic: return dic[(i, j)] #see if there is any case where both i and j reach to the end, cuz that will be the true condition #I only need one True if i >= len(name): return j == len(typed) #we iterated through the end of typed, and not yet for name if j >= len(typed): return False #if the characters don't match, return False if name[i] != typed[j]: dic[(i, j)] = False return False #if the two characters match #two options, either you move on (dfs(i + 1, j + 1)) or you consider it as an extra character (dfs(i, j + 1)) #return if any of them is True, which means that i, j reach to the end as aforementioned dic[(i, j)] = dfs(i + 1, j + 1) or dfs(i, j + 1) return dic[(i, j)] #start from index 0, 0 return dfs(0, 0)
long-pressed-name
Python DP (DFS + Memoization)
gypark23
0
77
long pressed name
925
0.337
Easy
14,997
https://leetcode.com/problems/long-pressed-name/discuss/1268980/Python3-solution-using-single-while-loop
class Solution: def isLongPressedName(self, name: str, typed: str) -> bool: if typed == name: return True n,t = len(name), len(typed) if t < n: return False i = j = 0 while True: if i < n and j < t: if name[i] == typed[j]: i += 1 j += 1 elif j > 0 and typed[j] == typed[j-1]: j += 1 else: return False elif j < t: if typed[j] == typed[j-1]: j += 1 else: return False elif i < n: return False else: return True
long-pressed-name
Python3 solution using single while loop
EklavyaJoshi
0
68
long pressed name
925
0.337
Easy
14,998
https://leetcode.com/problems/long-pressed-name/discuss/1156884/Python-wcomments-include-new-cases
class Solution: def isLongPressedName(self, name: str, typed: str) -> bool: # count chars in name tmp = 0 for index, value in enumerate(typed): # if current not equal name[tmp] or name[tmp-1] then it is not long pressed if value not in {name[tmp], name[tmp-1 if tmp-1 > 0 else 0]}: return False if value == name[tmp]: tmp += 1 # stop iterate if we found all chars from name if tmp >= len(name): # check if remaining symbols all equal to name[-1] st = set(typed[index:]) return len(st) == 1 and st.pop() == name[-1] return False
long-pressed-name
[Python] w/comments include new cases
cruim
0
125
long pressed name
925
0.337
Easy
14,999