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/backspace-string-compare/discuss/1995885/Python-or-2-Pointers-or-No-Complex-Inbuilt-function-usage | class Solution:
backSpace = '#'
#Returns the index after backspace
def getIndexAfterBackSpace(self, str, index):
backSpaceCount = 0
while(index >= 0):
if(str[index] == self.backSpace):
backSpaceCount += 1
elif(backSpaceCount > 0):
backSpaceCount -= 1
else:
break
index -= 1
return index
def backspaceCompare(self, s: str, t: str) -> bool:
p1, p2 = len(s) - 1, len(t) - 1
while(p1 >= 0 and p2 >= 0):
p1 = self.getIndexAfterBackSpace(s, p1)
p2 = self.getIndexAfterBackSpace(t, p2)
if(p1 < 0 or p2 < 0): break
if(s[p1] != t[p2]): return False
p1 -= 1
p2 -= 1
# Checking if Still any backspace charecter left, for case. s = "", t = "a#"
p1 = self.getIndexAfterBackSpace(s, p1)
p2 = self.getIndexAfterBackSpace(t, p2)
if(p1 != p2): return False
return True | backspace-string-compare | Python | 2 Pointers | No Complex Inbuilt function usage | thoufic | 3 | 499 | backspace string compare | 844 | 0.48 | Easy | 13,700 |
https://leetcode.com/problems/backspace-string-compare/discuss/1160674/Python-using-stacks-faster-than-94.94 | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
st_s = list()
st_t = list()
for c in s:
# To prevent the case that '#' comes at the very beginning of str
if not st_s and c == '#':
continue
elif c == '#':
st_s.pop()
else:
st_s.append(c)
for c in t:
if not st_t and c == '#':
continue
elif c == '#':
st_t.pop()
else:
st_t.append(c)
return ''.join(st_s) == ''.join(st_t) | backspace-string-compare | Python using stacks faster than 94.94% | keewook2 | 3 | 216 | backspace string compare | 844 | 0.48 | Easy | 13,701 |
https://leetcode.com/problems/backspace-string-compare/discuss/570522/Python-Easy-Solution | class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
S, T = self._helper(S), self._helper(T)
return S == T
def _helper(self,s):
while "#" in s:
i = s.index("#")
s = s[:i-1] + s[i+1:] if i > 0 else s[i+1:]
return s | backspace-string-compare | Python - Easy Solution | noobie12 | 3 | 1,300 | backspace string compare | 844 | 0.48 | Easy | 13,702 |
https://leetcode.com/problems/backspace-string-compare/discuss/570522/Python-Easy-Solution | class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
S, T = self._helper(S), self._helper(T)
return S == T
def _helper(self,s):
stack = []
for ele in s:
if ele != "#":
stack.append(ele)
elif stack:
stack.pop()
return stack | backspace-string-compare | Python - Easy Solution | noobie12 | 3 | 1,300 | backspace string compare | 844 | 0.48 | Easy | 13,703 |
https://leetcode.com/problems/backspace-string-compare/discuss/2001182/Python-Simple-Python-Solution | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
result1 = []
for i in s:
if i != '#':
result1.append(i)
else:
if result1:
result1.pop()
result2 = []
for i in t:
if i != '#':
result2.append(i)
else:
if result2:
result2.pop()
if result1 == result2:
return True
else:
return False | backspace-string-compare | [ Python ] ✅✅ Simple Python Solution✌👍 | ASHOK_KUMAR_MEGHVANSHI | 2 | 129 | backspace string compare | 844 | 0.48 | Easy | 13,704 |
https://leetcode.com/problems/backspace-string-compare/discuss/1997466/JavaC%2B%2BPythonJavaScriptKotlinSwiftO(n)timeBEATS-99.97-MEMORYSPEED-0ms-APRIL-2022 | class Solution:
def backspaceCompare(self, S, T):
i = len(S) - 1 # Traverse from the end of the strings
j = len(T) - 1
skipS = 0 # The number of backspaces required till we arrive at a valid character
skipT = 0
while i >= 0 or j >= 0:
while i >= 0: # Ensure that we are comparing a valid character in S
if S[i] == "#" :
skipS += 1 # If not a valid character, keep times we must backspace.
i = i - 1
elif skipS > 0:
skipS -= 1 # Backspace the number of times calculated in the previous step
i = i - 1
else:
break
while j >= 0: # Ensure that we are comparing a valid character in T
if T[j] == "#":
skipT += 1 # If not a valid character, keep times we must backspace.
j = j - 1
elif skipT > 0:
skipT -= 1 # Backspace the number of times calculated in the previous step
j = j - 1
else:
break
print("Comparing", S[i], T[j]) # Print out the characters for better understanding.
if i>= 0 and j >= 0 and S[i] != T[j]: # Compare both valid characters. If not the same, return False.
return False
if (i>=0) != (j>=0): # Also ensure that both the character indices are valid. If it is not valid,
return False # it means that we are comparing a "#" with a valid character.
i = i - 1
j = j - 1
return True # This means both the strings are equivalent. | backspace-string-compare | [Java/C++/Python/JavaScript/Kotlin/Swift]O(n)time/BEATS 99.97% MEMORY/SPEED 0ms APRIL 2022 | cucerdariancatalin | 2 | 80 | backspace string compare | 844 | 0.48 | Easy | 13,705 |
https://leetcode.com/problems/backspace-string-compare/discuss/1907674/Easiest-and-Simplest-Python-3-Code-oror-Faster-100-oror-STACK-APPROACH(FASTEST) | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
temp=[]
temp1=[]
if len(s)!=0 and len(t)!=0:
for i in s:
if i=='#' and len(temp)!=0:
temp.pop()
elif i=='#' and len(temp)==0:
pass
else:
temp.append(i)
for j in t:
if j=='#'and len(temp1)!=0:
temp1.pop()
elif j=='#' and len(temp1)==0:
pass
else:
temp1.append(j)
return (temp==temp1) | backspace-string-compare | Easiest & Simplest Python 3 Code || Faster 100% || STACK APPROACH(FASTEST) | RatnaPriya | 2 | 87 | backspace string compare | 844 | 0.48 | Easy | 13,706 |
https://leetcode.com/problems/backspace-string-compare/discuss/1515187/Python3-stack | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
ss, tt = [], []
for ch in s:
if ch == "#":
if ss: ss.pop()
else: ss.append(ch)
for ch in t:
if ch == "#":
if tt: tt.pop()
else: tt.append(ch)
return ss == tt | backspace-string-compare | [Python3] stack | ye15 | 2 | 84 | backspace string compare | 844 | 0.48 | Easy | 13,707 |
https://leetcode.com/problems/backspace-string-compare/discuss/1515187/Python3-stack | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
i, j = len(s)-1, len(t)-1
ss = tt = 0
while 0 <= i or 0 <= j:
while 0 <= i and (s[i] == "#" or ss):
if s[i] == "#": ss += 1
else: ss -= 1
i -= 1
while 0 <= j and (t[j] == "#" or tt):
if t[j] == "#": tt += 1
else: tt -= 1
j -= 1
if i < 0 and 0 <= j or 0 <= i and j < 0 or 0 <= i and 0 <= j and s[i] != t[j]: return False
i, j = i-1, j-1
return True | backspace-string-compare | [Python3] stack | ye15 | 2 | 84 | backspace string compare | 844 | 0.48 | Easy | 13,708 |
https://leetcode.com/problems/backspace-string-compare/discuss/2429491/Python3-Explanied-Straightforward-O(n)-w-Function | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
# Function takes a string as input, an returns a list of characters with backspaces processed
# It does this by looping through chars of the string appending them to a list
# If a "#" occurs, it removes the most recent character appended
def process_backspace(string):
output = []
for char in string:
if char == "#":
if len(output) > 0:
output.pop(-1)
else: output.append(char)
return output
# If the output of the process_backspace function with each string passed is the same, True! Else, false
return process_backspace(s) == process_backspace(t)
# Complexity:
# O(process_backspace) + O(process_backspace) + O(comparison)
# = O(n) + O(n) + O(1)
# = O(n) | backspace-string-compare | [Python3] Explanied - Straightforward O(n) w Function | connorthecrowe | 1 | 82 | backspace string compare | 844 | 0.48 | Easy | 13,709 |
https://leetcode.com/problems/backspace-string-compare/discuss/2298640/oror-Python-oror-Beats-99.58oror-STACKoror-Explanation-Using-Diagrams | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
def stacker(s):
stack=[]
for i in range(len(s)):
if not len(stack) and s[i]=="#": # this is to handle the side case where the first few elements are "#"
continue
elif s[i]=="#":
stack.pop(0)
else:
stack.insert(0,s[i])
return stack
stack1=stacker(s)
stack2=stacker(t)
return stack1==stack2 | backspace-string-compare | ✅|| Python || Beats 99.58%|| STACK|| Explanation Using Diagrams | HarshVardhan71 | 1 | 51 | backspace string compare | 844 | 0.48 | Easy | 13,710 |
https://leetcode.com/problems/backspace-string-compare/discuss/2158824/Python3-from-O(n)-to-O(1)-in-memory%3A-35ms-83.17 | class Solution:
def backspaceCompare(self, string: str, target: str) -> bool:
return self.solOne(string, target)
return self.solTwo(string, target)
# O(n) || O(1)
# Runtime: 35ms 83.17% Memory: 14mb 22.92%
def solOne(self, string, target):
stringLength = len(string) -1
targetLength = len(target) -1
while stringLength >= 0 or targetLength >= 0:
skipString = 0
skipTarget = 0
while stringLength >= 0:
if string[stringLength] == '#':
skipString += 1
stringLength -= 1
elif skipString > 0:
stringLength -= 1
skipString -= 1
else:
break
while targetLength >= 0:
if target[targetLength] == '#':
skipTarget += 1
targetLength -= 1
elif skipTarget > 0:
targetLength -= 1
skipTarget -= 1
else:
break
if (stringLength >= 0) != (targetLength >= 0):
return False
if stringLength >= 0 and targetLength >= 0 and string[stringLength] != target[targetLength]:
return False
stringLength -= 1
targetLength -= 1
return True
# O(n) || O(n)
# Runtime: 43ms 57.50% memory: 13.8mb 73.28%
def solTwo(self, string, target):
stackOne, stackTwo = [], []
for i in string:
if i == '#':
if stackOne:
stackOne.pop()
else:
stackOne.append(i)
for i in target:
if i == '#':
if stackTwo:
stackTwo.pop()
else:
stackTwo.append(i)
return stackOne == stackTwo | backspace-string-compare | Python3 from O(n) to O(1) in memory: 35ms 83.17% | arshergon | 1 | 157 | backspace string compare | 844 | 0.48 | Easy | 13,711 |
https://leetcode.com/problems/backspace-string-compare/discuss/2006952/Python3-1.-While-Loop-and-Return-Comparison-or-2.-Stack | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
return self.cpr(s)==self.cpr(t)
def cpr(self, s):
while "#" in s:
loc = s.find("#")
s = ""+s[loc+1:] if loc == 0 else s[0:loc-1]+s[loc+1:]
return s | backspace-string-compare | Python3 1. While Loop and Return Comparison | 2. Stack | khRay13 | 1 | 35 | backspace string compare | 844 | 0.48 | Easy | 13,712 |
https://leetcode.com/problems/backspace-string-compare/discuss/2006952/Python3-1.-While-Loop-and-Return-Comparison-or-2.-Stack | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
return self.stack(s)==self.stack(t)
def stack(self, s):
a = []
for k in s:
if k!="#":
a.append(k)
elif k=="#" and a:
a.pop()
else:
continue
return "".join(a) | backspace-string-compare | Python3 1. While Loop and Return Comparison | 2. Stack | khRay13 | 1 | 35 | backspace string compare | 844 | 0.48 | Easy | 13,713 |
https://leetcode.com/problems/backspace-string-compare/discuss/1353590/python3-easy-solution-for-beginners | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
l1=[]
l2=[]
for i in range (0,len(s)):
if s[i]!='#':
l1.append(s[i])
elif s[i]=='#' and l1 !=[]:
l1.pop()
for i in range (0,len(t)):
if t[i]!='#':
l2.append(t[i])
elif t[i]=='#' and l2 !=[]:
l2.pop()
if "".join(l1)=="".join(l2):
return True
else:
return False | backspace-string-compare | python3 easy solution for beginners | minato_namikaze | 1 | 141 | backspace string compare | 844 | 0.48 | Easy | 13,714 |
https://leetcode.com/problems/backspace-string-compare/discuss/1270316/Python-3-%3A-simple-and-easy-to-understand | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
slist = []
tlist = []
for i in s :
if i != '#' :
slist.append(i)
else :
if slist != [] : # if s or t begins with '#', will return error hence list is empty, nothing to pop
slist.pop()
for j in t :
if j != '#' :
tlist.append(j)
else :
if tlist != [] :
tlist.pop()
return slist == tlist | backspace-string-compare | Python 3 : simple and easy to understand | rohitkhairnar | 1 | 170 | backspace string compare | 844 | 0.48 | Easy | 13,715 |
https://leetcode.com/problems/backspace-string-compare/discuss/1139464/Python-Stack-Easy-Solution-95-Faster | class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
Stack_S = []
Stack_T = []
for char in S:
if char != '#':
Stack_S.append(char)
elif not Stack_S and char == '#':
continue
else:
Stack_S.pop()
for char in T:
if char != '#':
Stack_T.append(char)
elif not Stack_T and char == '#':
continue
else:
Stack_T.pop()
return Stack_S == Stack_T | backspace-string-compare | Python - Stack - Easy Solution - 95% Faster | piyushagg19 | 1 | 116 | backspace string compare | 844 | 0.48 | Easy | 13,716 |
https://leetcode.com/problems/backspace-string-compare/discuss/1139464/Python-Stack-Easy-Solution-95-Faster | class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
Stack_S = self.Compute(S)
Stack_T = self.Compute(T)
return Stack_S == Stack_T
def Compute(self, S: str) -> list[str]:
Stack = []
for char in S:
if char != '#':
Stack.append(char)
elif not Stack and char == '#':
continue
else:
Stack.pop()
return Stack | backspace-string-compare | Python - Stack - Easy Solution - 95% Faster | piyushagg19 | 1 | 116 | backspace string compare | 844 | 0.48 | Easy | 13,717 |
https://leetcode.com/problems/backspace-string-compare/discuss/1076814/Python3-easy | class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
s = self.backspaceString(S)
t = self.backspaceString(T)
return s==t
def backspaceString(self,txt):
stack = []
for i in txt:
if i =="#" and stack: stack.pop()
elif i!="#": stack.append(i)
return "".join(stack) | backspace-string-compare | Python3 easy | Pratyush1 | 1 | 86 | backspace string compare | 844 | 0.48 | Easy | 13,718 |
https://leetcode.com/problems/backspace-string-compare/discuss/2848297/844.-Backspace-String-Compare-Python-Solution | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
s_ans = []
t_ans = []
for i in s:
#First Checking if i=='#'
if (i == '#'):
#Then checking if list exists: only then pop, otherwise error aataa
#eg(#a#b#) : see here 1st # will be popped and error will be given
if s_ans: s_ans.pop()
else:
s_ans.append(i)
#print(s_ans)
for i in t:
if (i == '#'):
if t_ans: t_ans.pop()
else:
t_ans.append(i)
#print(t_ans)
if (s_ans == t_ans):
return True
else:
return False | backspace-string-compare | 844. Backspace String Compare - Python Solution | Brian_Daniel_Thomas | 0 | 1 | backspace string compare | 844 | 0.48 | Easy | 13,719 |
https://leetcode.com/problems/backspace-string-compare/discuss/2836455/Python-Solution-using-Stack-with-O(n)-Time-complexity-and-O(n)-Space-complexity | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
# create stack for s and t string
s_stack = []
t_stack = []
# iterate string and append to stack if not '#'
# if '#' pop the element from stack.
for i in s:
if i != '#':
s_stack.append(i)
else:
if s_stack:
s_stack.pop()
# iterate string and append to stack if not '#'
# if '#' pop the element from stack.
for i in t:
if i != '#':
t_stack.append(i)
else:
if t_stack:
t_stack.pop()
return "".join(s_stack) == "".join(t_stack) | backspace-string-compare | Python Solution using Stack with O(n) Time complexity and O(n) Space complexity | ratva0717 | 0 | 1 | backspace string compare | 844 | 0.48 | Easy | 13,720 |
https://leetcode.com/problems/backspace-string-compare/discuss/2830624/Python-create-2-new-str's-in-function | class Solution:
def sanitize_str(self, s: str) -> str:
l = []
for x in s:
if x == '#':
if l:
l.pop()
else:
l.append(x)
return ''.join(l)
def backspaceCompare(self, s: str, t: str) -> bool:
return self.sanitize_str(s) == self.sanitize_str(t) | backspace-string-compare | Python create 2 new str's in function | user3238Gj | 0 | 1 | backspace string compare | 844 | 0.48 | Easy | 13,721 |
https://leetcode.com/problems/backspace-string-compare/discuss/2828726/Python-Clean-up-strings-first-greater-then-compare-naive-approach | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
return self.helper(s) == self.helper(t)
def helper(self, s):
new, skip = '', 0
for i in range(len(s) - 1, -1, -1):
if s[i] == '#': # If hash, add to count to remove/skip
skip += 1
elif skip > 0: # Not hash, but count to remove/skip? Then do that
skip -= 1
else:
new = s[i] + new # Otherwise, not hash, and no count to remove/skip. So add it.
return new | backspace-string-compare | [Python] Clean up strings first -> then compare [naive approach] | graceiscoding | 0 | 1 | backspace string compare | 844 | 0.48 | Easy | 13,722 |
https://leetcode.com/problems/backspace-string-compare/discuss/2828096/Backspace-String-Compare-or-Python-Solution | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
sFinal = []
tFinal = []
for i in range(len(s)):
if s[i] == '#':
if sFinal:
sFinal.pop()
else:
sFinal.append(s[i])
for i in range(len(t)):
if t[i] == '#':
if tFinal:
tFinal.pop()
else:
tFinal.append(t[i])
return sFinal == tFinal | backspace-string-compare | Backspace String Compare | Python Solution | nishanrahman1994 | 0 | 2 | backspace string compare | 844 | 0.48 | Easy | 13,723 |
https://leetcode.com/problems/backspace-string-compare/discuss/2826636/backspace-string-compare | class Solution:
# Check if the string left uncompared if empty or not
def check_if_empty(self,s,i,c1):
while i>=0:
if s[i]=='#':
c1+=1
i-=1
elif c1!=0:
c1-=1
i-=1
else:
return False
return True
def backspaceCompare(self, s: str, t: str) -> bool:
i=len(s)-1
j=len(t)-1
c1=0
c2=0
while i>=0 and j>= 0:
# print(i,j)
if s[i]=='#':
c1+=1
i-=1
elif t[j]=='#':
c2+=1
j-=1
elif c1>0:
c1-=1
i-=1
elif c2>0:
c2-=1
j-=1
elif c1==0 and c2==0 and s[i]!='#' and s[i]==t[j]:
i-=1
j-=1
print(i,j,"after")
else:
return False
# if both were fully compared.
if i-c1<0 and j-c2 <0:
return True
# if one of them was longer and was left uncompared then check for whether the left string is empty
if i>=0 :
if self.check_if_empty(s,i,c1):
return True
return False
if j>=0 :
if self.check_if_empty(t,j,c2):
return True
return False
return False | backspace-string-compare | backspace-string-compare | shaikkamran | 0 | 3 | backspace string compare | 844 | 0.48 | Easy | 13,724 |
https://leetcode.com/problems/backspace-string-compare/discuss/2812787/Intuitive-Easy-Solution-or-Python-List-(Stack) | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
new_s = []
i = 0
for ss in s:
if ss != '#':
new_s.append(ss)
elif ss == '#' and len(new_s) > 0:
new_s.pop()
new_t = []
for tt in t:
if tt != '#':
new_t.append(tt)
elif tt == '#' and len(new_t) > 0:
new_t.pop()
return new_s == new_t | backspace-string-compare | Intuitive Easy Solution | Python List (Stack) | chienhsiang-hung | 0 | 4 | backspace string compare | 844 | 0.48 | Easy | 13,725 |
https://leetcode.com/problems/backspace-string-compare/discuss/2805003/Python3-or-Simple-and-effective-solution | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
def back_string(string):
ich = 0
while ich < len(string)-1:
if string[ich+1] == '#':
string = string[:ich]+string[ich+2:]
ich = max(0, ich - 1)
else:
ich += 1
return string
return back_string(s).strip('#') == back_string(t).strip('#') | backspace-string-compare | Python3 | Simple and effective solution | YLW_SE | 0 | 1 | backspace string compare | 844 | 0.48 | Easy | 13,726 |
https://leetcode.com/problems/backspace-string-compare/discuss/2799893/Two-stacks-oror-Python3 | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
s_stack, t_stack = [], []
for ch in s:
if s_stack and ch =='#':
s_stack.pop()
elif ch != '#':
s_stack.append(ch)
for ch in t:
if t_stack and ch =='#':
t_stack.pop()
elif ch != '#':
t_stack.append(ch)
return ''.join(s_stack) == ''.join(t_stack) | backspace-string-compare | Two stacks || Python3 | joshua_mur | 0 | 2 | backspace string compare | 844 | 0.48 | Easy | 13,727 |
https://leetcode.com/problems/backspace-string-compare/discuss/2799219/Easy-Understanding-Python-Solution | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
actS = ""
actT = ""
for i in s:
if(i == "#"):
actS = actS[:-1]
else:
actS += i
for i in t:
if(i == "#"):
actT = actT[:-1]
else:
actT += i
return actS == actT | backspace-string-compare | Easy Understanding Python Solution | abh1jith | 0 | 4 | backspace string compare | 844 | 0.48 | Easy | 13,728 |
https://leetcode.com/problems/backspace-string-compare/discuss/2794989/Python-stack-and-2-pointers-solutions | class Solution1:
def backspaceCompare(self, s: str, t: str) -> bool:
"""O(n) time, O(n) space"""
def type_to_editor(type_str: str) -> list:
editor = []
for elem in type_str:
if elem == '#':
if editor:
editor.pop()
else:
editor.append(elem)
return editor
s_editor = type_to_editor(s)
t_editor = type_to_editor(t)
return s_editor == t_editor
class Solution2:
def backspaceCompare(self, s: str, t: str) -> bool:
"""
Follow up: O(n) time, O(1) space
Use 2 pointers, fast iterate every elements,
find #backspace slow -= 1, otherwise, str[slow]=str[fast] then slow += 1.
"""
def type_to_editor(type_str: str) -> str:
type_str = list(type_str) # avoid typeError: 'str' object does not support item assignment
slow = 0
for fast in range(len(type_str)):
if type_str[fast] == '#':
if slow > 0:
slow -= 1
else:
type_str[slow] = type_str[fast]
slow += 1
return ''.join(type_str[0:slow])
s_editor = type_to_editor(s)
t_editor = type_to_editor(t)
return s_editor == t_editor | backspace-string-compare | Python, stack and 2 pointers solutions | woora3 | 0 | 6 | backspace string compare | 844 | 0.48 | Easy | 13,729 |
https://leetcode.com/problems/backspace-string-compare/discuss/2794512/Python-Stack-oror-EASIEST-SOLUTION-oror-EXPLANATION | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
ss = [] #stack1
tt = [] #stack2
for i in s:
if(i == '#'):
if(ss != []):
ss.pop() #removing the element that is before '#'
else:
ss.append(i)
for j in t:
if(j == '#'):
if(tt != []):
tt.pop()
else:
tt.append(j)
if(ss == tt):
return True
return False | backspace-string-compare | Python Stack || EASIEST SOLUTION || EXPLANATION 👍🎓👌 | abheer_mehrotra | 0 | 3 | backspace string compare | 844 | 0.48 | Easy | 13,730 |
https://leetcode.com/problems/backspace-string-compare/discuss/2784635/Python-Easy-way-to-understand-for-new-python-player | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
def backspace(tmp):
while '#' in tmp:
if tmp[0] == '#':
tmp = tmp[1:]
else:
idx = tmp.index('#')
del tmp[idx]
del tmp[idx-1]
return tmp
return backspace(list(s)) == backspace(list(t)) | backspace-string-compare | [Python] Easy way to understand for new python player \ | 20210116 | 0 | 2 | backspace string compare | 844 | 0.48 | Easy | 13,731 |
https://leetcode.com/problems/backspace-string-compare/discuss/2777085/Python-Easy-Solution-or-Faster-than-88.16-of-Submissions | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
val, val1 = '', ''
for i in range(len(s)):
if s[i] == '#':
val = val[:-1]
else:
val+=s[i]
for j in range(len(t)):
if t[j] == '#':
val1 = val1[:-1]
else:
val1+=t[j]
if val==val1:
return True
return False | backspace-string-compare | Python Easy Solution | Faster than 88.16% of Submissions | gautham0505 | 0 | 2 | backspace string compare | 844 | 0.48 | Easy | 13,732 |
https://leetcode.com/problems/backspace-string-compare/discuss/2768499/Easy-Approach-beats-70 | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
stck_s = []
stck_t = []
for char in s:
if char == '#':
if stck_s:
stck_s.pop()
else:
stck_s.append(char)
for char in t:
if char == '#':
if stck_t:
stck_t.pop()
else:
stck_t.append(char)
if stck_t == stck_s: return True
return False | backspace-string-compare | Easy Approach, beats 70% | zaberraiyan | 0 | 2 | backspace string compare | 844 | 0.48 | Easy | 13,733 |
https://leetcode.com/problems/backspace-string-compare/discuss/2725196/Runtime%3A-29-ms-faster-than-97.60 | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
def checkst(st) :
ss, sc, ix = '', 0, len(st)-1
while ix >= 0 :
x = st[ix]
if x == '#' :
sc += 1
else :
if sc > 0 :
sc -= 1
else :
ss = ss + x
ix -= 1
return ss
return checkst(s) == checkst(t) | backspace-string-compare | Runtime: 29 ms, faster than 97.60% | hansgun | 0 | 3 | backspace string compare | 844 | 0.48 | Easy | 13,734 |
https://leetcode.com/problems/backspace-string-compare/discuss/2705550/READABLE-python-solution-or-time-complexity%3A-O(n)-space-complexity%3A-O(1) | class Solution:
def backspaceCompare(self, string_1: str, string_2: str) -> bool:
i_1 = len(string_1) - 1
i_2 = len(string_2) - 1
counter_1 = 0 # backspace counters
counter_2 = 0
while i_1 >= 0 or i_2 >= 0:
while i_1 >= 0:
if string_1[i_1] == '#':
counter_1 += 1
i_1 -= 1
elif counter_1 > 0: # program already know that string_1[i_1] != '#' because the previous 'if' didn't work
counter_1 -= 1
i_1 -= 1
else:
break
while i_2 >= 0:
if string_2[i_2] == '#':
counter_2 += 1
i_2 -= 1
elif counter_2 > 0:
counter_2 -= 1
i_2 -= 1
else:
break
if (i_1 >= 0 and i_2 < 0) or (i_2 >= 0 and i_1 < 0):
return False
if (i_1 >= 0 and i_2 >= 0) and string_1[i_1] != string_2[i_2]:
return False
i_1 -= 1
i_2 -= 1
return True | backspace-string-compare | READABLE python solution | time complexity: O(n), space complexity: O(1) | gevondyanerik | 0 | 11 | backspace string compare | 844 | 0.48 | Easy | 13,735 |
https://leetcode.com/problems/backspace-string-compare/discuss/2702766/Simple-Python-solution | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
l1 = []
l2 = []
for ch in s:
if ch == '#':
if len(l1)>=1:
l1.pop()
else:
l1.append(ch)
for ch in t:
if ch == '#':
if len(l2)>=1:
l2.pop()
else:
l2.append(ch)
if l1==l2:
return True
return False | backspace-string-compare | Simple Python solution | imkprakash | 0 | 2 | backspace string compare | 844 | 0.48 | Easy | 13,736 |
https://leetcode.com/problems/backspace-string-compare/discuss/2696604/Python-Solution-O(N)-time-and-O(1)-space | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
index = 0
while index < len(s):
if s[index] == "#" and index != 0:
s = s[:index-1] + s[index+1:]
index -= 1
continue
index += 1
index = 0
while index < len(t):
if t[index] == "#" and index != 0:
t = t[:index-1] + t[index+1:]
index -= 1
continue
index += 1
s = s.replace("#","")
t = t.replace("#","")
return s == t | backspace-string-compare | Python Solution O(N) time and O(1) space | maomao1010 | 0 | 11 | backspace string compare | 844 | 0.48 | Easy | 13,737 |
https://leetcode.com/problems/backspace-string-compare/discuss/2674505/Easy-python-using-stack | class Solution:
def editorVersion(self, s:str) -> str:
stack = []
for ch in s:
if ch == "#":
if stack:
stack.pop()
else:
stack.append(ch)
return str(stack)
def backspaceCompare(self, s: str, t: str) -> bool:
s = self.editorVersion(s)
t = self.editorVersion(t)
print(s,t)
return s == t | backspace-string-compare | Easy python using stack | asiffmahmudd | 0 | 3 | backspace string compare | 844 | 0.48 | Easy | 13,738 |
https://leetcode.com/problems/backspace-string-compare/discuss/2673866/Python-solution | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
s1=''
s2=''
for c in s:
if c=='#':
if len(s1)== 0:
pass
else:
s1= s1[:-1]
else:
s1=s1 + c
for c in t:
if c=='#':
if len(s2) == 0:
pass
else:
s2= s2[:-1]
else:
s2=s2 + c
print(s1)
print(s2)
if s1 == s2:
return True
else:
return False | backspace-string-compare | Python solution | Sheeza | 0 | 4 | backspace string compare | 844 | 0.48 | Easy | 13,739 |
https://leetcode.com/problems/backspace-string-compare/discuss/2667931/Python-Easy-Solution | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
l1 = []
l2 = []
for i in s:
if i == "#" and l1:
l1.pop()
if i != "#":
l1.append(i)
for i in t:
if i == "#" and l2:
l2.pop()
if i != "#":
l2.append(i)
return True if l1 == l2 else False | backspace-string-compare | Python Easy Solution | user6770yv | 0 | 8 | backspace string compare | 844 | 0.48 | Easy | 13,740 |
https://leetcode.com/problems/backspace-string-compare/discuss/2667442/Stack-solution | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
def typing(s):
stack = []
for c in s:
if c == '#':
if stack:
stack.pop()
else:
stack.append(c)
return ''.join(stack)
return typing(s) == typing(t) | backspace-string-compare | Stack solution | kruzhilkin | 0 | 1 | backspace string compare | 844 | 0.48 | Easy | 13,741 |
https://leetcode.com/problems/backspace-string-compare/discuss/2662113/9-Line-Python-Monotonic-Stack | class Solution:
# Monotonic Stack 9 Line Solution
# Keep a mono
# If a '#' appears pop the mono
# Else Append to mono
def backspaceCompare(self, s: str, t: str) -> bool:
s, t = list(s), list(t)
def helper(s):
mono = []
for i in range(len(s)):
if s[i] == '#':
if mono: mono.pop()
else: mono.append(s[i])
return mono
return helper(s) == helper(t) | backspace-string-compare | 9 Line Python Monotonic Stack | shiv-codes | 0 | 19 | backspace string compare | 844 | 0.48 | Easy | 13,742 |
https://leetcode.com/problems/backspace-string-compare/discuss/2650501/Easy-Python-solution-using-if-else-with-explanation | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
# Define a function which works per string basis
def back_compare_per_string(string):
string_list = []
for i in string:
# If any backspace char is encountered, remove the last element only if the string_list is not empty. do nothing if its empty.
if i == "#":
if string_list:
string_list.pop()
else:
# Else, keep on appending the elements of the string in the list
string_list.append(i)
# Return the final list minus backspace characters
return string_list
return back_compare_per_string(s) == back_compare_per_string(t) | backspace-string-compare | Easy Python solution using if-else with explanation | code_snow | 0 | 28 | backspace string compare | 844 | 0.48 | Easy | 13,743 |
https://leetcode.com/problems/backspace-string-compare/discuss/2648032/Python-O(m%2Bn)-solution | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
s1=[]
for ch in s:
if ch == '#':
if s1:
s1.pop()
else:
s1.append(ch)
s2=[]
for ch in t:
if ch == '#':
if s2:
s2.pop()
else:
s2.append(ch)
return s1==s2 | backspace-string-compare | Python O(m+n) solution | enigmaman | 0 | 3 | backspace string compare | 844 | 0.48 | Easy | 13,744 |
https://leetcode.com/problems/backspace-string-compare/discuss/2640455/Python-Solution-Using-Stacks-or-Time-Complexity%3A-O(n)-or-Space-Complexity%3A-O(n) | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
s_stk, t_stk = [], []
for i in range(len(s)):
if s[i] != "#":
s_stk.append(s[i])
else:
if s_stk:
s_stk.pop()
else:
continue
for i in range(len(t)):
if t[i] != "#":
t_stk.append(t[i])
else:
if t_stk:
t_stk.pop()
else:
continue
return True if s_stk == t_stk else False | backspace-string-compare | Python Solution Using Stacks | Time Complexity: O(n) | Space Complexity: O(n) | jsdsz | 0 | 2 | backspace string compare | 844 | 0.48 | Easy | 13,745 |
https://leetcode.com/problems/backspace-string-compare/discuss/2481156/Python3-Solution-oror-Pop-Operation-oror-Easy | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
news = []
newt = []
for i in s:
if i != '#':
news.append(i)
elif len(news) > 0:
news.pop()
for i in t:
if i != '#':
newt.append(i)
elif len(newt) > 0:
newt.pop()
print(news,newt)
return news == newt | backspace-string-compare | Python3 Solution || Pop Operation || Easy | shashank_shashi | 0 | 37 | backspace string compare | 844 | 0.48 | Easy | 13,746 |
https://leetcode.com/problems/backspace-string-compare/discuss/2477998/Python3-Solution%3A-Passed-all-tests-oror-Very-simple | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
def preprocess(s):
s1 = []
for c in s:
if c == '#' :
if s1 != []:
s1.pop()
else:
s1.append(c)
return s1
return preprocess(s) == preprocess(t) | backspace-string-compare | ✔️ Python3 Solution: Passed all tests || Very simple | explusar | 0 | 16 | backspace string compare | 844 | 0.48 | Easy | 13,747 |
https://leetcode.com/problems/backspace-string-compare/discuss/2476786/Python-99.74-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Stack | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
l1 = self.helper(s, []) # calling helper function with string and empty stack as args.
l2 = self.helper(t, []) # calling helper function with string and empty stack as args.
return l1 == l2 # checking if s(stack) == t(stack)
def helper(self, s, stack): # helper function.
for char in s: # traversing the string.
if char is not "#": # checking is char in string is # or not.
stack.append(char) # if not # append it in the stack.
else:
if not stack: # if stack is empty. We could do it in diff way also. len(stack) == 0.
continue
stack.pop() # if we have elements in array then pop the last one.
return stack # returing the final stack. | backspace-string-compare | Python 99.74% faster | Simplest solution with explanation | Beg to Adv | Stack | rlakshay14 | 0 | 43 | backspace string compare | 844 | 0.48 | Easy | 13,748 |
https://leetcode.com/problems/backspace-string-compare/discuss/2476728/Python-Stack-Simplest-Solution-With-Explanation-or-Beg-to-adv-or-Stack | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
stack1 = [] # taking empty stack
stack2 = [] # taking another empty stack
for i in range(len(s)): # traversing through string s.
if s[i] is not "#": # if the elem is not #
stack1.append(s[i]) # will push it to the stack1
else: # if it is "#" and there is some elem in stack1 then we`ll pop it else we`ll pass.
if len(stack1)>0:
stack1.pop()
else:
pass
for i in range(len(t)): # traversing through string t.
if t[i] is not "#": # if the elem is not #
stack2.append(t[i]) # will push it to the stack2
else: # if it is "#" and there is some elem in stack2 then we`ll pop it else we`ll pass.
if len(stack2)>0:
stack2.pop()
else:
pass
return stack1 == stack2 # returning if they are equal when both are typed into empty text editors | backspace-string-compare | Python Stack Simplest Solution With Explanation | Beg to adv | Stack | rlakshay14 | 0 | 22 | backspace string compare | 844 | 0.48 | Easy | 13,749 |
https://leetcode.com/problems/longest-mountain-in-array/discuss/1837098/Python3%3A-One-pass-O(1)-Auxiliary-Space | class Solution:
def longestMountain(self, arr: List[int]) -> int:
increasing = False
increased = False
mx = -math.inf
curr = -math.inf
for i in range(1, len(arr)):
if arr[i] > arr[i-1]:
if increasing:
curr += 1
increased = True
else:
mx = max(curr, mx)
curr = 2
increased = True
increasing = True
elif arr[i] < arr[i-1]:
if increasing:
increasing = False
curr += 1
else:
if increased and not increasing:
mx = max(mx, curr)
curr = -math.inf
increased = False
increasing = False
if not increasing and increased:
mx = max(mx, curr)
return 0 if mx == -math.inf else mx | longest-mountain-in-array | Python3: One pass, O(1) Auxiliary Space | DheerajGadwala | 2 | 51 | longest mountain in array | 845 | 0.402 | Medium | 13,750 |
https://leetcode.com/problems/longest-mountain-in-array/discuss/1419207/One-pass-93-speed | class Solution:
def longestMountain(self, arr: List[int]) -> int:
len_mountain = slope = 0
start = -1
arr.append(arr[-1]) # to trigger len_mountain check in the loop
for i, (a, b) in enumerate(zip(arr, arr[1:])):
if b > a:
if slope < 1:
if slope == -1 and start > -1:
len_mountain = max(len_mountain, i + 1 - start)
start = i
slope = 1
elif b < a:
if slope == 1:
slope = -1
else:
if slope == -1:
if start > -1:
len_mountain = max(len_mountain, i + 1 - start)
slope = 0
start = -1
return len_mountain | longest-mountain-in-array | One pass, 93% speed | EvgenySH | 1 | 150 | longest mountain in array | 845 | 0.402 | Medium | 13,751 |
https://leetcode.com/problems/longest-mountain-in-array/discuss/937918/longestMountain-or-python3-one-pass-O(1)-space | class Solution:
def longestMountain(self, A: [int]) -> int:
ret, cur, up = 0, 1, True
for i in range(len(A) - 1):
if A[i+1] == A[i]:
ret, cur, up = max(cur, ret) if not up else ret, 1, True
continue
if up:
cur += 1 if A[i+1] > A[i] else 0
if cur <= 1:
continue
if A[i+1] < A[i]:
cur, up = cur + 1, False
continue
else:
if A[i+1] > A[i]:
ret, cur, up = max(cur, ret), 1, True
cur += 1
return ret if (ret := max(ret, cur) if not up else ret) >= 3 else 0 | longest-mountain-in-array | longestMountain | python3 one pass O(1) space | hangyu1130 | 1 | 87 | longest mountain in array | 845 | 0.402 | Medium | 13,752 |
https://leetcode.com/problems/longest-mountain-in-array/discuss/2813665/Python-(Simple-Maths) | class Solution:
def longestMountain(self, arr):
n = len(arr)
left, right = [0]*n, [0]*n
for i in range(1,n):
if arr[i] > arr[i-1]:
left[i] = left[i-1] + 1
for j in range(n-2,-1,-1):
if arr[j] > arr[j+1]:
right[j] = right[j+1] + 1
ans = [0]*n
for i in range(n):
if left[i] != 0 and right[i] != 0:
ans[i] = left[i] + right[i] + 1
return max(ans) | longest-mountain-in-array | Python (Simple Maths) | rnotappl | 0 | 3 | longest mountain in array | 845 | 0.402 | Medium | 13,753 |
https://leetcode.com/problems/longest-mountain-in-array/discuss/2734884/One-pass-two-state-variables-solution | class Solution:
def longestMountain(self, arr: List[int]) -> int:
longest = 0
left = 0
rise_seen = False
fall_seen = False
for right in range(1, len(arr)):
a, b = arr[right - 1], arr[right]
if a < b:
if fall_seen:
left = right - 1
rise_seen = True
fall_seen = False
elif a == b:
rise_seen = False
fall_seen = False
left = right
else:
fall_seen = True
if rise_seen:
longest = max(longest, right - left + 1)
return longest | longest-mountain-in-array | One pass, two state variables solution | abbus | 0 | 2 | longest mountain in array | 845 | 0.402 | Medium | 13,754 |
https://leetcode.com/problems/longest-mountain-in-array/discuss/2588471/Python3-or-T(n)-O(n)-or-S(n)-O(1)-or-One-pass-easy-understanding | class Solution:
def longestMountain(self, arr: List[int]) -> int:
if len(arr) < 3:
return 0
max_len = 0
l, r = 0, 1
while r < len(arr):
prev = l
up_exists, down_exists = False, False
while r < len(arr) and arr[prev] < arr[r]: # read upward trend
prev = r
r += 1
if prev != l:
up_exists = True
while r < len(arr) and arr[prev] > arr[r]: # read downward trend
down_exists = True
prev = r
r += 1
if prev != l and up_exists and down_exists: # update length if a mountain is detected
max_len = max(max_len, prev-l+1)
# handle duplicates
while r < len(arr) and arr[prev] == arr[r]:
prev = r
r += 1
l = prev
return max_len | longest-mountain-in-array | Python3 | T(n) = O(n) | S(n) = O(1) | One-pass easy-understanding | Ploypaphat | 0 | 19 | longest mountain in array | 845 | 0.402 | Medium | 13,755 |
https://leetcode.com/problems/longest-mountain-in-array/discuss/2523550/single-pass-python3 | class Solution:
def longestMountain(self, arr: List[int]) -> int:
n = len(arr)
if n <=2: return 0
ans=i=0
while i < n-1:
base = i
# check if we can go up
while i<n-1 and arr[i] < arr[i+1]:
i += 1
# if we could not go up, the it is not the right base of the mountain, move forward one step
if base == i:
i += 1
continue
# if we could go up, the check if where you are is the peak
peak = i
while i<n-1 and arr[i] > arr[i+1]:
i += 1
# we could not go down, it is not a mountain peak === i
if peak == i:
i += 1
continue
ans = max(ans, i-base+1)
return ans | longest-mountain-in-array | single pass, python3 | mnerc | 0 | 13 | longest mountain in array | 845 | 0.402 | Medium | 13,756 |
https://leetcode.com/problems/longest-mountain-in-array/discuss/2216285/Single-Traversal-or-Python | class Solution:
def longestMountain(self, arr: List[int]) -> int:
maxL = 0
i = 1
while i < len(arr) - 1:
isPeak = arr[i-1] < arr[i] and arr[i] > arr[i+1]
if not isPeak:
i+=1
continue
leftIdx = i - 2
while leftIdx >= 0 and arr[leftIdx] < arr[leftIdx+1]:
leftIdx-=1
rightIdx = i+2
while rightIdx < len(arr) and arr[rightIdx] < arr[rightIdx-1]:
rightIdx+=1
currL = rightIdx - leftIdx -1
maxL = max(currL,maxL)
i = rightIdx
return maxL | longest-mountain-in-array | Single Traversal | Python | bliqlegend | 0 | 29 | longest mountain in array | 845 | 0.402 | Medium | 13,757 |
https://leetcode.com/problems/longest-mountain-in-array/discuss/1723308/Python | class Solution:
def longestMountain(self, arr: List[int]) -> int:
ans=i=0
while i<len(arr):#In one pass we have to find one mountain or remove plain and valley
start=i
while i+1<len(arr) and arr[i+1]>arr[i]:#Find Peak
i+=1
if i==start:#Means either there is a plain or valley not peak
while i+1<len(arr) and arr[i+1]<=arr[i]:#Get rid of plain or valley
i+=1
if i==start:#Means we are at last el
break
continue
#If we reach here means we reach peak
peak=i
while i+1<len(arr) and arr[i+1]<arr[i]:#Find Valley
i+=1
if peak==i:#Means we found a plain not valley
while i+1<len(arr) and arr[i+1]==arr[i]:#Get rid of plain
i+=1
if i==peak:#Means we are at last el
break
continue
else:
ans=max(ans,i-start+1)#Means we found a mountain
return ans | longest-mountain-in-array | Python | heckt27 | 0 | 34 | longest mountain in array | 845 | 0.402 | Medium | 13,758 |
https://leetcode.com/problems/longest-mountain-in-array/discuss/1659076/Python-O(n)-time-O(1)-space-two-pointers-solution | class Solution:
def longestMountain(self, arr: List[int]) -> int:
n = len(arr)
res = 0
if n < 3:
return 0
idx = 0
start, end, peak = 0, 0, 0
flag_start, flag_end = False, False
while idx < n-2:
if arr[idx] >= arr[idx+1]:
idx += 1
flag_start = False
else: #arr[idx] < arr[idx+1]
start = idx
while idx < n-1 and arr[idx] < arr[idx+1]:
idx += 1
flag_start = True
peak = idx
if flag_start:
if idx < n-1 and arr[idx] <= arr[idx+1]:
idx += 1
else: # arr[idx] > arr[idx+1]
while idx < n-1 and arr[idx] > arr[idx+1]:
idx += 1
end = idx
if end >= peak + 1:
res = max(res, end-start+1)
return res | longest-mountain-in-array | Python O(n) time, O(1) space two-pointers solution | byuns9334 | 0 | 90 | longest mountain in array | 845 | 0.402 | Medium | 13,759 |
https://leetcode.com/problems/longest-mountain-in-array/discuss/1136556/simple-and-easy-python | class Solution:
def longestMountain(self, A: List[int]) -> int:
i = res = 0
while i < len(A):
start = i
while i + 1 < len(A) and A[i] < A[i+1]:
i += 1
if i == start:
i += 1
continue
end = i
while i + 1 < len(A) and A[i] > A[i+1]:
i += 1
if i == end:
i += 1
continue
res = max(res, i - start + 1)
return res | longest-mountain-in-array | simple and easy python | pheobhe | 0 | 40 | longest mountain in array | 845 | 0.402 | Medium | 13,760 |
https://leetcode.com/problems/longest-mountain-in-array/discuss/937650/python-o1-solution | class Solution:
def longestMountain(self, A: List[int]) -> int:
left,right = 0,1
output = 0
while right < len(A):
if A[left] >= A[right]:
left += 1
right += 1
else:
have_right = 0
while right < len(A)-1 and A[right] < A[right+1]:
right += 1
while right < len(A)-1 and A[right] > A[right+1]:
right += 1
have_right = 1
if have_right:
output = max(output,right-left+1)
left = right
right = left + 1
return output | longest-mountain-in-array | python o1 solution | yingziqing123 | 0 | 50 | longest mountain in array | 845 | 0.402 | Medium | 13,761 |
https://leetcode.com/problems/longest-mountain-in-array/discuss/716123/Python3Java-ez-to-understand-solution | class Solution:
"""
192ms 40.16% time
14.7MB 86.68% space
"""
def longestMountain(self, A: List[int]) -> int:
if len(A)<3:return 0
curr=-1
itr=1
while itr+1<len(A):
if A[itr-1]<A[itr] and A[itr]>A[itr+1]:
j,k=itr-1,itr+1
temp=3
while j-1>=0:
if A[j-1]<A[j]:
temp+=1
j-=1
else:break
while k+1<len(A):
if A[k+1]<A[k]:
temp+=1
k+=1
else:break
curr=max(curr,temp)
itr+=1
return curr if curr!=-1 else 0
Java Solution: 2ms beat 96.71%, 40.2MB beats 92.82%
class Solution {
public int longestMountain(int[] A) {
if(A.length<3){return 0;}
int curr=-1;
int itr=1;
while(itr+1<A.length){
if(A[itr]>A[itr+1]&&A[itr]>A[itr-1]){
int j=itr-1;
int k=itr+1;
int temp=3;
while(j-1>=0){
if(A[j-1]<A[j]){
temp+=1;
j-=1;
}
else{break;}
}
while(k+1<A.length){
if(A[k+1]<A[k]){
temp+=1;
k+=1;
}
else{break;}
}
curr=(curr<temp)?temp:curr;
}
itr+=1;
}
return (curr!=-1)?curr:0;
}
} | longest-mountain-in-array | Python3/Java ez to understand solution | 752937603 | 0 | 61 | longest mountain in array | 845 | 0.402 | Medium | 13,762 |
https://leetcode.com/problems/hand-of-straights/discuss/1938042/Python3-oror-Hashmap-oror-15-line-easy-to-understand | class Solution:
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
counter = Counter(hand)
while counter:
n = groupSize
start = min(counter.keys())
while n:
if start not in counter:
return False
counter[start] -= 1
if not counter[start]:
del counter[start]
start += 1
n -= 1
return True | hand-of-straights | Python3 || Hashmap || 15-line easy to understand | gulugulugulugulu | 3 | 227 | hand of straights | 846 | 0.564 | Medium | 13,763 |
https://leetcode.com/problems/hand-of-straights/discuss/1702142/Python-O(nlogn)-time-O(n)-space-solution-using-sort-and-hashmap | class Solution:
def isNStraightHand(self, nums: List[int], k: int) -> bool:
nums.sort()
n = len(nums)
count = defaultdict(int)
for num in nums:
count[num] += 1
for i in range(n):
if count[nums[i]] != 0:
count[nums[i]] -= 1
for j in range(nums[i]+1, nums[i]+k):
if count[j] == 0:
return False
count[j] -= 1
return True | hand-of-straights | Python O(nlogn) time, O(n) space solution using sort and hashmap | byuns9334 | 1 | 204 | hand of straights | 846 | 0.564 | Medium | 13,764 |
https://leetcode.com/problems/hand-of-straights/discuss/1564986/100-faster-oror-Well-Explained-oror-Clean-and-Concise-Code | class Solution:
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
if len(hand)%groupSize!=0:
return False
dic = Counter(hand)
keys = sorted(dic.keys())
for k in keys:
f = dic[k]
if f!=0:
for j in range(1,groupSize):
if dic[k+j]<f:
return False
dic[k+j]-=f
return True | hand-of-straights | 📌📌 100 % faster || Well-Explained || Clean & Concise Code 🐍 | abhi9Rai | 1 | 175 | hand of straights | 846 | 0.564 | Medium | 13,765 |
https://leetcode.com/problems/hand-of-straights/discuss/1222184/Deque-Min-Heap-Super-Easy-and-Understandable. | class Solution:
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
if len(hand)%groupSize !=0 :return False
queue=deque()
heapify(hand)
while hand:
if not queue:
queue.append([heappop(hand)])
elif len(queue[-1])==groupSize:
queue.pop()
else:
pop=heappop(hand)
if pop == queue[-1][-1] and pop==queue[0][-1]: queue.append([pop])
elif pop-queue[0][-1] > 1: return False
else:
left=queue.popleft()
left.append(pop)
queue.append(left)
return True if queue and len(queue[-1])==groupSize else False | hand-of-straights | Deque-Min-Heap Super Easy and Understandable. | hasham | 1 | 183 | hand of straights | 846 | 0.564 | Medium | 13,766 |
https://leetcode.com/problems/hand-of-straights/discuss/2523035/Python-easy-to-read-and-understand-or-hashmap | class Solution:
def isNStraightHand(self, hand: List[int], k: int) -> bool:
n = len(hand)
if n%k != 0:
return False
d = {}
for i in hand:
d[i] = d.get(i, 0) + 1
while d:
mn = min(d.keys())
for i in range(k):
if (mn+i) in d:
if d[(mn+i)] == 1:
del d[(mn+i)]
else:
d[(mn+i)] -= 1
else:
return False
return True | hand-of-straights | Python easy to read and understand | hashmap | sanial2001 | 0 | 51 | hand of straights | 846 | 0.564 | Medium | 13,767 |
https://leetcode.com/problems/hand-of-straights/discuss/2447901/Python-Easy-solution-or-faster-than-90 | class Solution:
def isNStraightHand(self, nums: List[int], k: int) -> bool:
l = len(nums)
h = defaultdict(int)
for i in nums:
h[i] += 1
if k == 1:
return True
if l%k :
return False
mx = max(list(h.values()))
s = list(set(nums))
heapq.heapify(s)
while s:
while s and h[s[0]] == 0:
heapq.heappop(s)
if s:
x = s[0]
h[x] -= 1
curr = 1
while curr < k:
n = x+curr
if h[n] > 0:
h[n] -= 1
else:return False
curr += 1
return True | hand-of-straights | Python Easy solution | faster than 90% | sami2002 | 0 | 19 | hand of straights | 846 | 0.564 | Medium | 13,768 |
https://leetcode.com/problems/hand-of-straights/discuss/2286454/Python-Easy-and-Fast-Solution | class Solution:
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
if len(hand) % groupSize:
return False
count = {}
for n in hand:
count[n] = 1 + count.get(n, 0)
minH = list(count.keys())
heapq.heapify(minH)
while minH:
first = minH[0]
for i in range(first, first + groupSize):
if i not in count:
return False
count[i] -= 1
if count[i] == 0:
if i != minH[0]:
return False
else:
heapq.heappop(minH)
return True | hand-of-straights | Python Easy and Fast Solution | soumyadexter7 | 0 | 72 | hand of straights | 846 | 0.564 | Medium | 13,769 |
https://leetcode.com/problems/hand-of-straights/discuss/2071058/Python-Hashmap-HeapSort | class Solution:
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
if len(hand) % groupSize: return False
if groupSize == 1: return True
size = len(hand) // groupSize
count = Counter(hand)
heap = []
for i, v in sorted(count.items(), key = lambda k:k[0]):
if not heap:
for _ in range(v):
heapq.heappush(heap, (i, 1))
else:
for _ in range(v):
if heap and heap[0][0] == i - 1:
ele, time = heapq.heappop(heap)
if time != groupSize - 1:
heapq.heappush(heap, (i, time + 1))
elif heap and heap[0][0] < i - 1:
return False
else:
heapq.heappush(heap, (i, 1))
return heap == [] | hand-of-straights | Python Hashmap HeapSort | Kennyyhhu | 0 | 61 | hand of straights | 846 | 0.564 | Medium | 13,770 |
https://leetcode.com/problems/hand-of-straights/discuss/2030308/Using-hashmap-Python | class Solution(object):
def isNStraightHand(self, hand, groupSize):
"""
:type hand: List[int]
:type groupSize: int
:rtype: bool
"""
if len(hand) % groupSize: return False
count = Counter(hand)
track = deque([])
for i, v in sorted(count.items(), key =lambda k:k[0]):
if track and track[-1][0] != i - 1:
return False
track.append([i, v])
if len(track) == groupSize:
cur_min = track[0][1]
track.popleft()
i = 0
while i < len(track):
if i > 0 and track[i][1] < track[i - 1][1]:
return False
elif track[i][1] == cur_min:
track.popleft()
else:
track[i][1] -= cur_min
i += 1
return len(track) == 0 | hand-of-straights | Using hashmap Python | Kennyyhhu | 0 | 87 | hand of straights | 846 | 0.564 | Medium | 13,771 |
https://leetcode.com/problems/hand-of-straights/discuss/1518051/Python3-Solution-with-using-counting | class Solution:
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
counter = collections.Counter(hand)
for c in sorted(counter):
if counter[c] > 0:
shift = 0
cur_c_count = counter[c]
while shift < groupSize:
if counter[c + shift] < cur_c_count:
return False
counter[c + shift] -= cur_c_count
shift += 1
return True | hand-of-straights | [Python3] Solution with using counting | maosipov11 | 0 | 104 | hand of straights | 846 | 0.564 | Medium | 13,772 |
https://leetcode.com/problems/hand-of-straights/discuss/986730/Python3-freq-table | class Solution:
def isNStraightHand(self, hand: List[int], W: int) -> bool:
freq = Counter(hand)
for x in sorted(freq):
if freq[x]:
for dx in range(1, W):
if freq[x+dx] < freq[x]: return False
freq[x+dx] -= freq[x]
return True | hand-of-straights | [Python3] freq table | ye15 | 0 | 84 | hand of straights | 846 | 0.564 | Medium | 13,773 |
https://leetcode.com/problems/hand-of-straights/discuss/986730/Python3-freq-table | class Solution:
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
freq = Counter(hand)
queue = deque()
prev, need = -1, 0
for x, v in sorted(freq.items()):
if need > v or need and x > prev+1: return False
queue.append(v - need)
prev, need = x, v
if len(queue) == groupSize: need -= queue.popleft()
return need == 0 | hand-of-straights | [Python3] freq table | ye15 | 0 | 84 | hand of straights | 846 | 0.564 | Medium | 13,774 |
https://leetcode.com/problems/hand-of-straights/discuss/785359/O(N-log(N))-time-and-O(N)-space-Python-beats-80-of-submissions-Using-HashMap-and-Lists | class Solution:
def isNStraightHand(self, hand: List[int], W: int) -> bool:
if not hand and W > 0:
return False
if W > len(hand):
return False
if W == 0 or W == 1:
return True
expectation_map = {}
# self.count keep track of the numbers of cards that have been successfully counted as a straight,
# when self.count == len(hand) => All cards are part of a valid straight
self.count = 0
handLength = len(hand)
#Sort the hand.
sortedHand = sorted(hand)
"""
This method updates the expectation map in the following way:
a) If the len(l) == W
=> We've completed a straight of length W, add it towards the final count
b) if the next expected number (num+1) is already in the map
=> add the list to a queue of hands waiting to make a straight
c) if expected number (num+1) not in the map
=> Add a new expectation key with value as a new queue with this list
"""
def update_expectation_with_list(expectation_map, num, l, W):
# If we have W consecutive numbers, we're done with this set, count towards final count
if len(l) == W:
self.count += W
# we need more numbers to make this straight, add back with next expected num
else:
exp = num + 1
# Some other list is already expecting this number, add to the queue
if exp in expectation_map:
expectation_map[exp].append(l)
# New expected number, create new key and set [l] as value
else:
expectation_map[exp] = [l]
"""
Very similar to update_expectation_with_list. The difference here is we have the first card of the straight and thus we need to handle it correctly (set the value as a list of lists)
"""
def update_expectation_with_integer(expectation_map, num):
exp = num + 1
# Some other list is already expecting this number, add to the queue
if exp in expectation_map:
expectation_map[exp].append([num])
# New expected number, create new key and set [num] as value
else:
expectation_map[exp] = [[num]]
for idx,num in enumerate(sortedHand):
# A possible straight can be formed with this number
if num in expectation_map:
# there are multiple hands waiting for this number
if len(expectation_map[num]) > 1:
# pop the first hand
l = expectation_map[num].pop(0)
# add num to this hand
l.append(num)
# Update the expectation map
update_expectation_with_list(expectation_map, num, l, W)
# there's only one hand expecting this number
else:
# pop the first hand
l = expectation_map[num].pop(0)
l.append(num)
# Important : del the key! There's no other hand expecting this number
expectation_map.pop(num)
update_expectation_with_list(expectation_map, num, l, W)
# Nothing is expecting this number, add new expectation to the map
else:
update_expectation_with_integer(expectation_map, num)
return self.count == handLength | hand-of-straights | O(N log(N)) time and O(N) space Python beats 80% of submissions - Using HashMap and Lists | prajwalpv | 0 | 163 | hand of straights | 846 | 0.564 | Medium | 13,775 |
https://leetcode.com/problems/hand-of-straights/discuss/681525/Python3-O(nlogn)-solution-Hand-of-Straights | class Solution:
def isNStraightHand(self, hand: List[int], W: int) -> bool:
nums, remainder = divmod(len(hand), W)
if remainder:
return False
cards = Counter(hand)
mins = sorted(cards.keys(), reverse=True)
def removeCard(c):
if c not in cards:
return False
cards[c] -= 1
if not cards[c]:
del cards[c]
while mins and mins[-1] not in cards:
mins.pop()
return True
for _ in range(nums):
curmin = mins[-1]
if any(not removeCard(curmin+i) for i in range(W)):
return False
return True | hand-of-straights | Python3 O(nlogn) solution - Hand of Straights | r0bertz | 0 | 138 | hand of straights | 846 | 0.564 | Medium | 13,776 |
https://leetcode.com/problems/hand-of-straights/discuss/551321/heap-approach-using-python | class Solution:
def isNStraightHand(self, hand, W):
"""
:type hand: List[int]
:type W: int
:rtype: bool
"""
cnt=collections.Counter(hand)
_h=[]
for h in hand:
heapq.heappush(_h,h)
while _h:
curEle=heapq.heappop(_h)
if cnt[curEle]==0:
continue
for i in range(W):
if cnt[curEle+i]<=0:
return False
else:
cnt[curEle+i]-=1
return True | hand-of-straights | heap approach using python | pathakrohit08 | 0 | 73 | hand of straights | 846 | 0.564 | Medium | 13,777 |
https://leetcode.com/problems/shortest-path-visiting-all-nodes/discuss/1800062/Python-Simple-Python-Solution-Using-Breadth-First-Search | class Solution:
def shortestPathLength(self, graph: List[List[int]]) -> int:
length = len(graph)
result = 0
visited_node = []
queue = []
for i in range(length):
visited_node.append(set([1<<i]))
queue.append([i,1<<i])
while queue:
result = result + 1
new_queue = []
for node, value in queue:
for neigbour_node in graph[node]:
mid_node = (1<<neigbour_node)|value
if mid_node not in visited_node[neigbour_node]:
if mid_node+1 == 1<<length:
return result
visited_node[neigbour_node].add(mid_node)
new_queue.append([neigbour_node, mid_node])
queue = new_queue
return 0 | shortest-path-visiting-all-nodes | [ Python ] ✔✔ Simple Python Solution Using Breadth-First-Search 🔥✌ | ASHOK_KUMAR_MEGHVANSHI | 6 | 914 | shortest path visiting all nodes | 847 | 0.613 | Hard | 13,778 |
https://leetcode.com/problems/shortest-path-visiting-all-nodes/discuss/1311903/Python3-Floyd-Warshall-%2B-TSP | class Solution:
def shortestPathLength(self, graph: List[List[int]]) -> int:
n = len(graph)
dist = [[inf]*n for _ in range(n)]
for i, x in enumerate(graph):
dist[i][i] = 0
for ii in x: dist[i][ii] = 1
# floyd-warshall
for k in range(n):
for i in range(n):
for j in range(n):
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
@cache
def fn(x, mask):
if mask == 0: return 0
ans = inf
for i in range(n):
if mask & (1 << i):
ans = min(ans, dist[x][i] + fn(i, mask ^ (1<<i)))
return ans
return min(fn(x, (1 << n)-1) for x in range(n)) | shortest-path-visiting-all-nodes | [Python3] Floyd-Warshall + TSP | ye15 | 5 | 433 | shortest path visiting all nodes | 847 | 0.613 | Hard | 13,779 |
https://leetcode.com/problems/shortest-path-visiting-all-nodes/discuss/1311903/Python3-Floyd-Warshall-%2B-TSP | class Solution:
def shortestPathLength(self, graph: List[List[int]]) -> int:
queue = deque([(i, 1<<i) for i in range(len(graph))])
seen = set(queue)
ans = 0
while queue:
for _ in range(len(queue)):
u, m = queue.popleft()
if m == (1<<len(graph)) - 1: return ans
for v in graph[u]:
if (v, m | 1<<v) not in seen:
queue.append((v, m | 1<<v))
seen.add((v, m | 1<<v))
ans += 1 | shortest-path-visiting-all-nodes | [Python3] Floyd-Warshall + TSP | ye15 | 5 | 433 | shortest path visiting all nodes | 847 | 0.613 | Hard | 13,780 |
https://leetcode.com/problems/shortest-path-visiting-all-nodes/discuss/2029272/Python-easy-to-read-and-understand-or-BFS | class Solution:
def shortestPathLength(self, graph: List[List[int]]) -> int:
q = []
n = len(graph)
for i in range(n):
visit = set()
visit.add(i)
q.append([i, visit])
steps = 0
while q:
num = len(q)
for i in range(num):
node, visit = q.pop(0)
#print(node, visit)
if len(visit) == n:
return steps
for nei in graph[node]:
temp = visit.copy()
temp.add(nei)
q.append([nei, temp])
if q:steps += 1 | shortest-path-visiting-all-nodes | Python easy to read and understand | BFS | sanial2001 | 0 | 199 | shortest path visiting all nodes | 847 | 0.613 | Hard | 13,781 |
https://leetcode.com/problems/shifting-letters/discuss/1088920/PythonPython3-Shifting-Letter-or-2-Solutions-or-One-liner | class Solution:
def shiftingLetters(self, S: str, shifts: List[int]) -> str:
final_shift = list(accumulate(shifts[::-1]))[::-1]
s_list = list(S)
for x in range(len(s_list)):
midval = ord(s_list[x]) + final_shift[x]%26
if midval > 122:
midval = midval - 26
s_list[x] = chr(midval)
return ''.join(s_list) | shifting-letters | [Python/Python3] Shifting Letter | 2 Solutions | One-liner | newborncoder | 4 | 761 | shifting letters | 848 | 0.454 | Medium | 13,782 |
https://leetcode.com/problems/shifting-letters/discuss/1088920/PythonPython3-Shifting-Letter-or-2-Solutions-or-One-liner | class Solution:
def shiftingLetters(self, S: str, shifts: List[int]) -> str:
return ''.join(chr((ord(letter) + shifting%26) - 26) if (ord(letter) + shifting%26)>122 else chr((ord(letter) + shifting%26)) for letter,shifting in zip(S, list(accumulate(shifts[::-1]))[::-1])) | shifting-letters | [Python/Python3] Shifting Letter | 2 Solutions | One-liner | newborncoder | 4 | 761 | shifting letters | 848 | 0.454 | Medium | 13,783 |
https://leetcode.com/problems/shifting-letters/discuss/1452036/Easy-Approach-oror-Explained-with-Example-oror-96-faster | class Solution:
def shiftingLetters(self, s: str, shifts: List[int]) -> str:
if len(shifts)>1:
for i in range(len(shifts)-2,-1,-1):
shifts[i]+=shifts[i+1] # Suffix sum
res=""
for i in range(len(s)):
c = chr(((ord(s[i])+shifts[i]-ord("a"))%26)+ord("a"))
res+=c
return res | shifting-letters | 🐍 Easy-Approach || Explained with Example || 96% faster 📌📌 | abhi9Rai | 2 | 163 | shifting letters | 848 | 0.454 | Medium | 13,784 |
https://leetcode.com/problems/shifting-letters/discuss/2677872/Python-oror-O(n)-beats-98.33 | class Solution:
def shiftingLetters(self, s: str, shifts: List[int]) -> str:
s = list(s)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
mydict= {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
sums = sum(shifts)
for i in range(len(s)):
index = mydict[s[i]]
index = index + sums
char = alphabet[index%26]
sums -= shifts[i]
s[i] = char
s = ''.join(s)
return s | shifting-letters | Python || O(n) beats 98.33% | Graviel77 | 1 | 132 | shifting letters | 848 | 0.454 | Medium | 13,785 |
https://leetcode.com/problems/shifting-letters/discuss/2836934/One-Line-Beats-96-Python | class Solution:
def shiftingLetters(self, s: str, shifts: List[int]) -> str:
return (lambda offsets : "".join([chr(ord('a') + (offsets[i] + ord(s[i]) - ord('a')) % 26) for i in range(len(s))]))(list(accumulate(shifts[::-1]))[::-1]) | shifting-letters | One Line Beats 96% Python | Norelaxation | 0 | 1 | shifting letters | 848 | 0.454 | Medium | 13,786 |
https://leetcode.com/problems/shifting-letters/discuss/2793833/Python-3-solution-with-O(n)-time-complexity | class Solution:
def shiftingLetters(self, s: str, shifts: List[int]) -> str:
"""Reverse shifts array and add incremental sum at each position.
e.g. [3,5,9] would become -> [17,14,9]
Now iterate for each character in s and add this offset to form a new
character, considering that the new character should be a lower case
letter, we need to scale it down to be in ascii range 97-122.
"""
num = 0
for r in range(len(shifts)-1, -1, -1): # Reverse the shifts array and sum at each index
new_sum = shifts[r] + num
shifts[r] += num
num = new_sum
a = ['']*len(s)
for i in range(len(s)):
new_ascii = (ord(s[i]) - ord('a') + shifts[i]) % 26 + ord('a')
a[i] = chr(new_ascii)
return ''.join(a) | shifting-letters | Python 3 solution with O(n) time complexity | ankitjaiswal07 | 0 | 10 | shifting letters | 848 | 0.454 | Medium | 13,787 |
https://leetcode.com/problems/shifting-letters/discuss/2619852/python-over-complicated... | class Solution:
def shiftingLetters(self, s: str, shifts: List[int]) -> str:
returned = [ord(ch) - ord("a") for ch in s]
dim = ord("z") - ord("a") + 1
for idx, shift in enumerate(itertools.accumulate(reversed(shifts))):
returned[-1-idx] = chr((returned[-1-idx] + shift) % dim + ord("a"))
return "".join(returned) | shifting-letters | python over complicated... | Potentis | 0 | 8 | shifting letters | 848 | 0.454 | Medium | 13,788 |
https://leetcode.com/problems/shifting-letters/discuss/2415686/Python's-magic-is-it's-libraries. | class Solution:
def shiftingLetters(self, s: str, shifts: List[int]) -> str:
shifts = list(accumulate(shifts[::-1]))[::-1]
shift = lambda c, x: chr(97+(ord(c)-97+x) % 26)
return ''.join(map(shift, s, shifts)) | shifting-letters | Python's magic is it's libraries. | blest | 0 | 41 | shifting letters | 848 | 0.454 | Medium | 13,789 |
https://leetcode.com/problems/shifting-letters/discuss/2323392/Python-easy-to-read-and-understand-or-suffix | class Solution:
def shiftingLetters(self, s: str, shifts: List[int]) -> str:
n = len(s)
nums = []
sums = 0
for i in shifts[::-1]:
sums = (sums+i)%26
nums.append(sums)
nums = nums[::-1]
res = ''
for i, ch in enumerate(s):
val = ord(s[i]) + nums[i]
while val > 122:
val -= 26
res += chr(val)
return res | shifting-letters | Python easy to read and understand | suffix | sanial2001 | 0 | 67 | shifting letters | 848 | 0.454 | Medium | 13,790 |
https://leetcode.com/problems/shifting-letters/discuss/2002342/Python-Simple-and-Easy-Solution-oror-O(N)-Time-Complexity | class Solution:
def shiftingLetters(self, s: str, shifts: List[int]) -> str:
arr = [i for i in s]
totalshift = sum(shifts) % 26
for shift in range(len(shifts)):
temp = ord(arr[shift]) - ord('a')
arr[shift] = chr((temp + totalshift)%26 + ord('a'))
totalshift = (totalshift - shifts[shift]) % 26
return ''.join(arr) | shifting-letters | Python - Simple and Easy Solution || O(N) Time Complexity | dayaniravi123 | 0 | 72 | shifting letters | 848 | 0.454 | Medium | 13,791 |
https://leetcode.com/problems/shifting-letters/discuss/1893030/python-3-oror-simple-solution-oror-O(n)O(n) | class Solution:
def shiftingLetters(self, s: str, shifts: List[int]) -> str:
def shift(c, n):
return chr((ord(c) - 97 + n) % 26 + 97)
for i in range(len(shifts) - 2, -1, -1):
shifts[i] += shifts[i + 1]
return ''.join(shift(c, n) for c, n in zip(s, shifts)) | shifting-letters | python 3 || simple solution || O(n)/O(n) | dereky4 | 0 | 80 | shifting letters | 848 | 0.454 | Medium | 13,792 |
https://leetcode.com/problems/shifting-letters/discuss/1870038/3-Lines-Python-Solution-oror-55-Faster | class Solution:
def shiftingLetters(self, s: str, shifts: List[int]) -> str:
ans='' ; C=ascii_lowercase ; shifts=list(accumulate(shifts[::-1]))[::-1]
for i in range(len(s)): ans+=C[(C.index(s[i])+shifts[i])%26]
return ans | shifting-letters | 3-Lines Python Solution || 55% Faster | Taha-C | 0 | 60 | shifting letters | 848 | 0.454 | Medium | 13,793 |
https://leetcode.com/problems/shifting-letters/discuss/1453775/Python-Solution | class Solution:
def shiftingLetters(self, s: str, shifts: List[int]) -> str:
prefix_shifts = [shifts[-1]]
n = len(s)
for i in range(n - 2, -1, -1):
prefix_shifts.append(prefix_shifts[-1] + shifts[i])
shifted = []
for i in range(n):
shifted.append(chr((ord(s[i]) - 97 + prefix_shifts[n - i - 1]) % 26 + 97))
return "".join(shifted) | shifting-letters | Python Solution | mariandanaila01 | 0 | 102 | shifting letters | 848 | 0.454 | Medium | 13,794 |
https://leetcode.com/problems/shifting-letters/discuss/1453526/python3or-Easy-Solution-or-O(n)-Time-Complexity | class Solution:
def shiftingLetters(self, s: str, shifts: List[int]) -> str:
ln=len(shifts)
s=list(s)
shift=0
for i in reversed(range(ln)):
shift=(shift+shifts[i])%26
s[i]=chr(((ord(s[i])-ord('a')+shift)%26)+ord('a'))
return "".join(s) | shifting-letters | python3| Easy Solution | O(n) Time Complexity | vikasprabhakar25 | 0 | 58 | shifting letters | 848 | 0.454 | Medium | 13,795 |
https://leetcode.com/problems/shifting-letters/discuss/1452631/python-ez-solution | class Solution:
def shiftingLetters(self, s: str, shifts: List[int]) -> str:
total = sum(shifts)
real_shift = []
for i in range(len(shifts)):
real_shift.append(total)
total -= shifts[i]
output = []
for i in range(len(s)):
actual = ord(s[i]) + real_shift[i]
while actual > ord('z'):
if actual - ord('z') > 26:
actual -= 26 * ((actual - ord('z')) // 26)
else:
actual -= 26
output.append(chr(actual))
return ''.join(output) | shifting-letters | python ez solution | yingziqing123 | 0 | 26 | shifting letters | 848 | 0.454 | Medium | 13,796 |
https://leetcode.com/problems/shifting-letters/discuss/1346904/Python-Reversed-Prefix-Sum-Beats-100 | class Solution:
def shiftingLetters(self, s: str, shifts: List[int]) -> str:
from itertools import accumulate
shifts = list(accumulate(shifts[::-1]))[::-1]
res = ""
for i in range(len(s)):
L = (ord(s[i])) + shifts[i] % 26
if 97 <= L <= 122:
res += chr(L)
else:
res += chr(96 + L % 122)
return res | shifting-letters | [Python] Reversed Prefix Sum - Beats 100% | Sai-Adarsh | 0 | 125 | shifting letters | 848 | 0.454 | Medium | 13,797 |
https://leetcode.com/problems/shifting-letters/discuss/1298168/Single-line-solution-but-little-slow. | class Solution:
def shiftingLetters(self, s: str, shifts: List[int]) -> str:
return ''.join([chr(97+((sum(shifts[j:])%26+(ord(s[j])-97))%26)) for j in range(len(s))]) | shifting-letters | Single line solution but little slow. | Rajashekar_Booreddy | 0 | 90 | shifting letters | 848 | 0.454 | Medium | 13,798 |
https://leetcode.com/problems/shifting-letters/discuss/1010530/Ultra-Simple-CppPython3-Solution-or-Suggestions-for-optimization-are-welcomed-or | class Solution:
def shiftingLetters(self, S: str, shifts: List[int]) -> str:
ans=""
s=0
rem=0
actual_shift=0
for i in range(len(shifts)-1,-1,-1):
s=s+shifts[i]
if s>=26:
s=s%26
rem=s%26
actual_shift=rem+ord(S[i])
if actual_shift>122:
temp=actual_shift
actual_shift=96+(temp-122)
ans=chr(actual_shift)+ans
return ans | shifting-letters | Ultra Simple Cpp/Python3 Solution | Suggestions for optimization are welcomed | | angiras_rohit | 0 | 68 | shifting letters | 848 | 0.454 | Medium | 13,799 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.