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/can-convert-string-in-k-moves/discuss/2155709/python-3-or-simple-O(n)O(1)-solution | class Solution:
def canConvertString(self, s: str, t: str, k: int) -> bool:
if len(s) != len(t):
return False
cycles, extra = divmod(k, 26)
shifts = [cycles + (shift <= extra) for shift in range(26)]
for cs, ct in zip(s, t):
shift = (ord(ct) - ord(cs)) % 26
if shift == 0:
continue
if not shifts[shift]:
return False
shifts[shift] -= 1
return True | can-convert-string-in-k-moves | python 3 | simple O(n)/O(1) solution | dereky4 | 0 | 67 | can convert string in k moves | 1,540 | 0.332 | Medium | 22,800 |
https://leetcode.com/problems/can-convert-string-in-k-moves/discuss/2069898/Simple-Python-Solution-or-Space-%3A-O(1)-or-Time-%3A-O(N) | class Solution:
def canConvertString(self, s: str, t: str, k: int) -> bool:
#If length of strings are different return False
if len(s) != len(t):
return False
check = [0]*26 #List which stores counts of t[i] - s[i]
#Storing counts of t[i] - s[i] for 0 <= i < len(s)
for i in range(len(s)):
if s[i] != t[i]:
temp = ( ord(t[i]) - ord(s[i]) ) % 26
big = temp + 26*check[temp]
check[temp] += 1
if big > k:
return False
return True | can-convert-string-in-k-moves | Simple Python Solution | Space : O(1) | Time : O(N) 🐍 | notradley | 0 | 61 | can convert string in k moves | 1,540 | 0.332 | Medium | 22,801 |
https://leetcode.com/problems/can-convert-string-in-k-moves/discuss/784642/Python3-via-a-dictionary | class Solution:
def canConvertString(self, s: str, t: str, k: int) -> bool:
if len(s) != len(t): return False #edge case
seen = {}
for ss, tt in zip(s, t):
if ss != tt:
d = (ord(tt) - ord(ss)) % 26 #distance
if d not in seen: seen[d] = d
else: seen[d] += 26
if seen[d] > k: return False
return True | can-convert-string-in-k-moves | [Python3] via a dictionary | ye15 | 0 | 20 | can convert string in k moves | 1,540 | 0.332 | Medium | 22,802 |
https://leetcode.com/problems/can-convert-string-in-k-moves/discuss/783456/Python3-Hashmap-solution | class Solution:
def canConvertString(self, s: str, t: str, k: int) -> bool:
if len(s)!=len(t):return False
lookup=collections.defaultdict(int)
for i in range(len(s)):
if s[i]!=t[i]:
char = ord(t[i])-ord(s[i])
if char<0:char+=26
lookup[char] += 1
keys = sorted(lookup.keys())
for key in keys:
temp=key
if key<k:
lookup[key]-=1
while lookup[key]:
temp+=26
if temp>k:break
if temp<=k:
lookup[key]-=1
if temp>k or key>k:return False
return True | can-convert-string-in-k-moves | Python3 Hashmap solution | harshitCode13 | 0 | 25 | can convert string in k moves | 1,540 | 0.332 | Medium | 22,803 |
https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/discuss/2825876/Python | class Solution:
def minInsertions(self, s: str) -> int:
"""
(
"""
res = need = 0
for i in range(len(s)):
if s[i] == '(':
need += 2
if need % 2 == 1:
res += 1
need -= 1
if s[i] == ')':
need -= 1
if need == -1:
res += 1
need = 1
return res + need | minimum-insertions-to-balance-a-parentheses-string | Python | lillllllllly | 0 | 2 | minimum insertions to balance a parentheses string | 1,541 | 0.499 | Medium | 22,804 |
https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/discuss/2740284/python | class Solution:
def minInsertions(self, s):
res = right = 0
for c in s:
if c == '(':
if right % 2:
right -= 1
res += 1
right += 2
if c == ')':
right -= 1
if right < 0:
right += 2
res += 1
return right + res | minimum-insertions-to-balance-a-parentheses-string | python | yhu415 | 0 | 4 | minimum insertions to balance a parentheses string | 1,541 | 0.499 | Medium | 22,805 |
https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/discuss/2686697/Python%2B-detailed-explanation | class Solution:
def minInsertions(self, s: str) -> int:
stk = list()
res = 0
idx = 0
while (idx < len(s)):
c = s[idx]
if (c == '('):
stk.append(c)
else: # 如果是right paren
# Fill in left parenthesis
if (not stk): # 如果没有left paren在stack
res += 1
stk.append('(')
# Paired right parenthesis.
if (idx < len(s) - 1 and s[idx + 1] == ')'):
idx += 1
stk.pop()
# Unpaired right parenthesis.
else:
res += 1
stk.pop()
idx += 1
# Calculate unpaired left parenthesis.
res += len(stk) * 2
return res
# # res 记录插入次数
# # need 变量记录右括号的需求量
# need, res = 0, 0
# for i in range(len(s)):
# if s[i] == '(':
# need += 2
# # 当遇到左括号时,若对右括号的需求量为奇数,需要插入 1 个右括号。
# # 因为一个左括号需要两个右括号嘛,右括号的需求必须是偶数
# if need %2 == 1:
# # 插入一个右括号
# res += 1
# # 对右括号的需求减一
# need -= 1
# elif s[i] == ')':
# need -= 1
# # 说明右括号太多了
# if need == -1:
# # 需要插入一个左括号
# res += 1
# # 同时,对右括号的需求变为 1
# # -1 -> 1 # 相当于是add 2 to need
# need = 1
# return need + res | minimum-insertions-to-balance-a-parentheses-string | Python+ detailed explanation | Michael_Songru | 0 | 5 | minimum insertions to balance a parentheses string | 1,541 | 0.499 | Medium | 22,806 |
https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/discuss/2677774/Simple-linear-solution-in-Python | class Solution:
def minInsertions(self, s: str) -> int:
insertion_num, right_need = 0, 0
for i in range(len(s)):
if (s[i] == '('):
right_need += 2
if (right_need % 2 == 1):
# we insert a right bracket
right_need -= 1
insertion_num += 1
if(s[i] == ')'):
right_need -= 1
if (right_need == -1):
# we insert a left bracket
right_need += 2
insertion_num += 1
return insertion_num + right_need | minimum-insertions-to-balance-a-parentheses-string | Simple linear solution in Python | leqinancy | 0 | 11 | minimum insertions to balance a parentheses string | 1,541 | 0.499 | Medium | 22,807 |
https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/discuss/2589508/Python-Solution-w-comments | class Solution:
def minInsertions(self, s: str) -> int:
res = 0
stack = []
i = 0
h = { '(' : "))"}
# loop through string
while i < len(s):
curChar = s[i]
# if the char is (, we can just append, update idx and continue
if curChar == '(':
stack.append(curChar)
i += 1
continue
# if our char is closing, get next char
nextChar = (s[i+1] if i+1 < len(s) else 'a')
# if nextChar isn't closing, we need an insertion, if not we can skip next char so increment i
if nextChar != ')':
res += 1
else:
i += 1
# if something in stack, pop it, else we need an insertion, increment
if stack:
stack.pop()
else:
res += 1
i += 1
# all remaining opening in stack will need two closing, return res + len(stack) *2
return res + (len(stack) * 2) | minimum-insertions-to-balance-a-parentheses-string | Python Solution w/ comments | Mark5013 | 0 | 47 | minimum insertions to balance a parentheses string | 1,541 | 0.499 | Medium | 22,808 |
https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/discuss/2153339/Python-One-pass-(Stack) | class Solution:
def minInsertions(self, s: str) -> int:
stack = []
pointer = 0
ans = 0
slen = len(s)
while pointer < slen:
if s[pointer] == '(':
stack.append('(')
else:
if pointer+1 < len(s):
if s[pointer+1] == ')':
if stack:
stack.pop(-1)
pointer += 1
else:
ans += 1
pointer += 1
else:
if stack:
ans += 1
stack.pop(-1)
else:
ans += 2
else:
if stack:
stack.pop(-1)
ans += 1
else:
ans += 2
pointer += 1
ans += (2 * len(stack))
return ans | minimum-insertions-to-balance-a-parentheses-string | Python One pass (Stack) | DietCoke777 | 0 | 65 | minimum insertions to balance a parentheses string | 1,541 | 0.499 | Medium | 22,809 |
https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/discuss/1781276/one-pass-count-needs | class Solution:
def minInsertions(self, s: str) -> int:
res = 0
need = 0
for symbol in s:
if symbol == '(':
need += 2
if need % 2 == 1:
res += 1
need -=1
else:
need -= 1
if need == -1:
res += 1
need = 1
return res + need | minimum-insertions-to-balance-a-parentheses-string | one pass count needs | alexxu666 | 0 | 113 | minimum insertions to balance a parentheses string | 1,541 | 0.499 | Medium | 22,810 |
https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/discuss/1690349/Python3-One-pass-using-balance-count | class Solution:
def minInsertions(self, s: str) -> int:
balnum = 0 # balance number: 2*left - right
right = 0 # count num of consecutive right parenthesis
res = 0 # result: num of insertions
for c in s:
if c == '(':
# clean unbalanced right parenthesis
while balnum < 0:
balnum += 2
res += 1
# complement odd number of right parenthesis
if right % 2 != 0:
res += 1
balnum -= 1
right = 0
balnum += 2
elif c == ')':
right += 1
balnum -= 1
# clean unbalanced right parenthesis
while balnum < 0:
balnum += 2
res += 1
return res + balnum | minimum-insertions-to-balance-a-parentheses-string | [Python3] One pass using balance count | Rainyforest | 0 | 101 | minimum insertions to balance a parentheses string | 1,541 | 0.499 | Medium | 22,811 |
https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/discuss/1472355/Python-Easy-Solution | class Solution:
def minInsertions(self, s: str) -> int:
N = len(s)
add = 0
stack = []
i = 0
while i<N:
if s[i]=='(':
stack.append(s[i])
i += 1
else:
if not stack:
if i+1 < N and s[i+1] == ")": ## "))"
add +=1
i +=2
else: # ")"
add +=2
i +=1
else:
if i+1 < N and s[i+1] == ")": # case top of stack ( and closing "))"
i += 2
else:# case top of stack ( and closing ")" so we need to add 1 to make it ( ))
add += 1
i +=1
stack.pop()
# check the length of stack
if len(stack)>0:
add += len(stack)*2
return add | minimum-insertions-to-balance-a-parentheses-string | Python Easy Solution | swolecoder | 0 | 122 | minimum insertions to balance a parentheses string | 1,541 | 0.499 | Medium | 22,812 |
https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/discuss/1391512/Simple-python-solution-with-stack-and-without-counters. | class Solution:
def minInsertions(self, s: str) -> int:
stack = []
i = res = 0
while i < len(s):
if s[i] == '(':
stack.append('(')
i+=1
else:
# when s[i] == ')', we peek and s[i+1] and make decisions
if not stack:
stack.append('(')
res += 1
stack.pop()
j = i+1
if j < len(s) and s[j] == ')':
i += 2
else:
res += 1
i += 1
res += 2*len(stack)
return res | minimum-insertions-to-balance-a-parentheses-string | Simple python solution with stack and without counters. | worker-bee | 0 | 104 | minimum insertions to balance a parentheses string | 1,541 | 0.499 | Medium | 22,813 |
https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/discuss/784514/Python3-easy-and-concise | class Solution:
def minInsertions(self, s: str) -> int:
ans = op = cl = 0 #open & closed parentheses
i = 0
while i <= len(s):
if i == len(s) or s[i] == "(":
if cl:
ans += 1 #add an extra closing parenthesis
if op: op -= 1
else: ans += 1 #add an opening parenthesis
cl = 0
if i < len(s): op += 1
else:
cl += 1
if cl == 2:
if op: op -= 1
else: ans += 1 #add an opening parenthesis
cl = 0
i += 1
return ans + op*2 | minimum-insertions-to-balance-a-parentheses-string | [Python3] easy & concise | ye15 | 0 | 44 | minimum insertions to balance a parentheses string | 1,541 | 0.499 | Medium | 22,814 |
https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/discuss/781309/Python3-Time-O(n)-(100-Fast) | class Solution:
def minInsertions(self, s: str) -> int:
stack = []
ret = 0
for c in s:
if c == '(':
if stack and not stack[- 1]:
ret += 1
stack.pop()
stack.append(1)
else:
if not stack:
ret += 1
stack.append(1)
if stack[- 1]:
stack[- 1] -= 1
else:
stack.pop()
while stack:
ret += 1 + stack.pop()
return ret | minimum-insertions-to-balance-a-parentheses-string | [Python3] Time O(n) (100% Fast) | timetoai | 0 | 22 | minimum insertions to balance a parentheses string | 1,541 | 0.499 | Medium | 22,815 |
https://leetcode.com/problems/find-longest-awesome-substring/discuss/2259262/Python3-or-Prefix-xor-or-O(n)-Solution | class Solution:
def longestAwesome(self, s: str) -> int:
# li = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
li = [2**i for i in range(10)]
# checker = {0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512}
checker = set(li)
checker.add(0)
# di: k = prefix xor, v = the first idx I got a new prefix_xor_value.
di = collections.OrderedDict({0: -1})
maxLength = prefix_xor = 0
for i in range(len(s)):
prefix_xor ^= li[int(s[i])]
# Found a new prefix_xor_value
if prefix_xor not in di:
di[prefix_xor] = i
# XOR operation with previous prefix_xor_value
for key in di.keys():
if i - di[key] <= maxLength:
break
# s[di[key] : i] is Awesome Substring
if key ^ prefix_xor in checker:
maxLength = i - di[key]
return maxLength | find-longest-awesome-substring | Python3 | Prefix xor | O(n) Solution | shugokra | 1 | 75 | find longest awesome substring | 1,542 | 0.414 | Hard | 22,816 |
https://leetcode.com/problems/find-longest-awesome-substring/discuss/784632/Python3-prefix-xor | class Solution:
def longestAwesome(self, s: str) -> int:
ans = prefix = 0
seen = {0: -1}
for i, c in enumerate(s):
prefix ^= 1 << int(c) #toggle bit
ans = max(ans, i - seen.get(prefix, inf))
for k in range(10):
x = prefix ^ (1 << k) #toggle kth bit
ans = max(ans, i - seen.get(x, inf))
seen.setdefault(prefix, i)
return ans | find-longest-awesome-substring | [Python3] prefix xor | ye15 | 1 | 128 | find longest awesome substring | 1,542 | 0.414 | Hard | 22,817 |
https://leetcode.com/problems/make-the-string-great/discuss/781044/Python3-5-line-stack-O(N) | class Solution:
def makeGood(self, s: str) -> str:
stack = []
for c in s:
if stack and abs(ord(stack[-1]) - ord(c)) == 32: stack.pop() #pop "bad"
else: stack.append(c) #push "good"
return "".join(stack) | make-the-string-great | [Python3] 5-line stack O(N) | ye15 | 34 | 1,400 | make the string great | 1,544 | 0.633 | Easy | 22,818 |
https://leetcode.com/problems/make-the-string-great/discuss/781044/Python3-5-line-stack-O(N) | class Solution:
def makeGood(self, s: str) -> str:
stack = []
for c in s:
if stack and ord(stack[-1]) ^ ord(c) == 32: stack.pop() #pop "bad"
else: stack.append(c) #push "good"
return "".join(stack) | make-the-string-great | [Python3] 5-line stack O(N) | ye15 | 34 | 1,400 | make the string great | 1,544 | 0.633 | Easy | 22,819 |
https://leetcode.com/problems/make-the-string-great/discuss/2791272/Detailed-Explanation-of-the-Python-Solution-or-99-Faster | class Solution:
def makeGood(self, s: str) -> str:
stack = []
for i in range(len(s)):
if stack and stack[-1] == s[i].swapcase():
stack.pop()
else:
stack.append(s[i])
return ''.join(stack) | make-the-string-great | ✔️ Detailed Explanation of the Python Solution | 99% Faster 🔥 | pniraj657 | 10 | 384 | make the string great | 1,544 | 0.633 | Easy | 22,820 |
https://leetcode.com/problems/make-the-string-great/discuss/2793757/Python-O(1)-memory | class Solution:
def makeGood(self, s: str) -> str:
i = 0
while i < len(s) - 1:
if ord(s[i]) - ord(s[i + 1]) == 32 or ord(s[i]) - ord(s[i + 1]) == -32:
s = s[:i] + s[i + 2:]
if i > 0:
i -= 1
else:
i += 1
return s | make-the-string-great | Python O(1) memory | discregionals | 6 | 148 | make the string great | 1,544 | 0.633 | Easy | 22,821 |
https://leetcode.com/problems/make-the-string-great/discuss/2790787/Simple-Python-Solution-or-Faster-than-99.57-or-Stack-implementation | class Solution:
def makeGood(self, s: str) -> str:
st = []
for i in s:
if st:
if i.isupper() and st[-1].islower() and st[-1].upper() == i:
st.pop()
continue
elif i.islower() and st[-1].isupper() and st[-1].lower() == i:
st.pop()
continue
else:
st.append(i)
continue
else:
st.append(i)
continue
return "".join(st) | make-the-string-great | Simple Python Solution | Faster than 99.57% | Stack implementation | aniketbhamani | 2 | 168 | make the string great | 1,544 | 0.633 | Easy | 22,822 |
https://leetcode.com/problems/make-the-string-great/discuss/2792716/Easy-Solution-oror-One-Pass-oror-96-Faster | class Solution:
def makeGood(self, s: str) -> str:
idx =0
while(idx+1<len(s)):
if(abs(ord(s[idx])-ord(s[idx+1]))==32):
s= s[:idx]+s[idx+2:]
idx =0
else:
idx+=1
return s | make-the-string-great | Easy Solution || One Pass || 96% Faster | hasan2599 | 1 | 54 | make the string great | 1,544 | 0.633 | Easy | 22,823 |
https://leetcode.com/problems/make-the-string-great/discuss/2791148/Python3-or-Stack-or-Simple | class Solution:
def makeGood(self, s: str) -> str:
stack = []
i = 0
def check(s1, s2):
return abs(ord(s1)-ord(s2)) == 32
for i in range(len(s)):
if not stack:
stack.append(s[i])
continue
l = stack[-1]
r = s[i]
if check(l, r):
stack.pop()
continue
stack.append(r)
return "".join(stack) | make-the-string-great | Python3 | Stack | Simple | vikinam97 | 1 | 52 | make the string great | 1,544 | 0.633 | Easy | 22,824 |
https://leetcode.com/problems/make-the-string-great/discuss/2791148/Python3-or-Stack-or-Simple | class Solution:
def makeGood(self, s: str) -> str:
stack = []
i = 0
for i in range(len(s)):
if not stack:
stack.append(s[i])
continue
l = stack[-1]
r = s[i]
if (l.isupper() and l.lower() == r) or (l.islower() and l.upper() == r):
stack.pop()
continue
stack.append(r)
return "".join(stack) | make-the-string-great | Python3 | Stack | Simple | vikinam97 | 1 | 52 | make the string great | 1,544 | 0.633 | Easy | 22,825 |
https://leetcode.com/problems/make-the-string-great/discuss/2481561/Python-Stack-93.82-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Stack | class Solution:
def makeGood(self, s: str) -> str:
stack = [] # taking a empty stack.
for c in s: # traversing through the provided string.
if not stack: # if stack is empty then will push it else we wont be able to make comparisons of char.
stack.append(c) # pushing the char
elif stack[-1].isupper() and stack[-1].lower() == c: # if exsisting element in stack is in upper case, and lower case of last element of stack is equal to current char
result.pop() # implies we found adjacent char and will remove them.
elif stack[-1].islower() and stack[-1].upper() == c: # if exsisting element in stack is in lower case, and upper case of last element of stack is equal to current char
stack.pop() # implies we found adjacent char and will remove them.
else:
stack.append(c) # else its a diff element then the last one and we`ll add it in the stack.
return ''.join(stack) # using join bcz we have to make a list as a string. | make-the-string-great | Python Stack 93.82% faster | Simplest solution with explanation | Beg to Adv | Stack | rlakshay14 | 1 | 74 | make the string great | 1,544 | 0.633 | Easy | 22,826 |
https://leetcode.com/problems/make-the-string-great/discuss/2315090/Fast-Python-stack-O(n) | class Solution:
def makeGood(self, s: str) -> str:
stack=[]
for i in s:
if stack and stack[-1]==i.swapcase():
stack.pop()
else:
stack.append(i)
return "".join(stack) | make-the-string-great | Fast Python stack O(n) | sunakshi132 | 1 | 89 | make the string great | 1,544 | 0.633 | Easy | 22,827 |
https://leetcode.com/problems/make-the-string-great/discuss/1758967/Python-dollarolution | class Solution:
def makeGood(self, s: str) -> str:
i = 0
while i < len(s)-1:
if ord(s[i]) == ord(s[i+1]) + 32 or ord(s[i]) == ord(s[i+1]) - 32:
s = s[0:i] + s[i+2:]
i = 0
else:
i += 1
return s | make-the-string-great | Python $olution | AakRay | 1 | 55 | make the string great | 1,544 | 0.633 | Easy | 22,828 |
https://leetcode.com/problems/make-the-string-great/discuss/1115868/Python3-simple-solution | class Solution:
def makeGood(self, s: str) -> str:
i = 0
while i < len(s)-1:
if (s[i].upper() == s[i+1] or s[i] == s[i+1].upper()) and (s[i] != s[i+1]):
s = s[:i] + s[i+2:]
i = 0
else:
i += 1
return s | make-the-string-great | Python3 simple solution | EklavyaJoshi | 1 | 61 | make the string great | 1,544 | 0.633 | Easy | 22,829 |
https://leetcode.com/problems/make-the-string-great/discuss/1076769/Python-3 | class Solution:
def makeGood(self, s: str) -> str:
stack = []
for i in s:
if stack:
if stack[-1]== i :
stack.append(i)
elif stack[-1]==i.lower() or stack[-1]==i.upper():stack.pop()
else:stack.append(i)
else:stack.append(i)
return"".join(stack) | make-the-string-great | Python 3 | Pratyush1 | 1 | 59 | make the string great | 1,544 | 0.633 | Easy | 22,830 |
https://leetcode.com/problems/make-the-string-great/discuss/2796361/python-solution-using-stack | class Solution:
def makeGood(self, s: str) -> str:
stack = []
for i in s:
if stack and (ord(stack[-1])-ord(i) == 32 or ord(stack[-1])-ord(i) == -32):
stack.pop()
else:
stack.append(i)
return "".join(stack) | make-the-string-great | python solution using stack | muge_zhang | 0 | 1 | make the string great | 1,544 | 0.633 | Easy | 22,831 |
https://leetcode.com/problems/make-the-string-great/discuss/2795573/python-solution | class Solution:
def makeGood(self, s: str) -> str:
if len(s)==0:
return s
for t in range(100):
i=0
while i + 1 < len(s):
if abs(ord(s[i])-ord(s[i+1])) == 32 :
s = s[:i]+ s[i+2:]
else:
i+=1
return s | make-the-string-great | python solution | sindhu_300 | 0 | 2 | make the string great | 1,544 | 0.633 | Easy | 22,832 |
https://leetcode.com/problems/make-the-string-great/discuss/2794975/Easy-Python-Solution-for-Beginners | class Solution:
def makeGood(self, s: str) -> str:
test = []
for i in range(len(s)):
test.append(s[i])
i = 0
while(i<len(test)-1):
if(abs(ord(test[i])-ord(test[i+1])) == 32):
del test[i+1]
del test[i]
i = 0
continue
i+= 1
return "".join(test) | make-the-string-great | Easy Python Solution for Beginners | imash_9 | 0 | 1 | make the string great | 1,544 | 0.633 | Easy | 22,833 |
https://leetcode.com/problems/make-the-string-great/discuss/2794754/LC-Daily-Challenge%3A-A-simple-stack-based-solution | class Solution:
def makeGood(self, s: str) -> str:
stack = []
for c in s:
stack.append(c)
if len(stack) >= 2:
if ((stack[-1].isupper() and stack[-2].islower()) or (stack[-1].islower() and stack[-2].isupper())) and stack[-1].lower() == stack[-2].lower():
stack.pop()
stack.pop()
return ''.join(stack) | make-the-string-great | LC Daily Challenge: A simple stack based solution | echen12 | 0 | 1 | make the string great | 1,544 | 0.633 | Easy | 22,834 |
https://leetcode.com/problems/make-the-string-great/discuss/2794735/Python3-using-Ascii-code | class Solution:
def makeGood(self, s: str) -> str:
i = 0
while (i < len(s)-1):
if(len(s) > 1):
ascii1 = ord(s[i])
ascii2 = ord(s[i+1])
if(ascii1 + 32 == ascii2 or ascii1 - 32 == ascii2):
s = s[:i] + s[i+2:]
i = 0
else:
i += 1
return s | make-the-string-great | Python3 using Ascii code | farzanamou | 0 | 4 | make the string great | 1,544 | 0.633 | Easy | 22,835 |
https://leetcode.com/problems/make-the-string-great/discuss/2794444/Simple-Python | class Solution:
def makeGood(self, s: str) -> str:
i=1
while i<=len(s)-1:
if ord(s[i])+32==ord(s[i-1]):
s=(s[:i-1]+s[i+1:])
i=0
elif ord(s[i])==ord(s[i-1])+32:
s=(s[:i-1]+s[i+1:])
i=0
i+=1
return s | make-the-string-great | Simple Python | priyanshupriyam123vv | 0 | 1 | make the string great | 1,544 | 0.633 | Easy | 22,836 |
https://leetcode.com/problems/make-the-string-great/discuss/2794396/Python3-Convert-To-Integer-List | class Solution:
def makeGood(self, s: str) -> str:
i, n = 1, list(map(ord, s))
while i < len(n):
if i and n[i]^n[i-1] == 32:
del n[i]
del n[i-1]
i -= 2
i += 1
return "".join(map(chr, n)) | make-the-string-great | Python3 Convert To Integer List | godshiva | 0 | 4 | make the string great | 1,544 | 0.633 | Easy | 22,837 |
https://leetcode.com/problems/make-the-string-great/discuss/2794386/Python-3-or-Stack-solution | class Solution:
def makeGood(self, s: str) -> str:
stack = []
stack.append(s[0])
for i in range(1, len(s)):
if stack and abs(ord(stack[-1]) - ord(s[i])) == 32:
stack.pop()
else:
stack.append(s[i])
ans = ""
for ch in stack:
ans += ch
return ans | make-the-string-great | Python 3 | Stack solution | sweetkimchi | 0 | 4 | make the string great | 1,544 | 0.633 | Easy | 22,838 |
https://leetcode.com/problems/make-the-string-great/discuss/2794385/Python-3-or-Stack-solution | class Solution:
def makeGood(self, s: str) -> str:
stack = []
stack.append(s[0])
for i in range(1, len(s)):
if stack and abs(ord(stack[-1]) - ord(s[i])) == 32:
stack.pop()
else:
stack.append(s[i])
ans = ""
for ch in stack:
ans += ch
return ans | make-the-string-great | Python 3 | Stack solution | sweetkimchi | 0 | 2 | make the string great | 1,544 | 0.633 | Easy | 22,839 |
https://leetcode.com/problems/make-the-string-great/discuss/2794383/Easy-Python3-using-ascii-values-strings | class Solution:
def makeGood(self, s: str) -> str:
i=0
while i+1<len(s):
if abs(ord(s[i])-ord(s[i+1])) == 32:
s = s[:i]+s[i+2:]
i = 0
else :
i+=1
return s | make-the-string-great | Easy - Python3- using ascii values-strings | phanee16 | 0 | 1 | make the string great | 1,544 | 0.633 | Easy | 22,840 |
https://leetcode.com/problems/make-the-string-great/discuss/2794345/Python-clean-recursive-solution | class Solution:
def makeGood(self, s: str) -> str:
for i in range(0, len(s) - 1):
if s[i].lower() == s[i + 1].lower() and s[i] != s[i + 1]:
return self.makeGood(s.replace(s[i: i + 2], ""))
return s | make-the-string-great | Python clean recursive solution | POTATOSAUR | 0 | 2 | make the string great | 1,544 | 0.633 | Easy | 22,841 |
https://leetcode.com/problems/make-the-string-great/discuss/2794293/Python-Short-O(n)-solution-using-stack | class Solution:
def makeGood(self, s: str) -> str:
stack = []
for i in s:
if stack and stack[-1].lower() == i.lower() and stack[-1].islower() - i.islower() != 0:
stack.pop()
else:
stack.append(i)
return ''.join(stack) | make-the-string-great | [Python] Short O(n) solution using stack | Mark_computer | 0 | 4 | make the string great | 1,544 | 0.633 | Easy | 22,842 |
https://leetcode.com/problems/make-the-string-great/discuss/2794269/Beginner-Friendly-Easy-Python-Codes | class Solution:
def makeGood(self, s: str) -> str:
stack = []
for i in s:
if not stack:
stack.append(i)
elif stack[-1] != i and stack[-1].upper() == i.upper():
stack.pop()
else:
stack.append(i)
return "".join(stack) | make-the-string-great | 💯✔️ Beginner Friendly Easy Python Codes | ShauryaGopu | 0 | 2 | make the string great | 1,544 | 0.633 | Easy | 22,843 |
https://leetcode.com/problems/make-the-string-great/discuss/2794201/PythonPython3-Stack-approach-O(n)-greater-same-as-Valid-Parenthesis! | class Solution:
def makeGood(self, s: str) -> str:
# Time complexity: O(n) since we scan through every character once. we do it in 2 separated for loops
# which means O(n + n) -> O(2n) -> O(n)
# Space complexity: O(n) since we use a stack and it will be upto the size of input
stack = []
for let in s:
if stack:
if stack[-1].lower() == let.lower():
# Update: can also use stack[-1] == let.swapcase() instead of 2 conditionals
# if one of the elements is a lower and the other is upper, we know we found the
# bad letters, so remove both of them
if (stack[-1].isupper() and let.islower()) or (stack[-1].islower() and let.isupper()):
stack.pop()
continue
else:
stack.append(let)
continue
# if it is an empty stack, or the letters don't match, or if they're not upper/lower as
# expected, then we just add the variable
stack.append(let)
if not stack:
return ""
# concatonate all the values in the stack into a string
good_string = ""
for val in stack:
good_string += val
return good_string | make-the-string-great | [Python/Python3] Stack approach O(n) -> same as Valid Parenthesis! | NeoRider3663 | 0 | 5 | make the string great | 1,544 | 0.633 | Easy | 22,844 |
https://leetcode.com/problems/make-the-string-great/discuss/2794194/Runtime%3A-46-ms-faster-than-82.04-of-Python3 | class Solution:
def makeGood(self, s: str) -> str:
stack = []
for i in s:
if stack and i!=stack[-1] and i.lower()==stack[-1].lower():
stack = stack[:-1]
else:
stack.append(i)
return "".join(stack) | make-the-string-great | Runtime: 46 ms, faster than 82.04% of Python3 | shu8hamRajput | 0 | 1 | make the string great | 1,544 | 0.633 | Easy | 22,845 |
https://leetcode.com/problems/make-the-string-great/discuss/2794107/Python-straight-forward | class Solution:
def makeGood(self, s: str) -> str:
temp = list(s)
left = 1
while left < len(temp):
if (temp[left].isupper() and temp[left-1].islower()) and (temp[left].lower() == temp[left-1]):
del temp[left]
del temp[left-1]
left = 1
elif (temp[left].islower() and temp[left-1].isupper()) and (temp[left] == temp[left-1].lower()):
del temp[left]
del temp[left-1]
left = 1
else:
left += 1
return ''.join(temp) | make-the-string-great | Python straight forward | jnslee311 | 0 | 2 | make the string great | 1,544 | 0.633 | Easy | 22,846 |
https://leetcode.com/problems/make-the-string-great/discuss/2794069/So-well-this-solution-is-for-MAKE-THE-STRING-GREAT | class Solution:
def makeGood(self, s: str) -> str:
ans = []
for c in s:
if ans and abs(ord(ans[-1]) - ord(c)) == 32:
ans.pop()
else:
ans.append(c)
return "".join(ans) | make-the-string-great | So well this solution is for MAKE THE STRING GREAT | manchalasreekanth999 | 0 | 2 | make the string great | 1,544 | 0.633 | Easy | 22,847 |
https://leetcode.com/problems/make-the-string-great/discuss/2794066/Recursion-Python-3-(Complexity-could-be-improved) | class Solution:
def checklower(self,s:str)->bool:
for i in range(len(s)-1):
if (s[i].upper()==s[i+1] or s[i+1].upper()==s[i]) and (s[i]!=s[i+1]):
return False
return True
def makeGood(self, s: str) -> str:
if s=="" or self.checklower(s):
return s
for i in range(len(s)-1):
if (s[i].upper()==s[i+1] or s[i+1].upper()==s[i])and (s[i]!=s[i+1]):
val=s.replace(s[i]+s[i+1],"")
return self.makeGood(val) | make-the-string-great | Recursion Python 3 (Complexity could be improved) | SAI_KRISHNA_PRATHAPANENI | 0 | 2 | make the string great | 1,544 | 0.633 | Easy | 22,848 |
https://leetcode.com/problems/make-the-string-great/discuss/2793920/Simple-Solution | class Solution:
def makeGood(self, s: str) -> str:
ans=[s[0]]
for i in range(1,len(s)):
if ans and s[i].lower()==ans[-1].lower() and s[i]!=ans[-1]:
ans.pop()
else:
ans.append(s[i])
return "".join(ans) | make-the-string-great | Simple Solution | vedaditya | 0 | 2 | make the string great | 1,544 | 0.633 | Easy | 22,849 |
https://leetcode.com/problems/make-the-string-great/discuss/2793891/Python-oror-Easy-Stack-Solution-O(n) | class Solution:
def makeGood(self, s: str) -> str:
stack = []
stack.append(s[0])
for i, _ in enumerate(s[1:], start = 1):
# upper/lower cases of same letter yield a difference of +/-32
if stack and abs(ord(s[i]) - ord(stack[-1])) == 32:
stack.pop()
else:
# maintain our stack to not have a 'bad' string
stack.append(s[i])
return ''.join(stack) | make-the-string-great | Python || Easy Stack Solution O(n) | avgpersonlargetoes | 0 | 3 | make the string great | 1,544 | 0.633 | Easy | 22,850 |
https://leetcode.com/problems/make-the-string-great/discuss/2793866/Most-simple-and-easy-to-understand-solution. | class Solution:
def makeGood(self, s: str) -> str:
stack = []
for curr_char in list(s):
if stack and abs(ord(curr_char) - ord(stack[-1])) == 32:
stack.pop()
else:
stack.append(curr_char)
return "".join(stack) | make-the-string-great | Most simple and easy to understand solution. | namanjawaliya | 0 | 1 | make the string great | 1,544 | 0.633 | Easy | 22,851 |
https://leetcode.com/problems/make-the-string-great/discuss/2793812/Make-the-string-Great-lessgreater | class Solution:
def makeGood(self, s: str) -> str:
i=0
while i<len(s)-1:
if s[i].islower() and s[i+1].isupper():
if s[i].upper()==s[i+1]:
s=s[:i]+s[i+2:]
i=0
else:
i+=1
elif s[i].isupper() and s[i+1].islower():
if s[i]==s[i+1].upper():
s=s[:i]+s[i+2:]
i=0
else:
i+=1
else:
i+=1
return s | make-the-string-great | Make the string Great </> | shivansh2001sri | 0 | 2 | make the string great | 1,544 | 0.633 | Easy | 22,852 |
https://leetcode.com/problems/make-the-string-great/discuss/2793798/Make-the-String-Great-or-PYTHON | class Solution:
def makeGood(self, s: str) -> str:
l=list(s)
lower="abcdefghijklmnopqrstuvwxyz"
upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
while(True):
if len(l)==0:
break
i=0
f=0
while(i<len(l)-1):
if l[i] in lower:
if l[i+1] in upper:
if lower.index(l[i])==upper.index(l[i+1]):
l.pop(i)
l.pop(i)
f=1
break
else:
i+=1
else:
i+=1
else:
if l[i+1] in lower:
if upper.index(l[i])==lower.index(l[i+1]):
l.pop(i)
l.pop(i)
f=1
break
else:
i+=1
else:
i+=1
if f==0:
break
return "".join(l) | make-the-string-great | Make the String Great | PYTHON | saptarishimondal | 0 | 3 | make the string great | 1,544 | 0.633 | Easy | 22,853 |
https://leetcode.com/problems/make-the-string-great/discuss/2793741/Python-Easy-Solution | class Solution:
def makeGood(self, s: str) -> str:
num = ['qQ', 'wW', 'eE', 'rR', 'tT', 'yY', 'uU', 'iI', 'oO', 'pP', 'aA', 'sS', 'dD', 'fF', 'gG', 'hH', 'jJ', 'kK', 'lL', 'zZ', 'xX', 'cC', 'vV', 'bB', 'nN', 'mM', 'Qq', 'Ww', 'Ee', 'Rr', 'Tt', 'Yy', 'Uu', 'Ii', 'Oo', 'Pp', 'Aa', 'Ss', 'Dd', 'Ff', 'Gg', 'Hh', 'Jj', 'Kk', 'Ll', 'Zz', 'Xx', 'Cc', 'Vv', 'Bb', 'Nn', 'Mm']
while any(substring in s for substring in num):
for substring in num:
s = s.replace(substring, '')
return s | make-the-string-great | Python - Easy Solution | khubaibalam2000 | 0 | 2 | make the string great | 1,544 | 0.633 | Easy | 22,854 |
https://leetcode.com/problems/make-the-string-great/discuss/2793688/Python-or-Stack-or-Custom-function-to-check-the-case | class Solution:
def makeGood(self, s: str) -> str:
def ofDifferentCases(ch1, ch2):
if ch1 == ch2:
return False
return ch1.lower() == ch2.lower()
stack = ['#']
for char in s:
if ofDifferentCases(stack[-1], char):
stack.pop()
else:
stack.append(char)
return ''.join(stack[1:]) | make-the-string-great | Python | Stack | Custom function to check the case | kamleshbp | 0 | 1 | make the string great | 1,544 | 0.633 | Easy | 22,855 |
https://leetcode.com/problems/make-the-string-great/discuss/2793652/Bad-O(n*b)-Python-Solution-Better-One-Pass-O(n)-Solution-Found | class Solution:
def makeGood(self, s: str) -> str:
bad_letters = True
while bad_letters:
bad_letters = False
i = 0
while i < len(s)-1:
if s[i].isupper() and s[i].lower() == s[i+1] \
or s[i].islower() and s[i].upper() == s[i+1]:
bad_letters = True
s = s[:i:] + s[i+2::]
i += 1
return s | make-the-string-great | Bad O(n*b) Python Solution, Better One-Pass O(n) Solution Found | jessewalker2010 | 0 | 5 | make the string great | 1,544 | 0.633 | Easy | 22,856 |
https://leetcode.com/problems/make-the-string-great/discuss/2793652/Bad-O(n*b)-Python-Solution-Better-One-Pass-O(n)-Solution-Found | class Solution:
def makeGood(self, s: str) -> str:
aux_string = ''
for char in s:
if not aux_string:
aux_string += char
elif char.isupper() and char.lower() == aux_string[-1] \
or char.islower() and char.upper() == aux_string[-1]:
aux_string = aux_string[:-1:]
else:
aux_string += char
return aux_string | make-the-string-great | Bad O(n*b) Python Solution, Better One-Pass O(n) Solution Found | jessewalker2010 | 0 | 5 | make the string great | 1,544 | 0.633 | Easy | 22,857 |
https://leetcode.com/problems/make-the-string-great/discuss/2793604/Python3-Solution-with-using-stack | class Solution:
def makeGood(self, s: str) -> str:
stack = []
for char in s:
if stack and stack[-1] != char and (stack[-1] == char.lower() or stack[-1] == char.upper()):
stack.pop()
else:
stack.append(char)
return ''.join(stack) | make-the-string-great | [Python3] Solution with using stack | maosipov11 | 0 | 5 | make the string great | 1,544 | 0.633 | Easy | 22,858 |
https://leetcode.com/problems/make-the-string-great/discuss/2793554/Simple-stack-solution-using-swapcase()-beats-78 | class Solution:
def makeGood(self, s: str) -> str:
stack = []
for c in s:
if stack and stack[-1].swapcase() == c:
stack.pop()
continue
stack.append(c)
return ''.join(stack) | make-the-string-great | Simple stack solution using swapcase() beats 78% | naubull2 | 0 | 2 | make the string great | 1,544 | 0.633 | Easy | 22,859 |
https://leetcode.com/problems/make-the-string-great/discuss/2793328/Simple-Python-Solution-or-Stack | class Solution:
def makeGood(self, s: str) -> str:
# print(chr(ord('A')+32))
stack=[]
for char in s:
if stack:
if stack[-1]==chr(ord(char)-32) or stack[-1]==chr(ord(char)+32):
stack.pop()
else:
stack.append(char)
else:
stack.append(char)
return "".join(stack) | make-the-string-great | Simple Python Solution | Stack | Siddharth_singh | 0 | 1 | make the string great | 1,544 | 0.633 | Easy | 22,860 |
https://leetcode.com/problems/make-the-string-great/discuss/2793246/Easy-Python-Stack | class Solution:
def makeGood(self, s: str) -> str:
ans = []
i = 0
while i<len(s):
while i<len(s) and ans and (ord(ans[-1]) == ord(s[i])+32 or ord(ans[-1])+32 == ord(s[i])):
ans.pop()
i+=1
if i < len(s):
ans.append(s[i])
i+=1
return "".join(ans) | make-the-string-great | Easy Python Stack | aazad20 | 0 | 2 | make the string great | 1,544 | 0.633 | Easy | 22,861 |
https://leetcode.com/problems/make-the-string-great/discuss/2793244/PYTHON-SOLUTION-oror-EASY-STACK | class Solution:
def makeGood(self, s: str) -> str:
st,ans,i=[],"",0
while i < len(s):
if st == []:
st.append(s[i])
# use this
elif st!=[] and abs(ord(s[i])-ord(st[-1]))==32:
st.pop()
else:
st.append(s[i])
<!-- #elif st!=[] and s[i].islower() == True:
#if st[-1].isupper() == True:
#if st[-1].lower() == s[i]:
# st.pop()
#else:
# st.append(s[i])
#else:
# st.append(s[i])
#elif st!=[] and s[i].isupper()== True:
#if st[-1].islower() == True :
# if st[-1].upper() == s[i]:
# st.pop()
# else:
# st.append(s[i])
#else:
# st.append(s[i]) -->
i+=1
if st == []:
return ""
ans = ans.join(st)
return ans | make-the-string-great | PYTHON SOLUTION || EASY STACK | cheems_ds_side | 0 | 5 | make the string great | 1,544 | 0.633 | Easy | 22,862 |
https://leetcode.com/problems/make-the-string-great/discuss/2793207/Easy-solution-with-python | class Solution:
def makeGood(self, s: str) -> str:
# solve easily with stack
# create empty stack
stack = []
#iterate each character in a string
for val in s:
# if stack has elements and last value in stack
# is equal to current val, remove the last element
# in the stack
if stack and abs(ord(val) - ord(stack[-1])) == 32:
stack.pop()
# if stack is empty or current value is not upper/lower
# case representation of last element of stack, add
# the element to stack
else:
stack.append(val)
return "".join(stack) | make-the-string-great | Easy solution with python | ratva0717 | 0 | 3 | make the string great | 1,544 | 0.633 | Easy | 22,863 |
https://leetcode.com/problems/make-the-string-great/discuss/2793178/Python-oror-Easily-Understood-oror-Fast-oror-Simple | class Solution:
def makeGood(self, s: str) -> str:
ans = []
for i in s:
if ans:
print(i,"-",ord(ans[-1]),"-",ord(i),"-",abs(ord(ans[-1])-ord(i)))
if ans and abs(ord(ans[-1])-ord(i))==32:
ans.pop(-1)
else:
ans.append(i)
return ''.join(ans) | make-the-string-great | ✅ Python || Easily Understood || Fast || Simple 🔥 | Marie-99 | 0 | 6 | make the string great | 1,544 | 0.633 | Easy | 22,864 |
https://leetcode.com/problems/make-the-string-great/discuss/2793166/Simple-python-solution-by-using-stack. | class Solution:
def makeGood(self, s: str) -> str:
stack = []
for a in s:
if len(stack) == 0:
stack.append(a)
continue
if (stack[-1].lower() == a.lower()) and ((stack[-1].isupper() and a.islower()) or (stack[-1].islower() and a.isupper())):
stack.pop()
else:
stack.append(a)
string = ''
while len(stack) != 0:
string = stack.pop() + string
return string | make-the-string-great | Simple python solution by using stack. | Tonmoy-saha18 | 0 | 5 | make the string great | 1,544 | 0.633 | Easy | 22,865 |
https://leetcode.com/problems/make-the-string-great/discuss/2793139/Easy-Python-Solution-using-Stack | class Solution:
def makeGood(self, s: str) -> str:
stack = []
for char in s:
if stack and stack[-1] == char.swapcase():
stack.pop()
else:
stack.append(char)
return ''.join(stack) | make-the-string-great | Easy Python Solution using Stack | jagdtri2003 | 0 | 3 | make the string great | 1,544 | 0.633 | Easy | 22,866 |
https://leetcode.com/problems/make-the-string-great/discuss/2793091/Python3-Solution | class Solution:
def makeGood(self, s: str) -> str:
ss = []
for c in s:
if ss and ss[-1] == c.swapcase(): # if the stack is not empty and the last letter on the stack is
ss.pop() # a match for the current letter (e.g., 'a' and 'A'), remove both
else:
ss.append(c) # continue adding to stack to compare with next letter
return "".join(ss) | make-the-string-great | Python3 Solution | avs-abhishek123 | 0 | 1 | make the string great | 1,544 | 0.633 | Easy | 22,867 |
https://leetcode.com/problems/make-the-string-great/discuss/2793009/Python-3-Stack-Solution-O(N)-7-lines | class Solution:
def makeGood(self, s: str) -> str:
stk = ['#']
for c in s:
if c.upper() == stk[-1].upper() and c != stk[-1]:
stk.pop()
else:
stk.append(c)
return ''.join(stk[1:]) | make-the-string-great | Python 3 Stack Solution / O(N) / 7 lines | zaynefn | 0 | 2 | make the string great | 1,544 | 0.633 | Easy | 22,868 |
https://leetcode.com/problems/make-the-string-great/discuss/2792931/Python3-80-faster | class Solution:
def makeGood(self, s: str) -> str:
s = list(s)
stack = []
while s:
x = s.pop()
if stack and abs(ord(x) - ord(stack[-1])) == 32: stack.pop()
else: stack.append(x)
return ''.join(stack[::-1]) | make-the-string-great | Python3 80% faster | Coaspe | 0 | 1 | make the string great | 1,544 | 0.633 | Easy | 22,869 |
https://leetcode.com/problems/make-the-string-great/discuss/2792907/Accepted-Simplest-Solution-in-Python | class Solution:
def makeGood(self, s: str) -> str:
stack=[]
for i in s:
if len(stack)==0:
stack.append(i)
continue
if abs(ord(stack[-1])-ord(i))==32:
stack.pop()
else:
stack.append(i)
return "".join(stack) | make-the-string-great | Accepted 💯 Simplest Solution in Python ✅ | adarshg04 | 0 | 1 | make the string great | 1,544 | 0.633 | Easy | 22,870 |
https://leetcode.com/problems/make-the-string-great/discuss/2792816/Python-Simple-Python-Solution-Using-Stack | class Solution:
def makeGood(self, s: str) -> str:
stack = []
for char in s:
if not stack:
stack.append(char)
else:
top = stack[-1]
if char != top and (char.upper() == top or char == top.upper()):
stack.pop(-1)
else:
stack.append(char)
return ''.join(stack) | make-the-string-great | [ Python ] ✅✅ Simple Python Solution Using Stack🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 11 | make the string great | 1,544 | 0.633 | Easy | 22,871 |
https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/781062/Python3-4-line-recursive | class Solution:
def findKthBit(self, n: int, k: int) -> str:
if k == 1: return "0"
if k == 2**(n-1): return "1"
if k < 2**(n-1): return self.findKthBit(n-1, k)
return "0" if self.findKthBit(n-1, 2**n-k) == "1" else "1" | find-kth-bit-in-nth-binary-string | [Python3] 4-line recursive | ye15 | 11 | 432 | find kth bit in nth binary string | 1,545 | 0.583 | Medium | 22,872 |
https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/2091929/Python-4-Lines-or-Simple-Solution | class Solution:
def findKthBit(self, n: int, k: int) -> str:
i, s, hash_map = 1, '0', {'1': '0', '0': '1'}
for i in range(1, n):
s = s + '1' + ''.join((hash_map[i] for i in s))[::-1]
return s[k-1] | find-kth-bit-in-nth-binary-string | Python 4 Lines | Simple Solution | Nk0311 | 1 | 85 | find kth bit in nth binary string | 1,545 | 0.583 | Medium | 22,873 |
https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/1801801/Python-Easy-understanding-solution | class Solution:
def findKthBit(self, n: int, k: int) -> str:
s1 = '0'
for i in range(1, n+1):
a = self.invert_reverse(s1)
s1 = (s1 + '1' + a)
a = s1
return s1[k-1]
def invert_reverse(self, s):
ans = ''
for i in range(len(s)):
if s[i] == '0':
ans += '1'
elif s[i] == '1':
ans += '0'
return ans[::-1] | find-kth-bit-in-nth-binary-string | Python Easy understanding solution | pandeypankaj219 | 1 | 74 | find kth bit in nth binary string | 1,545 | 0.583 | Medium | 22,874 |
https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/1449260/Python3-solution | class Solution:
def findKthBit(self, n: int, k: int) -> str:
if n == 1:
return "0"
i = 1
s = '0'
while i < n:
z = s + '1'
s = s.replace('0',',').replace('1','0').replace(',','1')
z += s[::-1]
i += 1
s = z
return s[k-1] | find-kth-bit-in-nth-binary-string | Python3 solution | EklavyaJoshi | 1 | 44 | find kth bit in nth binary string | 1,545 | 0.583 | Medium | 22,875 |
https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/2835948/Python3-Solution-or-Clean-and-Concise-or-O(n) | class Solution:
def findKthBit(self, N, K, R = True):
if K == 1: return '0' if R else '1'
mid = (1 << (N - 1))
if K < mid: return self.findKthBit(N - 1, K, R)
if K > mid: return self.findKthBit(N - 1, 2 * mid - K, not R)
return '1' if R else '0' | find-kth-bit-in-nth-binary-string | ✔ Python3 Solution | Clean & Concise | O(n) | satyam2001 | 0 | 2 | find kth bit in nth binary string | 1,545 | 0.583 | Medium | 22,876 |
https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/2835948/Python3-Solution-or-Clean-and-Concise-or-O(n) | class Solution:
def findKthBit(self, N, K):
ans = 1
mid = (1 << (N - 1))
while K > 1:
if K == mid: return str(ans)
if K > mid:
K = 2 * mid - K
ans ^= 1
mid >>= 1
return str(ans^1) | find-kth-bit-in-nth-binary-string | ✔ Python3 Solution | Clean & Concise | O(n) | satyam2001 | 0 | 2 | find kth bit in nth binary string | 1,545 | 0.583 | Medium | 22,877 |
https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/2794206/python-Recursive-solution-with-O(logn)-complexity | class Solution:
def findKthBit(self, n: int, k: int) -> str:
def highestPowerOf2(n):
return math.pow(2, int(math.log(n,2)))
def findKthBit(k):
if(k==0): return 0
if(k==1): return 1
t = highestPowerOf2(k)
if t*2-1==k: return 1
d = k - (t-1)
return 1 if findKthBit(t-d-1)==0 else 0
return str(findKthBit(k-1)) | find-kth-bit-in-nth-binary-string | [python] Recursive solution with O(logn) complexity | snr2718 | 0 | 3 | find kth bit in nth binary string | 1,545 | 0.583 | Medium | 22,878 |
https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/2793224/Simple-solution-in-python | class Solution:
def findKthBit(self, n: int, k: int) -> str:
binary = '0'
for a in range(1, n):
binary += '1' + self.invert(list(binary))[::-1]
return binary[k-1]
def invert(self, ls):
for i in range(len(ls)):
if ls[i] == '0':
ls[i] = '1'
else:
ls[i] = '0'
return ''.join(ls) | find-kth-bit-in-nth-binary-string | Simple solution in python | Tonmoy-saha18 | 0 | 3 | find kth bit in nth binary string | 1,545 | 0.583 | Medium | 22,879 |
https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/2791397/Python3-oror-Easy-Solution | class Solution:
def findKthBit(self, n: int, k: int) -> str:
totalLen = 2**n-1
invert = 0
while(totalLen>1):
m = (totalLen+1)//2
if(k==m):
invert+=1
break
elif(k>m):
invert+=1
k = totalLen-k+1
totalLen = m-1
return str(invert%2) | find-kth-bit-in-nth-binary-string | Python3 || Easy Solution | ty2134029 | 0 | 4 | find kth bit in nth binary string | 1,545 | 0.583 | Medium | 22,880 |
https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/2745340/Python-Recursive-Approach | class Solution:
S = '0'
Kn = 1
def invertB(self,bit_s):
inverse_s = ''
for i in bit_s:
if i == '0':
inverse_s += '1'
else:
inverse_s += '0'
return inverse_s
def findString(self, n: int):
if n == 1 or len(self.S) >= self.Kn:
return
self.S = self.S + '1' + self.invertB(self.S)[::-1]
self.findString(n-1)
def findKthBit(self, n: int, k: int) -> str:
self.Kn = k
self.findString(n)
print(self.S)
return self.S[k-1] | find-kth-bit-in-nth-binary-string | Python Recursive Approach | amanjhurani5 | 0 | 6 | find kth bit in nth binary string | 1,545 | 0.583 | Medium | 22,881 |
https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/2426800/Python3-or-Getting-TLE-Cause-My-Solution-is-O(n2)-Any-Way-to-Improve | class Solution:
def findKthBit(self, n: int, k: int) -> str:
#generate helper function will get the Sn!
#since I am facing issue with max rec. stack depth, I will simply do
#bottom-up dp!
def generate(n):
#dp table
dp = [None] * (n+1)
#add dp-base
dp[1] = "0"
def invert(s):
for i in range(len(s)):
s = s[:i] + "0" + s[i+1:] if s[i] == "1" else s[:i] + "1" + s[i+1:]
return s
#iterate through from i = 2 to n and construct each si and store in dp for future ref!
for i in range(2, n+1):
ans = ""
former = dp[i-1]
ans += former
ans += "1"
#get the reversed version of inverted si-1 string!
latter = invert(former)[::-1]
ans += latter
#store in dp the ans for current i as si!
dp[i] = ans
return dp[n]
overall_string = generate(n)
#kth bit should be at index k-1! For example, 5th bit should be at index 4 since string is
#0-indexed!
return overall_string[k-1] | find-kth-bit-in-nth-binary-string | Python3 | Getting TLE Cause My Solution is O(n^2) Any Way to Improve? | JOON1234 | 0 | 13 | find kth bit in nth binary string | 1,545 | 0.583 | Medium | 22,882 |
https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/2426769/Python3-or-Why-Recursion-Depth-Exceeded-Even-With-Memoization-Added | class Solution:
def findKthBit(self, n: int, k: int) -> str:
#generate helper function will get the Sn!
def generate(n, memo):
#base case for memoization: if we already know the Sn, refer to memo!
if(n in memo):
return memo[n]
#base case: n == 1 and k == 1
if(n == 1 and k == 1):
return "0"
ans = ""
former = generate(n-1, memo)
ans += former
ans += "1"
def invert(s):
for i in range(len(s)):
s = s[:i] + "0" + s[i+1:] if s[i] == "1" else s[:i] + "1" + s[i+1:]
return s
latter = invert(former)[::-1]
ans += latter
#make a memo!
memo[n] = ans
return ans
overall_string = generate(n, {})
#kth bit should be at index k-1! For example, 5th bit should be at index 4 since string is
#0-indexed!
return overall_string[k-1] | find-kth-bit-in-nth-binary-string | Python3 | Why Recursion Depth Exceeded Even With Memoization Added? | JOON1234 | 0 | 8 | find kth bit in nth binary string | 1,545 | 0.583 | Medium | 22,883 |
https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/1848025/Pyhton3-Solution | class Solution:
def invert(self, s) -> str:
res=""
for i in s:
if i=='0':
res+='1'
else:
res+='0'
return res[::-1]
def findbits(self, n) -> str:
if n==0:
return '0'
si1=self.findbits(n-1)
si1r=self.invert(si1)
si=si1+'1'+si1r
return si
def findKthBit(self, n: int, k: int) -> str:
s=self.findbits(n)
return s[k-1] | find-kth-bit-in-nth-binary-string | Pyhton3 Solution | eaux2002 | 0 | 51 | find kth bit in nth binary string | 1,545 | 0.583 | Medium | 22,884 |
https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/1759728/Python-very-simple-recursive-solution | class Solution:
def findKthBit(self, n: int, k: int) -> str:
invert = {"0":"1", "1":"0"}
def helper(n, k): # 0 <= k <= n-1
mid = 2**(n-1) -1
if n == 0:
return "0"
elif n == 1:
return "011"[k]
elif k == mid:
return "1"
elif k < mid:
return helper(n-1, k)
else: # k> mid
return invert[helper(n, 2*mid-k)]
return helper(n, k-1) | find-kth-bit-in-nth-binary-string | Python very simple recursive solution | byuns9334 | 0 | 54 | find kth bit in nth binary string | 1,545 | 0.583 | Medium | 22,885 |
https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/1697685/With-comments-to-understand-using-Recursion-and-Python | class Solution:
def findKthBit(self, n: int, k: int) -> str:
# print(n,k)
if(n == 1):
return '0'
mid = (2**n)//2
if(k == mid):
return "1"
if(k < mid):
return self.findKthBit(n-1,k)
else:
# return opp of val since k is greater than mid
val = self.findKthBit(n-1,(2**n) - k)
if(val == '0'):
return '1'
else:
return '0' | find-kth-bit-in-nth-binary-string | With comments to understand using Recursion and Python | jagdishpawar8105 | 0 | 69 | find kth bit in nth binary string | 1,545 | 0.583 | Medium | 22,886 |
https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/1503092/Python3-Recursion-with-Detailed-Explanation-and-Example | class Solution:
def findKthBit(self, n: int, k: int) -> str:
# Recursion
# Time: O(n)
# ----------------------------------------------
# Observation 1 (not useful observation)
# Si has length of 2**n-1
# s1: len=1 (2-1)
# s2: len=3 (2-1)*2+1 = (2^2-2)+1 = 2^2-1
# s3: len=4 (2^2-1)*2+1 = (2^3-2)+1 = 2^3-1
# ----------------------------------------------
# Observation 2
# Find k-th bit in n-th binary string can be break down into
# => Find k-th bit in (n-1)-th binary string if k < midpoint of n-th binary string (= 2**(n-1))
# => "1" if k = midpoint
# => Find (2**n - k) bit in (n-1)-th binary string with all bits inverted (0<->1) if k > midpoint
# e.g., n=4, k=11 => midpoint=8
# => k>midpoint (11>8)
# => find 11-th in 4-th binary string
# is equivalent to find 5-th in 3-th binary string with bit-inverted
# ----------------------------------------------
# Example
# recursion(4, 11, 0)
# recursion(3, 5, 1)
# recursion(2, 3, 0)
# recursion(1, 1, 1)
def recursion(n, k, flip):
print(n, k, flip)
if n == 1:
return "1" if flip else "0"
mid = 2**(n-1)
if mid == k:
return "0" if flip else "1"
elif k < mid:
return recursion(n-1, k, flip)
else: # k > mid (flip and reverse)
return recursion(n-1, 2**n-k, 1-flip)
return recursion(n, k, 0) | find-kth-bit-in-nth-binary-string | Python3 - Recursion with Detailed Explanation & Example | tkuo-tkuo | 0 | 68 | find kth bit in nth binary string | 1,545 | 0.583 | Medium | 22,887 |
https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/1326318/BruteForce | class Solution:
def findKthBit(self, n: int, k: int) -> str:
def helper(n):
if n==1:
return "0"
x = helper(n-1)
y = x.replace("1","2").replace("0","1").replace("2","0")[::-1]
return x + "1" + y
s = helper(n)
return s[k-1] | find-kth-bit-in-nth-binary-string | BruteForce | abhijeetgupto | 0 | 49 | find kth bit in nth binary string | 1,545 | 0.583 | Medium | 22,888 |
https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/902062/python3-brute-force-for-everyday-mortals | class Solution:
def findKthBit(self, n: int, k: int) -> str:
# build the sequence (brute force), do it n-1 times
# use XOR for quick inversion vs. bit by bit
# grow string per rules, grow mask to length of string
# O(N) time, O(S) space
s, mask = "0", "1"
for i in range(n-1):
inv = int(s, 2) ^ int(mask, 2)
s = s + "1" + "{:b}".format(inv)[::-1]
mask += "1" * (len(s) - len(mask))
return s[k-1] | find-kth-bit-in-nth-binary-string | python3 - brute force for everyday mortals | dachwadachwa | 0 | 43 | find kth bit in nth binary string | 1,545 | 0.583 | Medium | 22,889 |
https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/781588/Python3-Solution | class Solution:
def findKthBit(self, n: int, k: int) -> str:
def invert(bin):
bin = list(bin)
for i in range(len(bin)):
if bin[i] == '1':
bin[i] = '0'
else:
bin[i] = '1'
return ''.join(bin)
bin_n = bin(n)[2:]
dp = ['0'] * n
for i in range(1,n):
dp[i] = dp[i-1] + '1' + invert(dp[i-1])[::-1]
return dp[-1][k-1] | find-kth-bit-in-nth-binary-string | [Python3] Solution | pratushah | 0 | 46 | find kth bit in nth binary string | 1,545 | 0.583 | Medium | 22,890 |
https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/781005/python3-recursion-(raw-from-contest-ideas-in-comments) | class Solution:
def findKthBit(self, n: int, k: int) -> str:
'''
length pattern:
1-1
2-2*1+1=3=2**2-1
3-2*3+1=7=2**3-1
4-2*7+1=15=16-1=2**4-1
n-2**n-1
k-th bit:
k<2**(n-1)
'''
def helper(n,k):
if n==1:
return 0
elif k==2**(n-1):
return 1
elif k<2**(n-1):
return helper(n-1,k)
else:
return 1-helper(n-1,2**(n-1)-(k-2**(n-1)))
return str(helper(n,k)) | find-kth-bit-in-nth-binary-string | python3 recursion (raw from contest, ideas in comments) | strawberry_rain | 0 | 43 | find kth bit in nth binary string | 1,545 | 0.583 | Medium | 22,891 |
https://leetcode.com/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/discuss/781075/Python3-O(N)-prefix-sum | class Solution:
def maxNonOverlapping(self, nums: List[int], target: int) -> int:
ans = prefix = 0
seen = set([0]) #prefix sum seen so far ()
for i, x in enumerate(nums):
prefix += x
if prefix - target in seen:
ans += 1
seen.clear() #reset seen
seen.add(prefix)
return ans | maximum-number-of-non-overlapping-subarrays-with-sum-equals-target | [Python3] O(N) prefix sum | ye15 | 2 | 54 | maximum number of non overlapping subarrays with sum equals target | 1,546 | 0.472 | Medium | 22,892 |
https://leetcode.com/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/discuss/1896049/Python-Greedy-Solution-(Subarray-sum-equals-k-%2B-Non-overlapping-intervals) | class Solution:
def maxNonOverlapping(self, nums: List[int], target: int) -> int:
d = {0:0}
rangeListF = []
sm = 0
for i in range(len(nums)):
sm += nums[i]
if sm - target in d:
if len(rangeListF) == 0 or d[sm - target] > rangeListF[-1][1]:
rangeListF.append([d[sm - target], i])
else:
pass
d[sm] = i+1
return len(rangeListF) | maximum-number-of-non-overlapping-subarrays-with-sum-equals-target | Python Greedy Solution (Subarray sum equals k + Non overlapping intervals) | DietCoke777 | 0 | 88 | maximum number of non overlapping subarrays with sum equals target | 1,546 | 0.472 | Medium | 22,893 |
https://leetcode.com/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/discuss/1800930/Simple-Python-Solution | class Solution:
def maxNonOverlapping(self, nums: List[int], target: int) -> int:
d={}
d[0]=-1
idx=-1
current_sum=0
count=0
for i in range(len(nums)):
current_sum+=nums[i]
if ((current_sum - target) in d) and (d[current_sum-target]>=idx):
count+=1
idx=i
d[current_sum]=i
return count | maximum-number-of-non-overlapping-subarrays-with-sum-equals-target | Simple Python Solution | Siddharth_singh | 0 | 114 | maximum number of non overlapping subarrays with sum equals target | 1,546 | 0.472 | Medium | 22,894 |
https://leetcode.com/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/discuss/1740750/WEEB-DOES-PYTHON-DPPREFIX-SUM-(BEATS-97.37) | class Solution:
def maxNonOverlapping(self, nums: List[int], target: int) -> int:
dp = defaultdict(int)
dp[0] = 1
curSum = 0
result = 0
for i in range(len(nums)):
curSum += nums[i]
if curSum - target in dp:
result += dp[curSum-target]
dp = defaultdict(int)
dp[0] = 1
curSum = 0
dp[curSum] = 1
return result | maximum-number-of-non-overlapping-subarrays-with-sum-equals-target | WEEB DOES PYTHON DP/PREFIX SUM (BEATS 97.37%) | Skywalker5423 | 0 | 82 | maximum number of non overlapping subarrays with sum equals target | 1,546 | 0.472 | Medium | 22,895 |
https://leetcode.com/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/discuss/1444050/Python-simple-solution%3A-O(n)-time-O(n)-space | class Solution:
def maxNonOverlapping(self, nums: List[int], target: int) -> int:
moddict = {}
moddict[0] = 0
res = 0 # value to be returned
cnt = 1
s = 0
for num in nums:
s += num
if s-target in moddict:
res += 1
moddict = {}
moddict[s] = cnt
cnt += 1
return res | maximum-number-of-non-overlapping-subarrays-with-sum-equals-target | Python simple solution: O(n) time, O(n) space | byuns9334 | 0 | 150 | maximum number of non overlapping subarrays with sum equals target | 1,546 | 0.472 | Medium | 22,896 |
https://leetcode.com/problems/minimum-cost-to-cut-a-stick/discuss/781085/Python3-top-down-and-bottom-up-dp | class Solution:
def minCost(self, n: int, cuts: List[int]) -> int:
@lru_cache(None)
def fn(lo, hi):
"""Return cost of cutting [lo, hi]."""
cc = [c for c in cuts if lo < c < hi] #collect cuts within this region
if not cc: return 0
ans = inf
for mid in cc: ans = min(ans, fn(lo, mid) + fn(mid, hi))
return ans + hi - lo
return fn(0, n) | minimum-cost-to-cut-a-stick | [Python3] top-down & bottom-up dp | ye15 | 6 | 488 | minimum cost to cut a stick | 1,547 | 0.57 | Hard | 22,897 |
https://leetcode.com/problems/minimum-cost-to-cut-a-stick/discuss/781085/Python3-top-down-and-bottom-up-dp | class Solution:
def minCost(self, n: int, cuts: List[int]) -> int:
cuts.extend([0, n])
cuts.sort()
@lru_cache(None)
def fn(i, j):
"""Return cost of cutting from cuts[i] to cuts[j]."""
if i+1 == j: return 0 #no cut in (i, j)
return cuts[j] - cuts[i] + min(fn(i, k) + fn(k, j) for k in range(i+1, j))
return fn(0, len(cuts)-1) | minimum-cost-to-cut-a-stick | [Python3] top-down & bottom-up dp | ye15 | 6 | 488 | minimum cost to cut a stick | 1,547 | 0.57 | Hard | 22,898 |
https://leetcode.com/problems/minimum-cost-to-cut-a-stick/discuss/781085/Python3-top-down-and-bottom-up-dp | class Solution:
def minCost(self, n: int, cuts: List[int]) -> int:
cuts.extend([0, n])
cuts.sort()
dp = [[0]*len(cuts) for _ in cuts]
for i in reversed(range(len(cuts))):
for j in range(i+2, len(cuts)):
dp[i][j] = cuts[j] - cuts[i] + min(dp[i][k] + dp[k][j] for k in range(i+1, j))
return dp[0][-1] | minimum-cost-to-cut-a-stick | [Python3] top-down & bottom-up dp | ye15 | 6 | 488 | minimum cost to cut a stick | 1,547 | 0.57 | Hard | 22,899 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.