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-length-of-a-concatenated-string-with-unique-characters/discuss/2740185/Brute-force-using-recursion | class Solution:
def maxLength(self, arr: List[str]) -> int:
def step(i, set_state):
if i == n:
return 0
#if adding i-th element is valid add it and check if it increases the length
s = set(arr[i])
if not set_state & s:
return max(step(i + 1, set_state), len(arr[i]) + step(i + 1, set_state | s))
return step(i + 1, set_state)
arr = [a for a in arr if len(a) == len(set(a)) ]
n = len(arr)
return step(0, set()) | maximum-length-of-a-concatenated-string-with-unique-characters | Brute force using recursion | nonchalant-enthusiast | 0 | 4 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,600 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2740121/Brute-forcing-while-keeping-an-array-of-unique-sets | class Solution:
def maxLength(self, arr: List[str]) -> int:
n = len(arr)
max_len = 0
dp = [set()]
max_len = 0
for a in arr:
s = set(a)
if len(a) > len(s):
continue
for d in dp[:]:
if not d & s:
dp.append(d | s)
return(max(map(len, dp))) | maximum-length-of-a-concatenated-string-with-unique-characters | Brute forcing, while keeping an array of unique sets | nonchalant-enthusiast | 0 | 4 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,601 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2739943/Python-3-Backtracking-beats-98-runtime | class Solution:
def maxLength(self, arr: List[str]) -> int:
# Beats 98.37% runtime
# Beats 43.86% space
if len(arr) <= 1:
if len(arr) == 0 or len(arr[0]) != len(set(arr[0])):
return 0
return len(arr[0])
best = 0
def explore(curr, candidates):
nonlocal best
if (L := len(curr)) == len(set(curr)):
if L > best:
best = L
if len(candidates) > 0:
explore(curr + candidates[0], candidates[1:])
explore(curr, candidates[1:])
for idx,val in enumerate(arr):
if len(val) + sum([len(a) for a in arr[idx+1:]]) < best:
break
explore(val, arr[idx+1:])
return best | maximum-length-of-a-concatenated-string-with-unique-characters | Python 3 Backtracking, beats 98% runtime | karamartin | 0 | 10 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,602 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2739763/Easy-iterative-Python-solution | class Solution:
def maxLength(self, arr: List[str]) -> int:
cur = []
res = 0
for w in arr:
if len(w) > 26:
continue
if len(w) > len(set(w)):
continue
l = len(cur)
for i in range(l):
pre = cur[i]
tmp = pre+w
if len(tmp) == len(set(tmp)):
cur.append(tmp)
res = max(res, len(tmp))
cur.append(w)
res = max(res, len(w))
return res | maximum-length-of-a-concatenated-string-with-unique-characters | Easy iterative Python solution | MrsMeow | 0 | 7 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,603 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2739664/The-best-easy-fast-solution-Python3 | class Solution:
def maxLength(self, arr: List[str]) -> int:
a, maxl =[''], 0
for string in arr:
for word in a:
res = word + string
if len(res) != len(set(res)):
continue
a.append(res)
maxl = max(maxl, len(res))
return maxl | maximum-length-of-a-concatenated-string-with-unique-characters | The best easy fast solution Python3 | genaral-kg | 0 | 9 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,604 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2739561/Simple-Python3-solution-(DFS-backtracking) | class Solution:
def maxLength(self, arr: List[str]) -> int:
def dfs(path, start):
# check for destination
if len(path) != len(set(path)): # duplicate characters
return
self.ans = max(self.ans, len(path))
# make choices
for i in range(start, len(arr)):
dfs(path + arr[i], i + 1)
if not arr: return 0
self.ans = 0
dfs("", 0)
return self.ans | maximum-length-of-a-concatenated-string-with-unique-characters | Simple Python3 solution (DFS backtracking) | cutesunny | 0 | 6 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,605 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2739352/Pytohn3!-8-Lines-solution. | class Solution:
def maxLength(self, arr: List[str]) -> int:
arrayOr = lambda lst: reduce(lambda x,y: x|y, [a for a in lst], 0)
isValid = lambda lst: arrayOr(lst) == sum(lst)
charToBits = lambda x: (1<<(ord(x) - ord('a')))
arr = [[charToBits(c) for c in word] for word in arr]
arr = [arrayOr(bits) for bits in arr if isValid(bits)]
subArr = lambda x, bits: [xi for i, xi in enumerate(x) if (bits >> i) & 1]
subs = [subArr(arr, bits) for bits in range(1 << len(arr))]
sumBits = lambda x: sum([(x >> i) & 1 for i in range(26)])
return max([sumBits(sum(sub)) for sub in subs if isValid(sub)]) | maximum-length-of-a-concatenated-string-with-unique-characters | 😎Pytohn3! 8 Lines solution. | aminjun | 0 | 24 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,606 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2739280/Python-solution-using-backtrack-and-bit-manipulation | class Solution:
def maxLength(self, arr: List[str]) -> int:
ans = 0
def dfs(i, bitmask, length):
nonlocal ans
ans = max(ans, length)
if i == len(arr):
return
# cache for backtrack
prev_bitmask = bitmask
for ch in arr[i]:
if 1 << (ord(ch)-ord('a')) & bitmask != 0:
# duplicates if we add arr[i]
dfs(i+1, prev_bitmask, length)
return
bitmask |= 1<<(ord(ch)-ord('a'))
# either add arr[i] to subsequence
dfs(i+1, prev_bitmask, length)
# or skip arr[i]
dfs(i+1, bitmask, length+len(arr[i]))
return
dfs(0, 0, 0)
return ans | maximum-length-of-a-concatenated-string-with-unique-characters | Python solution using backtrack and bit manipulation | f2154 | 0 | 17 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,607 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2738742/Python-oror-13-lines-faster-than-99-oror-DP-oror-Dailly-Challenge | class Solution:
def maxLength(self, arr: List[str]) -> int:
a = {0}
f = {0: 0}
for word in arr:
if len(word) != len(Counter(word)):
continue
w = sum([1 << (ord(ch) - ord('a')) for ch in word])
a1 = set()
for k in a:
k1 = k + w
if (k | w) == k1:
a1.add(k1)
f[k1] = f[k] + len(word)
a = a.union(a1)
return max(f.values()) | maximum-length-of-a-concatenated-string-with-unique-characters | Python || 13 lines faster than 99% || DP || Dailly Challenge | syb3181 | 0 | 16 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,608 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2738693/Python-faster-than-90.56-explained | class Solution:
def maxLength(self, arr: List[str]) -> int:
# Break down the problem as max unique characters from given set + an array and reduce it recursively
def getMax(trailSet, arrIndex):
maxl = len(trailSet)
for i in range(arrIndex, len(arr)):
s = arr[i]
setofs = set(s)
#if string has any duplicate chars, then continue
if len(setofs) != len(s): continue
#if string has any chars that are duplicate with initialset, then continue
if len(setofs.intersection(trailSet)) != 0: continue
maxl = max(maxl, getMax(trailSet.union(setofs), i+1))
return maxl
#Start with empty set and full array
return getMax(set(),0) | maximum-length-of-a-concatenated-string-with-unique-characters | Python faster than 90.56% explained | pradyumna04 | 0 | 20 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,609 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2738555/Python-or-Backtracking-solution | class Solution:
def maxLength(self, arr: List[str]) -> int:
maxLen = 0
def helper(i, seen):
nonlocal maxLen
string = ''.join(seen)
if len(string) > len(set(string)):
return
if len(string) == len(set(string)):
maxLen = max(maxLen, len(string))
for j in range(i, len(arr)):
if len(arr[j]) == len(set(arr[j])):
seen.append(arr[j])
helper(j + 1, seen)
seen.pop()
helper(0, [])
return maxLen | maximum-length-of-a-concatenated-string-with-unique-characters | Python | Backtracking solution | KevinJM17 | 0 | 9 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,610 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2738464/Python-or-Backtracking | class Solution:
def maxLength(self, arr: List[str]) -> int:
best = [0]
def backtrack(i, s):
if i == len(arr):
return
if len(arr[i] + s) == len(set(arr[i] + s)):
s += arr[i]
backtrack(i+1, s)
best[0] = max(best[0], len(s))
s = s[:-len(arr[i])]
backtrack(i+1, s)
backtrack(0, "")
return best[0] | maximum-length-of-a-concatenated-string-with-unique-characters | Python | Backtracking | synapsecredit | 0 | 7 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,611 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2738432/Python-easy-recursion-solution.-112-ms-faster-than-86 | class Solution:
def maxLength(self, arr: List[str]) -> int:
answers = []
def dfs(prefix, index):
if index == len(arr):
# push to list our prefix's length (It has unique chars, see below)
answers.append(len(prefix))
return
# If we have not any intersactions of new string with existing prefix
# and new string has not any repetions of its letters,
# we will consider this as one of the solutions.
if not set(prefix) & set(arr[index]) and len(set(arr[index])) == len(arr[index]):
dfs(prefix + arr[index], index + 1)
dfs(prefix, index + 1) # add nothing and move
return
dfs("", 0)
return max(answers) | maximum-length-of-a-concatenated-string-with-unique-characters | Python easy recursion solution. 112 ms, faster than 86% | milsolve | 0 | 23 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,612 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2738390/Easy-to-Understand-DP-Solution-or-Python-3 | class Solution:
def maxLength(self, arr: List[str]) -> int:
dp={}
def func(i,a):
if i==len(arr):
sz=len(a)
if len(set(a)) < sz: return 0
return sz
if (i,a) in dp: return dp[(i,a)]
#Not pick
u=func(i+1,a)
#Pick
v=func(i+1, a+arr[i])
dp[(i,a)]=max(u,v)
return dp[(i,a)]
return func(0,'') | maximum-length-of-a-concatenated-string-with-unique-characters | Easy to Understand DP Solution | Python 3 | Mohit_Hadiyal16 | 0 | 21 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,613 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2738346/Python-Brute-Force-BFS-approach | class Solution:
def maxLength(self, arr: List[str]) -> int:
#brute force
n = len(arr)
chars = [set(e) for e in arr]
valid = [False for _ in range(n)]
maxl = 0
q = deque()
for i in range(n):
e = arr[i]
seen = set()
found = True
for c in e:
if c not in seen:
seen.add(c)
else:
found = False
break
if found:
q.append((i,seen,len(arr[i])))
valid[i] = True
#do bfs
while q:
j,node,l = q.popleft()
maxl = max(maxl,l)
for k in range(j+1,n):
if valid[k] and not chars[k]&node:
q.append((k,chars[k]|node,l+len(arr[k])))
return maxl | maximum-length-of-a-concatenated-string-with-unique-characters | Python Brute Force BFS approach | user9611y | 0 | 6 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,614 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2738285/Recursive-without-bit-manipulation | class Solution:
def maxLength(self, arr: List[str]) -> int:
set_info = []
for s in arr:
cur_set = set(s)
if len(s) != len(set(s)):
set_info.append((-1,cur_set))
else:
set_info.append((len(s),cur_set))
def dfs(i,cur_set):
if i < 0:
return 0
cur_word = arr[i]
take,not_take = 0,0
if set_info[i][0] != -1:
expected_length = len(cur_set) + set_info[i][0]
new_set = cur_set|set_info[i][1]
if len(new_set) == expected_length:
take = len(cur_word) + dfs(i-1,new_set)
not_take = dfs(i-1,cur_set)
return max(take,not_take)
return dfs(len(arr) - 1,set()) | maximum-length-of-a-concatenated-string-with-unique-characters | Recursive without bit manipulation | shriyansnaik | 0 | 4 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,615 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2738237/Set-approach-in-python | class Solution:
def maxLength(self, arr: List[str]) -> int:
if not arr:return 0
setl = [""]
clen = 0
for word in arr:
for setword in setl:
temp = setword+word
if len(temp) != len(set(temp)):continue
setl.append(temp)
#print(setl)
clen = max(clen,len(temp))
return(clen) | maximum-length-of-a-concatenated-string-with-unique-characters | Set approach in python | tkrishnakumar30 | 0 | 7 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,616 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2738228/clean-codeing-to-easy-understanding-with-good-runtime | class Solution:
def maxLength(self, arr: List[str]) -> int:
uniqELements = ['']
maximum = 0
for i in range(len(arr)):
sz = len(uniqELements)
for j in range(sz):
x=arr[i]+uniqELements[j]
if (len(x)==len(set(x))):
uniqELements.append(x)
maximum = max(maximum,len(x))
#print(uniqELements)
return maximum | maximum-length-of-a-concatenated-string-with-unique-characters | clean codeing to easy understanding with good runtime | V_Bhavani_Prasad | 0 | 9 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,617 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2738181/Fast-and-Easy-Python-Solution | class Solution:
# Backtracking Siple python solution
def maxLength(self, arr: List[str]) -> int:
res = -sys.maxsize
def helper(curr, i):
nonlocal res
res = max(res, len(curr))
if i == len(arr):
return
for j in range(i + 1, len(arr)):
if any(c in curr for c in arr[j]) or len(arr[j]) != len(set(arr[j])): continue
helper(curr + arr[j], j)
helper('', -1)
return res | maximum-length-of-a-concatenated-string-with-unique-characters | Fast and Easy Python Solution | shiv-codes | 0 | 24 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,618 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2738138/Python-or-Backtracking-recursion-with-memoization | class Solution:
ans = 0
used = set()
stack = []
def maxLength(self, arr: List[str]) -> int:
@cache
def rec(carry):
self.ans = max(self.ans, len(carry))
for s in arr:
q = set(t for t in s)
if not q & self.used and (len(s) == len(q)):
self.stack.append(s)
self.used |= q
rec("".join(k for k in sorted(self.stack, key = lambda x: x[0])))
self.stack.pop()
self.used -= q
return len(carry)
rec("")
return self.ans | maximum-length-of-a-concatenated-string-with-unique-characters | Python | Backtracking recursion with memoization | LordVader1 | 0 | 24 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,619 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2738118/python-using-backtracking-easy | class Solution:
def maxLength(self, arr: List[str]) -> int:
charset=set()
def overlap(charset,s):
c=Counter(charset)+Counter(s)
return max(c.values())>1
def backtrack(i):
if(i==len(arr)):
return len(charset)
res=0
if not overlap(charset,arr[i]):
for c in arr[i]:
charset.add(c)
res=backtrack(i+1)
for c in arr[i]:
charset.remove(c)
return max(res,backtrack(i+1))
return backtrack(0) | maximum-length-of-a-concatenated-string-with-unique-characters | python using backtracking easy | Raghunath_Reddy | 0 | 7 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,620 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2738062/Python3-solution...-Help-me-to-reduce-the-time | class Solution:
def maxLength(self, arr: List[str]) -> int:
n = len(arr)
ans = 0
for mask in range(1 << n):
seen = set()
isValid = True
strSize = 0
for i in range(n):
if (mask >> i) & 1 == 0: continue
for c in arr[i]:
if c in seen: # If c is already existed then it's invalid subsequence.
isValid = False
break
seen.add(c) # mark as character `c` is already seen
strSize += 1
if not isValid: break # prune when there is a duplicate
if isValid and strSize > ans:
ans = strSize
return ans | maximum-length-of-a-concatenated-string-with-unique-characters | Python3 solution... Help me to reduce the time | rupamkarmakarcr7 | 0 | 4 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,621 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2738060/Python-Solution-With-DP | class Solution:
def maxLength(self, arr: List[str]) -> int:
dp = {}
def f(s,i):
if i == 0:
if len(set(s + arr[i])) == len(arr[i] + s):
return len(s + arr[i])
else:
if len(arr[i]) == len(set(arr[i])):
return max(len(s),len(arr[i]))
else:
return len(s)
sr = s + arr[i]
if dp.get(sr) != None:
return dp[sr]
take = float("-inf")
if len(set(sr)) == len(sr):
take = f(s + arr[i],i - 1)
not_take = f(s,i - 1)
else:
not_take = f(s,i - 1)
dp[sr] = max(take,not_take)
return dp[sr]
return f("", len(arr) - 1) | maximum-length-of-a-concatenated-string-with-unique-characters | Python Solution With DP | a_dityamishra | 0 | 9 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,622 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2738035/Python-Bitmask | class Solution:
def maxLength(self, arr: List[str]) -> int:
bitarr = []
arrsize = []
for word in arr:
bitmask = 0
for v in word:
if bitmask & 1<< (ord(v)-ord("a")):
bitmask = 0
word = ""
break
bitmask += 1<< (ord(v)-ord("a"))
bitarr.append(bitmask)
arrsize.append(len(word))
n = len(arr)
def dfs(mask,idx):
if idx == n:
return 0
if mask & bitarr[idx]:
return dfs(mask,idx+1)
else:
return max(dfs(mask,idx+1), arrsize[idx] + dfs(mask|bitarr[idx],idx+1))
return dfs(0,0) | maximum-length-of-a-concatenated-string-with-unique-characters | Python Bitmask | Akhil_krish_na | 0 | 6 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,623 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2738010/Python-Solution-or-Recursion-or-DP | class Solution:
def maxLength(self, arr: List[str]) -> int:
n=len(arr)
def helper(ind, prev):
if ind==n:
return 0
notTake=helper(ind+1, prev)
take=0
count=Counter(arr[ind]+prev)
# print(count)
flag=True
temp=''
for key, value in count.items():
temp+=key
if value>1:
flag=False
break
if flag:
take=max(len(count), helper(ind+1, temp))
# print(take)
ans=max(take, notTake)
return ans
return helper(0, '') | maximum-length-of-a-concatenated-string-with-unique-characters | Python Solution ✅ | Recursion | DP ❌ | Siddharth_singh | 0 | 13 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,624 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2737874/Python-solution-or-backtrack | class Solution:
def maxLength(self, arr: List[str]) -> int:
def backtrack(nums, path):
if not nums:
return len(path)
temp = path + nums[0]
if len(temp) > len(set(temp)):
return backtrack(nums[1:], path)
return max(backtrack(nums[1:], path + nums[0]), backtrack(nums[1:], path))
return backtrack(arr,"") | maximum-length-of-a-concatenated-string-with-unique-characters | Python solution | backtrack | maomao1010 | 0 | 10 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,625 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2737862/Recursion-Solution-or-Easy-to-understand-or-Backtracking | class Solution:
def maxLength(self, arr: List[str]) -> int:
max_el=0
n=len(arr)
def recursion(el_pair,ind):
nonlocal max_el
max_el=max(max_el,len(el_pair))
for j in range(ind+1,n):
if len(el_pair+arr[j])==len(set(el_pair+arr[j])):
recursion(el_pair+arr[j],j)
for i in range(n):
if len(arr[i])==len(set(arr[i])):
recursion(arr[i],i)
return max_el | maximum-length-of-a-concatenated-string-with-unique-characters | Recursion Solution | Easy to understand | Backtracking | ankush_A2U8C | 0 | 9 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,626 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2737646/Understandable-code | class Solution:
def maxLength(self, arr: List[str]) -> int:
s=""
res=0
def check(a):
for i in a:
if a.count(i)>1 :
return False
return True
def valid(a,s):
for i in a:
if i in s:
return False
return True
def fun(i,s,res):
if i==len(arr):
return 0
# -1:
# if check(arr[i])==True and valid(s,arr[i])==True:
# return len(arr[i])
p=0
if check(arr[i])==True and valid(s,arr[i])==True:
p=len(arr[i])+fun(i+1,s+arr[i],res+len(arr[i]))
np=0+fun(i+1,s,res)
return max(p,np)
return fun(0,s,res) | maximum-length-of-a-concatenated-string-with-unique-characters | Understandable code | hemanth_12 | 0 | 22 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,627 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2737586/Python-backtracking-simple-solution | class Solution:
def max_len(self,arr,ans,S,n):
# print(S,ans,len(S),len(set(S)),n)
if(n>=len(arr)):
if(len(S)==len(set(S))):
ans[0] = max(ans[0],len(S))
return ans[0]
else:
return 0
if(len(S)==len(set(S))):
ans[0] = max(ans[0],len(S))
self.max_len(arr,ans,S,n+1)
S += arr[n]
self.max_len(arr,ans,S,n+1)
return ans[0]
def maxLength(self, arr: List[str]) -> int:
ans = [0]
S = ""
n = 0
return self.max_len(arr,ans,S,n) | maximum-length-of-a-concatenated-string-with-unique-characters | Python backtracking simple solution | Jayu79 | 0 | 25 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,628 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2737566/Python3-Bitmask-Brute-Force | class Solution:
def maxLength(self, arr: List[str]) -> int:
an = ord('a')
d = {}
for i in range(ord('a'), ord('z') + 1):
d[chr(i)] = 1<<(i-an)
ops = [0]
ch = []
for str in arr:
v = 0
for c in str:
if (v&d[c]):
v = 0
break
v|=d[c]
if v > 0:
ch.append(v)
for v in ch:
for i in range(len(ops)):
if 0 == (ops[i] & v):
ops.append(ops[i] | v)
def bc(v):
c = 0
while v:
c+=(v&1)
v>>=1
return c
return max(map(bc, ops)) | maximum-length-of-a-concatenated-string-with-unique-characters | Python3 Bitmask Brute Force | godshiva | 0 | 9 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,629 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2718120/Python3-Simple-bitmasking-%2B-backtracking | class Solution:
def maxLength(self, arr: List[str]) -> int:
# We use bitmasking to mark the attendence of a char
def masking(s):
mask = 0
for i in s:
pos = 1 << (ord(i)-ord('a'))
# If we see the same character in a string,
# we make it as -1(unusable)
if mask & pos != 0: return -1
mask |= pos
return mask
# Get all the masking
masked = [masking(s) for s in arr]
n = len(arr)
# Use dfs to check the optimal answer
# because we might take the curr one or take the next one
# Since we don't have an optimal way to find,
# we just find all the possible answers
@lru_cache(None)
def dfs(mask, curr):
if curr == n: return 0
res = 0
for i in range(curr, n):
# If both string have same character(s)
# or the string is unusable
if mask & masked[i] != 0 or masked[i] == -1: continue
# We want to find the maximum length
# so len(arr[i]) + dfs(...)
res = max(res, len(arr[i]) + dfs(mask | masked[i], i+1))
return res
return dfs(0, 0) | maximum-length-of-a-concatenated-string-with-unique-characters | Python3 Simple bitmasking + backtracking | rjnkokre | 0 | 20 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,630 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2345323/PYTHON-or-BACKTRACKING-or-EXPLAINED-or-EASY-or-FAST-or | class Solution:
def maxLength(self, arr: List[str]) -> int:
ans = 0
count = [0]*26
counts = []
new_arr = []
for string in arr:
flag = True
tmp = [0]*26
for ch in string:
if tmp[ord(ch) - 97] == True:
flag = False
break
else:
tmp[ord(ch) - 97] = True
if flag == False:continue
counts.append(tmp)
new_arr.append(string)
n = len(new_arr)
def compatible(a,b):
for i in range(26):
if a[i] == True and b[i] == True: return False
return True
def addUp(a,b):
for i in range(26):
if b[i] == True: a[i] = True
def solve(index,count):
if index == n:return 0
cpy = count.copy()
ch1 = -inf
if compatible(count,counts[index]):
addUp(count,counts[index])
ch1 = solve(index+1,count) + len(new_arr[index])
ch2 = solve(index+1 , cpy)
ans = max(ch1,ch2)
return ans
return solve(0,count) | maximum-length-of-a-concatenated-string-with-unique-characters | PYTHON | BACKTRACKING | EXPLAINED | EASY | FAST | | reaper_27 | 0 | 112 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,631 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2268625/1-Set-solution-python-recursion | class Solution:
def maxLength(self, arr: List[str]) -> int:
mxLen = 0
track = set()
def helper(i, tmp):
nonlocal mxLen
if i == len(arr):
mxLen = max(mxLen, len(tmp))
return
# non-skip
canPick = True
# if cur element has duplicate
for chars in arr[i]:
if chars in track:
canPick = False
track.add(chars)
track.clear()
if canPick:
# if the cur element has a char which also exists in tmp
for chars in tmp:
track.add(chars)
for chars in arr[i]:
if chars in track:
canPick = False
break
track.clear()
if canPick:
helper(i+1, tmp + arr[i])
#skip
helper(i+1, tmp)
helper(0, "")
return mxLen | maximum-length-of-a-concatenated-string-with-unique-characters | 1 Set solution python recursion | DigantaC | 0 | 123 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,632 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/1693294/Python-easy-simple-dfsbacktracking-solution | class Solution:
def maxLength(self, arr: List[str]) -> int:
def uni(s):
count = defaultdict(int)
for c in s:
count[c] += 1
if count[c] > 1:
return False
return True
arr = [x for x in arr if uni(x)]
n = len(arr)
if n == 0:
return 0
stack = []
for i in range(n):
x = [s for s in arr[i]]
stack.append((set(x), [i]))
def unique(s, ch):
for c in ch:
if c in s:
return False
return True
maxlen = 0
while stack:
charset, index = stack.pop()
maxlen = max(maxlen, len(charset))
k = index[-1] + 1
for i in range(k, n):
if unique(charset, arr[i]):
cha = set([x for x in arr[i]])
stack.append((charset | cha, index + [i]))
return maxlen | maximum-length-of-a-concatenated-string-with-unique-characters | Python easy, simple dfs/backtracking solution | byuns9334 | 0 | 200 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,633 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/1499802/Python-Clean-Backtracking | class Solution:
def maxLength(self, arr: List[str]) -> int:
def unique(strg, vis):
s = set(strg)
if len(s) < len(strg):
return False
for c in s:
if c in vis:
return False
return True
def backtrack(i= 0):
nonlocal N, maxm
for j in range(i, N):
if unique(arr[j], vis):
for c in arr[j]:
vis.add(c)
maxm = max(len(vis), maxm)
backtrack(j)
for c in arr[j]:
vis.remove(c)
N, maxm = len(arr), 0
vis = set()
backtrack()
return maxm | maximum-length-of-a-concatenated-string-with-unique-characters | [Python] Clean Backtracking | soma28 | 0 | 297 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,634 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/1435610/Simple-Python-DFS-%2B-set-%2B-prefix-size-%2B-pruning-or-Beat-95-with-explanation | class Solution:
def maxLength(self, arr: List[str]) -> int:
max_length = float('-inf')
# use prefix_size to check if the remaining array can produce possible larger unique string
prefix_size = [0] * len(arr)
prefix_size[-1] = len(set(list(arr[-1])))
for i in range(len(arr)-2, -1, -1):
prefix_size[i] = len(set(list(arr[i]))) + prefix_size[i+1]
# print(prefix_size)
def backtrack(arr, string, index=0):
nonlocal max_length
# before we go deeper backtrack,
# we check if the remaining array can produce possible larger unique string,
# if current string, presumbly unique, plus the remaining possible unique string has length smaller than current maximum length,
# then we don't need to go deeper, just return.
if index < len(prefix_size) and len(string) + prefix_size[index] < max_length:
return
if len(string) > max_length and len(string) > 0:
max_length = len(string)
if index == len(arr):
return
for i in range(index, len(arr)):
set1 = set(string)
set2 = set(list(arr[i]))
union = set1.union(set2)
# must check if the union set size is equal to the array size sum so to make sure they are all unique
if len(union) == len(string) + len(arr[i]):
for c in set2:
string.append(c)
backtrack(arr, string, i + 1)
for c in range(len(arr[i])):
string.pop()
return
backtrack(arr, [], 0)
return max_length if max_length != float('-inf') else 0 | maximum-length-of-a-concatenated-string-with-unique-characters | Simple Python DFS + set + prefix size + pruning | Beat 95% with explanation | jiongnanliu | 0 | 125 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,635 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/1316139/DP-Memo-Solution | class Solution:
def maxLength(self, arr: List[str]) -> int:
def createSubseq(arr,memo,i=0,used=0):
#either pick i or leave it return max of both
if i >= len(arr):return 0
if (i,used) in memo: return memo[(i,used)]
temp = used
res = createSubseq(arr,memo,i+1,used)
#since there are onlty 26 chars we can use integer bits to store used values
for ch in arr[i]:
key = 1<<(ord(ch)-ord('a'))
if temp & key != 0:break
temp |= key
else:
res = max(res,len(arr[i])+createSubseq(arr,memo,i+1,temp))
memo[(i,used)]=res
return res
memo = dict()
return createSubseq(arr,memo) | maximum-length-of-a-concatenated-string-with-unique-characters | DP Memo Solution | necilAlbayrak | 0 | 298 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,636 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/1180393/99.95-faster-and-efficient-Python-code | class Solution:
def maxLength(self, arr: List[str]) -> int:
l=len(arr)
max=0
l2=[]
v=1
while(v<27):
for u in range(0,l):
if(len(arr[u])==v):
l2.append(arr[u])
v=v+1
for i in range(0,l):
c=0
k=0
s=set()
while(k<len(l2[i])):
if(l2[i][k] in s):
break
else:
s.add(l2[i][k])
k=k+1
if(k==len(l2[i])):
c=c+k
for j in range(0,l):
k=0
while(k<len(l2[j])):
if(l2[j][k] in s):
break
else:
s.add(l2[j][k])
k=k+1
if(k==len(l2[j])):
c=c+k
if(c>max):
max=c
l2.reverse()
for i in range(0,l):
c=0
k=0
s=set()
while(k<len(l2[i])):
if(l2[i][k] in s):
break
else:
s.add(l2[i][k])
k=k+1
if(k==len(l2[i])):
c=c+k
for j in range(0,l):
k=0
while(k<len(l2[j])):
if(l2[j][k] in s):
break
else:
s.add(l2[j][k])
k=k+1
if(k==len(l2[j])):
c=c+k
if(c>max):
max=c
return max | maximum-length-of-a-concatenated-string-with-unique-characters | 99.95% faster and efficient Python code | Rajashekar_Booreddy | 0 | 424 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,637 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/1144354/Python-O(N)-Space-solution | class Solution:
# 84 ms, 92.06%. Time: O(2^N). Space: O(N)
def maxLength(self, arr: List[str]) -> int:
chars = [set(s) for s in arr if len(s) == len(set(s))]
def dfs(i=0, seen=set()):
if i == len(chars): return len(seen)
skip = dfs(i + 1, seen)
if seen & chars[i]: return skip
take = dfs(i + 1, seen | chars[i])
return max(skip, take)
return dfs() if chars else 0 | maximum-length-of-a-concatenated-string-with-unique-characters | [Python] O(N) Space solution | JummyEgg | 0 | 301 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,638 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/1133846/BackTracking-or-Python-3 | class Solution:
def maxLength(self, arr: List[str]) -> int:
if len(arr) == 1:
if len(arr[0]) == len(set(arr[0])):
return len(arr[0])
return 0
self.max = 0
def helper(size, pos, curr):
if len(curr) == size:
temp = ''.join(curr)
if len(temp) == len(set(temp)):
self.max = max(self.max, len(temp))
return
for i in range(pos, len(arr)):
curr.append(arr[i])
helper(size, i + 1, curr)
curr.pop()
for i in range(1, len(arr) + 1):
helper(i, 0, [])
return self.max | maximum-length-of-a-concatenated-string-with-unique-characters | BackTracking | Python 3 | abhyasa | 0 | 234 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,639 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/1092327/Python3-backtracking | class Solution:
def maxLength(self, arr: List[str]) -> int:
ans = [""]
for x in arr:
for i in range(len(ans)):
xx = x + ans[i]
if len(xx) == len(set(xx)): ans.append(xx)
return max(len(x) for x in ans) | maximum-length-of-a-concatenated-string-with-unique-characters | [Python3] backtracking | ye15 | 0 | 254 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,640 |
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/1092327/Python3-backtracking | class Solution:
def maxLength(self, arr: List[str]) -> int:
ans = 0
freq = [0]*26
def fn(i):
"""Return max length of arr[i:] given freq."""
if i == len(arr): return 0
ans = fn(i+1) # skipping arr[i]
if len(set(arr[i])) == len(arr[i]):
if all(freq[ord(c)-97] == 0 for c in arr[i]):
for c in arr[i]: freq[ord(c)-97] += 1
ans = max(ans, len(arr[i]) + fn(i+1))
for c in arr[i]: freq[ord(c)-97] -= 1 # backtracking
return ans
return fn(0) | maximum-length-of-a-concatenated-string-with-unique-characters | [Python3] backtracking | ye15 | 0 | 254 | maximum length of a concatenated string with unique characters | 1,239 | 0.522 | Medium | 18,641 |
https://leetcode.com/problems/tiling-a-rectangle-with-the-fewest-squares/discuss/1216988/Python3-backtracking | class Solution:
def tilingRectangle(self, n: int, m: int) -> int:
if n == m: return 1
depth = [0]*m
def fn(x):
"""Explore tiling rectangle area via backtracking."""
nonlocal ans
if x < ans:
if min(depth) == n: ans = x # all tiled
else:
i = min(depth)
j = jj = depth.index(i) # (i, j)
while jj < m and depth[jj] == depth[j]: jj += 1
k = min(n - i, jj - j)
for kk in reversed(range(1, k+1)):
for jj in range(j, j+kk): depth[jj] += kk
fn(x+1)
for jj in range(j, j+kk): depth[jj] -= kk
ans = max(n, m)
fn(0)
return ans | tiling-a-rectangle-with-the-fewest-squares | [Python3] backtracking | ye15 | 1 | 334 | tiling a rectangle with the fewest squares | 1,240 | 0.539 | Hard | 18,642 |
https://leetcode.com/problems/tiling-a-rectangle-with-the-fewest-squares/discuss/2844040/Bottom-Up-Approach-utilizing-Transpose-and-minimal-siding-speed-up | class Solution:
def tilingRectangle(self, n: int, m: int) -> int:
# edge case 1 allowing early quit processing.
if n == m :
return 1
# edge case 2, occurs according to tiling problem. Only one for which implementation breaks.
elif (n==11 and m == 13) or (n==13 and m==11) :
return 6
else :
# memo usage of results. Build from result 1 go to end result. Bottom up progression.
memo = [[0 for _ in range(m+1)] for _ in range(n+1)]
# loop from 1 to n inclusive
for n_measure in range(1, n+1) :
# loop 1 to m inclusive
for m_measure in range(1, m+1) :
# if we are at equal measures, this is a square
if (n_measure == m_measure) :
# mark it as 1 as these are our measures so this can be covered by equal square
memo[n_measure][m_measure] = 1
continue
# only do half the array
else :
if m_measure < n and n_measure < m and memo[m_measure][n_measure] != 0 :
memo[n_measure][m_measure] = memo[m_measure][n_measure]
continue
# otherwise, set sub rectangles 1 and 2 and minimal rectangle to infinity to start
sub_rectangle1, sub_rectangle2, min_rectangle = inf, inf, inf
offset = 1
# starting with offset of 1 go to min of n and m
while offset <= min(n_measure, m_measure) :
# if we have run off the smaller, break at this point
if (m_measure - offset < 0) or (n_measure - offset < 0) :
break
# get sub rectangles 1 and 2 based off of which slicing you're doing
sub_rectangle1 = memo[n_measure][m_measure-offset] + memo[n_measure-offset][offset]
sub_rectangle2 = memo[n_measure-offset][m_measure] + memo[offset][m_measure-offset]
# set min to minimum of the results now built
min_rectangle = min(min_rectangle, sub_rectangle1, sub_rectangle2)
# increment offset as if you are doing two different measures simultaneously
offset += 1
# memoize current result minmal plus 1 more for work done for this square itself.
memo[n_measure][m_measure] = min_rectangle + 1
return memo[n][m] | tiling-a-rectangle-with-the-fewest-squares | Bottom Up Approach utilizing Transpose and minimal siding speed up | laichbr | 0 | 1 | tiling a rectangle with the fewest squares | 1,240 | 0.539 | Hard | 18,643 |
https://leetcode.com/problems/minimum-swaps-to-make-strings-equal/discuss/1196255/Python3-solution-using-list-and-dictionary | class Solution:
def minimumSwap(self, s1: str, s2: str) -> int:
if s1 == s2:
return 0
else:
count = 0
d = {('xx','yy'):1,('xy','yx'):2,('yy','xx'):1,('yx','xy'):2}
x = []
y = []
for i,j in zip(s1,s2):
if i != j:
x.append(i)
y.append(j)
x.sort()
y.sort(reverse=True)
i,j = 0,0
if len(x)%2 != 0 or len(y)%2 != 0:
return -1
while i < len(x) and j < len(y):
z = (''.join(x[i:i+2]),''.join(y[i:i+2]))
if z not in d:
return -1
else:
count += d[z]
i += 2
j += 2
return count | minimum-swaps-to-make-strings-equal | Python3 solution using list and dictionary | EklavyaJoshi | 2 | 117 | minimum swaps to make strings equal | 1,247 | 0.638 | Medium | 18,644 |
https://leetcode.com/problems/minimum-swaps-to-make-strings-equal/discuss/2152657/python-3-oror-simple-greedy-solution-oror-O(n)O(1) | class Solution:
def minimumSwap(self, s1: str, s2: str) -> int:
xy = yx = 0
for c1, c2 in zip(s1, s2):
if c1 == 'x' and c2 == 'y':
xy += 1
elif c1 == 'y' and c2 == 'x':
yx += 1
if (xy + yx) % 2:
return -1
return xy // 2 + yx // 2 + (xy % 2) * 2 | minimum-swaps-to-make-strings-equal | python 3 || simple greedy solution || O(n)/O(1) | dereky4 | 1 | 101 | minimum swaps to make strings equal | 1,247 | 0.638 | Medium | 18,645 |
https://leetcode.com/problems/minimum-swaps-to-make-strings-equal/discuss/597304/Easy-Python-Solution-Runtime-20ms-faster-than-96 | class Solution:
def minimumSwap(self, s1: str, s2: str) -> int:
if len(s1)!=len(s2):
return -1
d={"xxyy":1, "xyyx":2,"xxxy":3,"yxxy":2, "yyxx":1,"xxxy":-1}
if len(s1)==2:
return d[s1+s2]
l1=[]
l2=[]
for i in range(len(s1)):
if s1[i]!=s2[i]:
l1.append(s1[i])
l2.append(s2[i])
print(l1)
print(l2)
l1.sort()
l2.sort(reverse=True)
print(l1)
print(l2)
if len(l1)%2!=0:
return -1
result=0
for i in range(0,len(l1)-1,2):
s1=l1[i]+l1[i+1]
s2=l2[i]+l2[i+1]
result+=d[s1+s2]
return (result) | minimum-swaps-to-make-strings-equal | Easy Python Solution Runtime-20ms faster than 96% | Ayu-99 | 0 | 84 | minimum swaps to make strings equal | 1,247 | 0.638 | Medium | 18,646 |
https://leetcode.com/problems/minimum-swaps-to-make-strings-equal/discuss/419432/Python-3-(beats-100)-(three-lines)-(-O(n)-)-(one-pass) | class Solution:
def minimumSwap(self, S: str, T: str) -> int:
L, D = len(S), {'x': 1, 'y': 1}
for i in range(L): D[S[i]] += S[i] != T[i]
return -1 if (D['x']+D['y']) % 2 else D['x']//2 + D['y']//2
- Junaid Mansuri | minimum-swaps-to-make-strings-equal | Python 3 (beats 100%) (three lines) ( O(n) ) (one pass) | junaidmansuri | -2 | 164 | minimum swaps to make strings equal | 1,247 | 0.638 | Medium | 18,647 |
https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/1265615/Python-Two-pointer | class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
right ,left = 0,0
ans = 0
odd_cnt = 0
ans = 0
cur_sub_cnt = 0
for right in range(len(nums)):
if nums[right]%2 == 1:
odd_cnt += 1
cur_sub_cnt = 0
while odd_cnt == k:
if nums[left]%2 == 1:
odd_cnt -= 1
cur_sub_cnt += 1
left += 1
ans += cur_sub_cnt
return ans | count-number-of-nice-subarrays | Python - Two pointer | harshhx | 28 | 1,300 | count number of nice subarrays | 1,248 | 0.597 | Medium | 18,648 |
https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/1808819/Python-Solution-Beats-95-81 | class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
odd_ls = []
for i, num in enumerate(nums):
if num % 2 == 1:
odd_ls.append(i)
odd_ls = [-1] + odd_ls + [len(nums)]
count = 0
for i in range(1, len(odd_ls) - k):
count += (odd_ls[i] - odd_ls[i - 1]) * (odd_ls[i + k] - odd_ls[i + k - 1])
return count | count-number-of-nice-subarrays | Python Solution Beats 95, 81 | code369369369 | 3 | 191 | count number of nice subarrays | 1,248 | 0.597 | Medium | 18,649 |
https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/1829179/Python-easy-to-read-and-understand-or-Subarray-sum-equals-k | class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
n = len(nums)
for i in range(n):
nums[i] = 0 if nums[i]%2 == 0 else 1
d = {0:1}
sums, ans = 0, 0
for i in range(n):
sums += nums[i]
if sums-k in d:
ans += d[sums-k]
d[sums] = d.get(sums, 0) + 1
return ans | count-number-of-nice-subarrays | Python easy to read and understand | Subarray sum equals k | sanial2001 | 1 | 268 | count number of nice subarrays | 1,248 | 0.597 | Medium | 18,650 |
https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/1790522/Easy-Python-Sliding-Window | class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
if nums == None or len(nums) < k:
return None
return self.two_pointers(nums, k) - self.two_pointers(nums, k - 1)
def two_pointers(self, nums, k):
odd = 0
result = 0
i, j = 0, 0
for j in range(len(nums)):
if nums[j] % 2 != 0:
odd += 1
while odd > k:
if nums[i] % 2 != 0:
odd -= 1
i += 1
result += (j - i + 1)
return result | count-number-of-nice-subarrays | Easy Python Sliding Window | lolapeng88 | 1 | 176 | count number of nice subarrays | 1,248 | 0.597 | Medium | 18,651 |
https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/2821543/Python-array-transformation | class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
stack=[]
preOdd=True
for i in nums:
if i%2==1:
if preOdd:
stack.append(1)
else:
if preOdd:
stack.append(2)
else:
stack[-1]+=1
preOdd=i%2==1
if preOdd:
stack.append(1)
return sum([stack[j]*stack[j+k] for j in range(len(stack)-k)]) | count-number-of-nice-subarrays | Python array transformation | guankiro | 0 | 2 | count number of nice subarrays | 1,248 | 0.597 | Medium | 18,652 |
https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/2771497/Python-Sliding-Window | class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
def helper(k):
l, odd_c, res = 0, 0, 0
for r in range(len(nums)):
odd_c += nums[r] % 2
while odd_c > k:
odd_c -= nums[l] % 2
l += 1
res += r - l + 1
return res
return helper(k) - helper(k - 1) | count-number-of-nice-subarrays | Python Sliding Window | JSTM2022 | 0 | 7 | count number of nice subarrays | 1,248 | 0.597 | Medium | 18,653 |
https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/2745963/Python3-oror-easy-Solution | class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
oddPos = [-1]
ans = 0; n = len(nums)
for i in range(n):
if(nums[i]%2==1):
oddPos.append(i)
oddPos.append(n)
n = len(oddPos)
i = 1
while(i+k<n):
ans+=(oddPos[i]-oddPos[i-1])*(oddPos[i+k]-oddPos[i+k-1])
i+=1
return ans | count-number-of-nice-subarrays | Python3 || easy Solution | ty2134029 | 0 | 4 | count number of nice subarrays | 1,248 | 0.597 | Medium | 18,654 |
https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/2718006/Python3-Prefix-Sum-with-Visual-Explanation-O(n)-Space-O(n)-Time-Complexity | class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
prefixSum = [1 if n & 1 else 0 for n in nums]
for idx in range(len(nums)):
prefixSum[idx] += prefixSum[idx-1] if idx-1 >= 0 else 0
result = 0
dic = {0: 1}
for num in prefixSum:
if num - k in dic:
result += dic[num-k]
dic[num] = dic.get(num, 0) + 1
return result | count-number-of-nice-subarrays | [Python3] Prefix Sum with Visual Explanation = O(n) Space, O(n) Time Complexity | mania7 | 0 | 11 | count number of nice subarrays | 1,248 | 0.597 | Medium | 18,655 |
https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/2663504/Python3-Solution-oror-O(N)-Time-and-Space-Complexity | class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
prefixSum=0
dic={}
count=0
for i in range(len(nums)):
if nums[i]&1!=0:
prefixSum+=1
if prefixSum not in dic:
dic[prefixSum]=0
if prefixSum==k:
count+=1
if prefixSum-k in dic:
count+=dic[prefixSum-k]
dic[prefixSum]+=1
return count | count-number-of-nice-subarrays | Python3 Solution || O(N) Time & Space Complexity | akshatkhanna37 | 0 | 9 | count number of nice subarrays | 1,248 | 0.597 | Medium | 18,656 |
https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/2604209/Python-or-Sliding-Window-or-Easy-To-Understand | class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
res = 0
cnt = 0
left = right = 0
while right < len(nums):
cnt += (nums[right]%2==1)
if cnt == k:
# set the `left` and `right` counter
cnt_left = 1
cnt_right = 1
# how many number before this odd number?
while left < right and nums[left]%2!=1:
cnt_left += 1
left += 1
# one more move to shrink the window
left += 1
cnt -= 1
# how many number between right and next valid odd?
while right+1 < len(nums) and nums[right+1]%2!=1:
cnt_right += 1
right += 1
res += (cnt_left)*(cnt_right)
right += 1
return res | count-number-of-nice-subarrays | Python | Sliding Window | Easy To Understand 🔥 | evan-dayy | 0 | 54 | count number of nice subarrays | 1,248 | 0.597 | Medium | 18,657 |
https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/2378137/PYTHON-or-LINEAT-TIME-or-HASHMAP-or-EXPLAINED-or-EASY-or | class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
d = defaultdict(int)
d[0] = 1
count = 0
ans = 0
for num in nums:
if num % 2 == 1: count += 1
ans += d[count - k]
d[count] += 1
return ans | count-number-of-nice-subarrays | PYTHON | LINEAT TIME | HASHMAP | EXPLAINED | EASY | | reaper_27 | 0 | 98 | count number of nice subarrays | 1,248 | 0.597 | Medium | 18,658 |
https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/1959115/python3-swipe-windows-easy-understand | class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
prev_start, prev_end = 0, 1
odd_cnt = 0
ret = 0
for i, n in enumerate(nums):
if n % 2 == 1:
odd_cnt += 1
while odd_cnt > k:
if nums[prev_start] % 2 == 1:
odd_cnt -= 1
prev_start += 1
prev_end = prev_start
add_back = False
while odd_cnt > k - 1:
if nums[prev_end] % 2 == 1:
odd_cnt -= 1
add_back = True
prev_end += 1
if add_back: odd_cnt += 1
if odd_cnt == k:
ret += (prev_end - prev_start)
return ret | count-number-of-nice-subarrays | python3 swipe windows easy understand | BichengWang | 0 | 151 | count number of nice subarrays | 1,248 | 0.597 | Medium | 18,659 |
https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/1754246/Python-Prefix-%22count%22-solution-explained | class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
# will store the count of the odd nums
# we have seen till now, we're also going
# to add the fact that we've seen an odd num
# already to account for when the whole
# subarray having count(odd_nums) == k, more on that later
counter = {0:1}
res = 0 # num subarrays of valid subarrays
odd_count = 0 # rolling count of number of odd nums
for i in range(len(nums)):
# increment the rolling count of the
# num of odds we have seen hitherto
if nums[i] % 2 != 0:
odd_count += 1
# now, we check if there's an existing
# subarray which we've seen already
# which has x odd numbers such that the curr_odd_num - k == x
# i.e can we remove an existing subarray which
# from the current subarray such that the current
# odd num count becomes k?
#
# Now, if there was a subarray which had
# it's odd num count equal to k, we'll check if odd_count - k in d
# i.e k - k in d => 0 in d and hence we added that
# 0 in the map initially to counter this case
if odd_count - k in counter:
res += counter[odd_count - k]
# and either way, we're going to add the
# current rolling odd num count to our dictionary
# for further processing
counter[odd_count] = counter.get(odd_count, 0) + 1
return res | count-number-of-nice-subarrays | [Python] Prefix "count" solution explained | buccatini | 0 | 79 | count number of nice subarrays | 1,248 | 0.597 | Medium | 18,660 |
https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/1650850/Python-O(n)-time-O(1)-space-sliding-window-solution | class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
return self.atmostk(nums, k) - self.atmostk(nums, k-1)
def atmostk(self, s, k):
lookup = defaultdict(int)
l, r, counter, res = 0, 0, 0, 0
while r < len(s):
if s[r] % 2 ==1:
lookup[s[r]] += 1
counter += 1
r += 1
while l <r and counter > k:
if s[l] %2 == 1:
if lookup[s[l]] >= 2:
lookup[s[l]] -=1
else:
del lookup[s[l]]
counter -= 1
l += 1
res += (r-l+1)
return res | count-number-of-nice-subarrays | Python O(n) time, O(1) space sliding window solution | byuns9334 | 0 | 230 | count number of nice subarrays | 1,248 | 0.597 | Medium | 18,661 |
https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/1489131/You-must-see-once-oror-Tricky-One-oror-I-Found-it-in-2-hrs | class Solution:
def numberOfSubarrays(self, nums: List[int], k: int) -> int:
res,left,end=0,0,0
n=len(nums)
dic = defaultdict(int)
while (end<n):
dic[nums[end]%2]+=1
if dic[1]==k:
re = 0 # count of even numbers right side of limit (k no. of odds)
while end+1<n and nums[end+1]%2==0:
re+=1
end+=1
dic[0]+=1
le = 0
while dic[1]==k:
le+=1
dic[nums[left]%2]-=1
left+=1
if re:
res += le*(re+1)
else:
res += le
end+=1
return res | count-number-of-nice-subarrays | 📌📌 You must see once || Tricky-One || I Found it in 2 hrs 🐍 | abhi9Rai | 0 | 445 | count number of nice subarrays | 1,248 | 0.597 | Medium | 18,662 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/503754/Python-Memory-Usage-Less-Than-100-Faster-than-100 | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
open = 0
s = list(s)
for i, c in enumerate(s):
if c == '(': open += 1
elif c == ')':
if not open: s[i] = ""
else: open -= 1
for i in range(len(s)-1, -1, -1):
if not open: break
if s[i] == '(': s[i] = ""; open -= 1
return "".join(s) | minimum-remove-to-make-valid-parentheses | Python - Memory Usage Less Than 100%, Faster than 100% | mmbhatk | 24 | 2,900 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,663 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1073038/Python-or-Fast-and-Easy-or-Beats-98 | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack = []
s = list(s)
for i in range(len(s)):
if s[i] == "(": stack.append(i)
elif s[i] == ")":
if stack: stack.pop()
else: s[i] = ""
for i in stack:
s[i] = ""
return "".join(s) | minimum-remove-to-make-valid-parentheses | Python | Fast & Easy | Beats 98% | SlavaHerasymov | 13 | 635 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,664 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1850429/Python-Simple-Python-Solution-Using-Stack-and-Iterative-Approach | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
s=list(s)
stack = []
for i in range(len(s)):
if s[i]=='(':
stack.append(i)
elif s[i]==')':
if len(stack)>0:
stack.pop()
else:
s[i] = ''
while len(stack)>0:
s[stack[-1]]=''
stack.pop()
return ''.join(s) | minimum-remove-to-make-valid-parentheses | [ Python ] ✔✔ Simple Python Solution Using Stack and Iterative Approach 🔥✌ | ASHOK_KUMAR_MEGHVANSHI | 4 | 172 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,665 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1291344/fastest-solution-in-python-using-stack-or-easy | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
s= list(s)
stack= []
for i in range(len(s)):
if s[i]=='(':
stack.append(i)
elif s[i]==')':
if stack:
stack.pop()
else:
s[i]=''
for i in stack:
s[i]=''
return ''.join(s) | minimum-remove-to-make-valid-parentheses | fastest solution in python using stack | easy | chikushen99 | 4 | 181 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,666 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1683379/Python-Simple-Solution-with-and-without-Stack | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
ans=list()
count_bracket=0
for index,char in enumerate(s):
if char =='(':
count_bracket+=1
elif char ==')':
if not count_bracket:
continue
count_bracket-=1
ans.append(char)
for i in range(len(ans)-1,-1,-1):
if ans[i]=='(' and count_bracket >0 :
ans[i]=''
count_bracket-=1
else:
continue
return ''.join(ans) | minimum-remove-to-make-valid-parentheses | Python Simple Solution with and without Stack | redux1779 | 3 | 174 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,667 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1683379/Python-Simple-Solution-with-and-without-Stack | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack=list()
ans=list(s)
for index,char in enumerate(s):
if char =='(': stack.append(index)
elif char ==')':
if stack: stack.pop()
else: ans[index]=''
for left_index in stack:
ans[left_index]=''
return "".join(ans) | minimum-remove-to-make-valid-parentheses | Python Simple Solution with and without Stack | redux1779 | 3 | 174 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,668 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1852004/Python-Easy-prefix-count | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
closing, opening, ans = s.count(')'), 0, ''
for i in s:
if i == '(':
opening += 1
if opening <= closing: ans += '('
elif i == ')':
if opening > 0: ans += ')'
closing -= 1; opening -= 1
if opening < 0: opening = 0
else: ans += i
return ans | minimum-remove-to-make-valid-parentheses | ✅ Python Easy prefix count | dhananjay79 | 2 | 67 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,669 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1537727/Python-3-%3A-99-faster-solution | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack = []
s = list(s)
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
elif s[i] == ')':
if stack:
stack.pop()
else:
s[i] = ""
for j in stack:
s[j] = ""
return "".join(s) | minimum-remove-to-make-valid-parentheses | Python 3 : 99% faster solution | deleted_user | 2 | 108 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,670 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1428700/Intuitive-Approach-or-Easy-Solution-or-Python3 | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stackParan = []
stackIdx = []
n = len(s)
for i in range(n):
if s[i].islower() == True:
continue
else:
#Checking Valid Paranthesis
if len(stackParan) == 0 and len(stackIdx) == 0:
stackParan.append(s[i])
stackIdx.append(i)
else:
if stackParan[-1] == "(" and s[i] == ")":
stackParan.pop()
stackIdx.pop()
elif stackParan[-1] == ")" or stackParan[-1] == "(":
stackParan.append(s[i])
stackIdx.append(i)
s = list(s)
while stackIdx != []:
s.pop(stackIdx[-1])
stackIdx.pop()
return "".join(s) | minimum-remove-to-make-valid-parentheses | Intuitive Approach | Easy Solution | Python3 | dkamat01 | 2 | 73 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,671 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/994699/Simple-Python-3-stack-solution-with-short-explanation | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
'''
Keep a stack of indices of front parens "(", pop when you encounter a back paren ")".
If front stack is empty, add index to back set.
Add everything in front stack to back set for fast lookup.
Recompute s, skipping any index that's in the set.
'''
front, back = [], set()
for i, c in enumerate(s):
if c == '(':
front.append(i)
elif c == ')':
if front:
front.pop()
else:
back.add(i)
for i in front:
back.add(i)
return ''.join([c for i, c in enumerate(s) if i not in back]) | minimum-remove-to-make-valid-parentheses | Simple Python 3 stack solution with short explanation | gins1 | 2 | 144 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,672 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/2165204/Python3-oror-Easiest-and-Efficient-oror-tc%3A-O(n)-sc%3A-O(n)-oror-Explained | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
st = deque()
prob = deque()
for i in range(len(s)):
if s[i] == '(':
st.append(i)
elif s[i] == ')':
if st: st.pop()
else: prob.append(i)
st = set(st + prob)
news = ''
for i in range(len(s)):
if i not in st: news += s[i]
return news | minimum-remove-to-make-valid-parentheses | Python3 || Easiest and Efficient || tc: O(n) sc: O(n) || Explained | Dewang_Patil | 1 | 92 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,673 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1916001/Python-easy-to-read-and-understand-or-stack | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
invalid = []
stack = []
n = len(s)
for i in range(n):
if s[i] == "(":
stack.append(i)
elif s[i] == ")":
if stack and s[stack[-1]] == "(":
stack.pop()
else:
invalid.append(i)
#print(stack)
for i in range(len(stack)):
invalid.append(stack[i])
res = ""
for i in range(n):
if i in invalid:
continue
else:
res += s[i]
return res | minimum-remove-to-make-valid-parentheses | Python easy to read and understand | stack | sanial2001 | 1 | 99 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,674 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1852382/Python-Python3-or-Clean-Code-Simple-O(n) | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
indexes = []
for i in range(len(s)):
if s[i] == '(':
indexes.append(i)
elif s[i] == ')':
if not len(indexes) or s[indexes[-1]] == ')':
indexes.append(i)
else:
indexes.pop()
for deleted, index in enumerate(indexes):
s = s[:index - deleted] + s[index + 1 - deleted:]
return s | minimum-remove-to-make-valid-parentheses | Python / Python3 | Clean Code, Simple O(n) | casmith1987 | 1 | 36 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,675 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1851412/Python-or-Simple-Solution | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
def f(s, c1, c2):
a = 0
ans = ""
for i in s:
if i==c1:
a += 1
ans += i
elif i==c2:
a -= 1
if a >= 0:
ans += i
else:
a = 0
else:
ans += i
return ans, a
ans, a = f(s, "(", ")")
if a>0:
ans, _ = f(ans[::-1], ")", "(")
return ans[::-1]
return ans | minimum-remove-to-make-valid-parentheses | [Python] | Simple Solution | zouhair11elhadi | 1 | 22 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,676 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1851345/python-easy-stack-solution | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
index_stack = []
s = list(s)
for i in range(len(s)):
if s[i]=='(':
index_stack.append(i)
elif s[i] == ')':
if len(index_stack)!=0:
index_stack.pop()
else:
s[i] = ""
for i in index_stack:
s[i] = ""
return "".join(s) | minimum-remove-to-make-valid-parentheses | python easy stack solution | Brillianttyagi | 1 | 38 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,677 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1073808/Python-or-Stack | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack = []
for i in range(len(s)):
if s[i] == '(':
stack.append(('(', i))
elif s[i] == ')':
stack.append((')', i))
if len(stack) > 1:
if stack[-1][0] == ')' and stack[-2][0] == '(':
stack.pop()
stack.pop()
s = [i for i in s]
for x in stack:
s[x[1]] = None
return("".join([i for i in s if i != None])) | minimum-remove-to-make-valid-parentheses | Python | Stack | Sai-Adarsh | 1 | 83 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,678 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1072741/One-pass-Python-solution-faster-than-80-submissions | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
ans = [""] * len(s)
op = []
for i in range(len(s)):
if s[i] == "(":
op.append(i)
elif s[i] == ")":
if len(op)>0:
idx = op.pop()
ans[idx] = "("
ans[i] = s[i]
else:
ans[i] = s[i]
return "".join(ans) | minimum-remove-to-make-valid-parentheses | One pass Python solution, faster than 80% submissions | shrutigupta55 | 1 | 26 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,679 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/2788316/Python-Runtime%3A-Faster-than-63.46-Memory%3A-Lesser-than-95.96 | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack = []
invalid_closes = []
for i in range(len(s)):
c = s[i]
if c == '(': # if opening, append
stack.append(i)
elif c == ')' and stack: #if closed and stack is not empty
stack.pop(-1) # pop latest open bracket
elif c == ')' and not stack: #if closed and stack is empty
invalid_closes.append(i)
for r in sorted(stack + invalid_closes,reverse=True):
s = s[:r] + s[r+1:]
return s | minimum-remove-to-make-valid-parentheses | Python - Runtime: Faster than 63.46%, Memory: Lesser than 95.96% | leeweixuan | 0 | 3 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,680 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/2786543/Naive-O(N)-solution-for-python | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack=[]
pos=[]
for i in range(len(s)):
if s[i]=='(':
stack.append('(')
pos.append(i) #record position
elif s[i]==')':
if len(stack)>0 and stack[-1]=='(':
stack.pop()
pos.pop()
else:
stack.append(')')
pos.append(i)
ans=[]
pos=set(pos)
for i in range(len(s)):
if i in pos:
continue
else:
ans.append(s[i])
return ''.join(ans) | minimum-remove-to-make-valid-parentheses | Naive O(N) solution for python | xmanfire007 | 0 | 1 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,681 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/2744327/Python-Easy-Stack-Solution | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack = []
stack_pos = []
s_l = list(s)
for i, v in enumerate(s):
if v == '(':
stack.append('(')
stack_pos.append(i)
elif stack and v ==')' and stack[-1]=='(':
stack.pop()
stack_pos.pop()
elif v ==')':
stack.append(')')
stack_pos.append(i)
# print(stack)
# print(stack_pos)
for i in stack_pos:
s_l[i]=''
return ''.join(s_l) | minimum-remove-to-make-valid-parentheses | Python Easy Stack Solution | ben_wei | 0 | 4 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,682 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/2627054/Python3-Simple-low-memory | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
# First Pass - search for unbalanced ')'
i = 0
stack = []
# Add each opening brace to a stack. On each closing brace, if there is no corresponding opening
# one in the stack - then remove it. If there is, pop from the stack
while i < len(s):
if s[i] == '(':
stack.append('(')
if s[i] == ')':
if stack:
stack.pop()
else:
s = s[:i] + s[i+1:]
i -= 1
i += 1
# Second Pass - search for unbalanced '('
stack = []
i -= 1
# Add each closing to a stack. On each opening check the stack.
# Remove if unbalanced. If balanced, pop from the stack
while i >= 0:
if s[i] == ')':
stack.append(')')
if s[i] == '(':
if stack: stack.pop()
else:
s = s[:i] + s[i+1:]
i -=1
return s | minimum-remove-to-make-valid-parentheses | [Python3] Simple, low memory | connorthecrowe | 0 | 10 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,683 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/2563129/Clean-Fast-Python3-or-O(n)-or-Stack | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
opens, dels = [], set()
for i, c in enumerate(s):
if c == '(':
opens.append(i)
elif c == ')':
if opens:
opens.pop()
else:
dels.add(i)
dels.update(opens)
res = ""
for i, c in enumerate(s):
if i not in dels:
res += c
return res | minimum-remove-to-make-valid-parentheses | Clean, Fast Python3 | O(n) | Stack | ryangrayson | 0 | 15 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,684 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/2508646/Python-solution.-beats-37-runtime-and-99-memory | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
st = []
ans = s
count = 0
for i in range(len(s)):
if s[i] == '(':
st.append('(')
elif s[i] == ')' and len(st) != 0:
st.pop()
elif s[i] == ')' and len(st) == 0:
#this count variable is being used as we are removing elements in ans,
#so the position of the latter elements gets pushed forward by 1 so we do add 1 everytime we remove an element from the string
#this takes care of extra opening parenthesis
ans = ans[:i-count] + ans[i+1-count:]
count +=1
#print(ans, st)
#this is to take care of extra closing parenthesis
if len(st) != 0:
for i in range(len(ans)-1, -1, -1):
if len(st) == 0:
break
if ans[i] == '(':
ans = ans[:i] + ans[i+1:]
st.pop()
return ans | minimum-remove-to-make-valid-parentheses | Python solution. beats 37% runtime and 99% memory, | neeraj02 | 0 | 10 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,685 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/2378423/PYTHON-or-STACK-BASED-or-EXPLANED-WITH-PICTURE-or-CLEAR-AND-CONSICE-or | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack = []
for index,val in enumerate(s):
if val == '(':
stack.append(val)
elif val == ')':
tmp = ""
while stack and stack[-1] != '(':
tmp = stack.pop() + tmp
if stack: tmp = stack.pop() + tmp + ')'
stack.append(tmp)
else:
stack.append(val)
tmp = ""
for i in stack:
if i == '(': continue
tmp += i
return tmp | minimum-remove-to-make-valid-parentheses | PYTHON | STACK BASED | EXPLANED WITH PICTURE | CLEAR AND CONSICE | | reaper_27 | 0 | 42 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,686 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1854683/Python3-Easy-solution-with-explanation | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
bracket_stack = []
temp = list(s)
for i in range(len(s)):
if s[i] == '(':
bracket_stack.append(i)
elif s[i] ==')':
if bracket_stack:
bracket_stack.pop()
else:
temp[i] = ''
# print(bracket_stack) Use these statements for better understanding with all the given 3 Test Cases
# print(temp)
for i in bracket_stack:
temp[i]=''
return ''.join(temp) | minimum-remove-to-make-valid-parentheses | Python3- Easy solution with explanation | SAvasthi | 0 | 24 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,687 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1852281/Simple-Python3-Solution | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
cnt_open, cnt_close, res = 0, 0, ''
for ch in s:
if ch == '(': cnt_open += 1
if ch == ')': cnt_close += 1
if cnt_open < cnt_close:
cnt_close -= 1
else:
res = res + ch
s = res
cnt_open, cnt_close, res = 0, 0, ''
for ch in reversed(s):
if ch == '(': cnt_open += 1
if ch == ')': cnt_close += 1
if cnt_close < cnt_open:
cnt_open -= 1
else:
res = ch + res
return res | minimum-remove-to-make-valid-parentheses | Simple Python3 Solution | user6774u | 0 | 14 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,688 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1852183/simple-python-stack | class Solution(object):
def minRemoveToMakeValid(self, s: str) -> str:
s = list(s)
stack = []
for i, char in enumerate(s):
if char == '(':
stack.append(i)
elif char == ')':
if stack:
stack.pop()
else:
s[i] = ''
while stack:
s[stack.pop()] = ''
return ''.join(s) | minimum-remove-to-make-valid-parentheses | simple python stack | gasohel336 | 0 | 21 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,689 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1852107/Python3-Solution-with-using-stack | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack = []
open_cnt = 0
for idx in range(len(s)):
if s[idx] == '(':
stack.append(idx)
open_cnt += 1
elif s[idx] == ')':
if stack and open_cnt > 0:
stack.pop()
open_cnt -= 1
else:
stack.append(idx)
cur_stack_idx = 0
res = []
for idx in range(len(s)):
if cur_stack_idx < len(stack) and idx == stack[cur_stack_idx]:
cur_stack_idx += 1
continue
res.append(s[idx])
return ''.join(res) | minimum-remove-to-make-valid-parentheses | [Python3] Solution with using stack | maosipov11 | 0 | 8 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,690 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1852103/simply-python-stack | class Solution(object):
def minRemoveToMakeValid(self, s: str) -> str:
s = list(s)
stack = []
for i, char in enumerate(s):
if char == '(':
stack.append(i)
elif char == ')':
if stack:
stack.pop()
else:
s[i] = ''
while stack:
s[stack.pop()] = ''
return ''.join(s)
sol = Solution()
print(sol.minRemoveToMakeValid("(()")) | minimum-remove-to-make-valid-parentheses | simply python stack | gasohel336 | 0 | 12 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,691 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1851761/Simple-Python-3-solution-using-set-and-stack | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
st=[] # stack
ans="" #ans string
l="("
r=")"
tobeRemoved = set() #set contains indexes to be removed
for idx in range(len(s)):
i = s[idx]
if i == l : # if "(" add in stack
st.append(idx)
elif i==r:
if st: # if stack then pop the top element from it
# as we are only adding "(" into stack if ")" comes then its
# pair is found
st.pop()
else:
tobeRemoved.add(idx)
for i in st:
tobeRemoved.add(i)
for i in range(len(s)):
if i not in tobeRemoved:
ans+=s[i]
return ans | minimum-remove-to-make-valid-parentheses | Simple Python 3 solution using set and stack | Anurag_Tiwari | 0 | 16 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,692 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1851552/PYTHON-SIMPLE-list-and-stack-solution-with-explanation-(154ms) | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
LENGTH = len ( s );
#We will put all of the characters in a list
constructionZone = [];
#We do this for constant access to characters
for i in range( LENGTH ):
constructionZone.append( s[ i ] );
#Have a stack to process matches
stack = [];
#For each character
for i in range( LENGTH ):
char = s[ i ];
#When we see a left parenthesis we place its index
#In the stack
if char == '(':
stack.append( i );
#For the right ones,
elif char == ')':
#If we have a match,
if len ( stack ) > 0:
#We take out the index of the left
nullIndex = stack.pop();
#And we will replace the matching pair in the list
#With these dummy parenthesis
constructionZone[ nullIndex ] = '{';
constructionZone[ i ] = '}';
#We go through our list of characters
for i in range( LENGTH ):
char = constructionZone[ i ];
#Any of the unmatched ones, we re assign to
#Empty
if char in "()":
constructionZone[ i ] = "";
#And the good ones, that we marked with dummy parenthesis
#We put back
elif char == '{':
constructionZone[ i ] = '(';
elif char == '}':
constructionZone[ i ] = ')';
#Lastly, we join the list back into a string
return "".join ( constructionZone ); | minimum-remove-to-make-valid-parentheses | PYTHON SIMPLE list and stack solution with explanation (154ms) | greg_savage | 0 | 20 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,693 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1851501/Python-Simple-Solution | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack = []
arr = list(s)
for i in range(len(arr)):
if arr[i] == "(":
stack.append(i)
elif arr[i] == ")":
if len(stack) == 0:
arr[i] = "."
else:
stack.pop()
for i in stack:
arr[i] = "."
count = arr.count(".")
ansStr = "".join(arr)
return ansStr.replace(".", "", count) | minimum-remove-to-make-valid-parentheses | [Python] Simple Solution | chitranshibendale | 0 | 21 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,694 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1851206/Easy-peasy-python-solution-with-minimum-space-and-O(n)-time | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack = 0
remove = []
open_ind = []
for ind, val in enumerate(s):
if val == '(':
open_ind.append(ind)
stack+=1
elif val == ')' and stack>0:
open_ind.pop(-1)
stack-=1
elif val == ')' and stack ==0:
remove.append(ind)
final_arr = remove+open_ind
final_arr.sort()
for val in reversed(final_arr):
s = s[:val]+s[val+1:]
return s | minimum-remove-to-make-valid-parentheses | Easy peasy python solution with minimum space and O(n) time | shubham3 | 0 | 6 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,695 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1851182/Python-or-Extension-of-valid-parentheses-or-o(n) | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack = []
#step 1 : Collect invalid paranthese index
for index in range(len(s)) :
ch = s[index]
if ch in ('(',')'):
if stack:
if ch == ')' and s[stack[-1]] == '(':
stack.pop()
else:
stack.append(index)
else:
stack.append(index)
#step 1 : Re-itrate ignore the invalid indexes present in stack
result = ""
stack = set(stack)
for index in range(len(s)):
if index not in stack:
result += s[index]
return result | minimum-remove-to-make-valid-parentheses | Python | Extension of valid parentheses | o(n) | cheppu4 | 0 | 12 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,696 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1850922/Python3-92.52-or-Stack-and-StringBuilder-or-Easy-Implementation | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
st = deque([])
sb = []
ans = 0
for cha in s:
sb.append(cha)
if cha == ')':
if st:
st.pop()
else:
sb.pop()
if cha == '(':
st.append(len(sb) - 1)
sb2 = []
for i, cha in enumerate(sb):
if st and i == st[0]:
st.popleft()
continue
sb2.append(cha)
return ''.join(sb2) | minimum-remove-to-make-valid-parentheses | Python3 92.52% | Stack & StringBuilder | Easy Implementation | doneowth | 0 | 8 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,697 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1850709/Python-oror-2-Pointer-oror-2-Pass-Solution-oror-Linear-Time | class Solution:
def process(self, s, reverse = False):
open_, close = 0,0
i = 0 if not reverse else len(s)-1
newS = ""
while -1 < i < len(s):
if s[i] == '(':
open_+=1
elif s[i] == ')':
close+=1
else:
newS = newS + s[i] if not reverse else s[i] + newS
i = i + 1 if not reverse else i - 1
continue
if reverse:
if close >= open_:
newS = s[i]+newS
else:
open_ -= 1
i-=1
else:
if close <= open_:
newS += s[i]
else:
close -= 1
i+=1
return newS
def minRemoveToMakeValid(self, s: str) -> str:
return self.process(self.process(s), True) | minimum-remove-to-make-valid-parentheses | Python || 2 Pointer || 2 Pass Solution || Linear Time | sathwickreddy | 0 | 29 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,698 |
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/1850659/Python-oror-Time-O(n)-oror-Explained-with-Picture-oror-Easy-To-understand | class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
# Stack will be used to check wheather the parenthese is valid or not
stack = []
# Pos is used to iterate over the string
pos = 0
# In valid, we will keep all the valid parenthese
valid = []
# We will iterate over the string
for i in s:
# If '(' encounterd, push it into the stack, with its index.
if i == '(':
stack.append(['(', pos])
# If ')' is encountered, will check the last element of stack. If that is '(', then this will ve valid.
# So, will push that index of the parenthese into the valid variable
# Then pos the last element of the stack
elif i == ')':
if stack and stack[-1][0] == '(':
valid.append(stack[-1][1])
valid.append(pos)
stack.pop()
pos += 1
# If string = "lee(t(c)o)de)"
# Then valid = [5, 7, 3, 9]
# Sort this valid
# So, valid = [3, 5, 7, 9]
valid.sort()
# Now again we will iterate over the string. If we get any parenthese, will check if that position is present in the valid list or not
# If present, then push that into the answer
# if not, then leave that
l = len(valid)
valid_pos = 0
ans = ''
pos = 0
for i in s:
if valid_pos < l and pos == valid[valid_pos]:
ans += i
valid_pos += 1
elif i != "(" and i != ')':
ans += i
pos += 1
# Return the ans variable
return ans | minimum-remove-to-make-valid-parentheses | ✅ Python || Time O(n) || Explained with Picture || Easy To understand | tusharkanti2001maji | 0 | 9 | minimum remove to make valid parentheses | 1,249 | 0.657 | Medium | 18,699 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.