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/is-subsequence/discuss/2783712/Slow-and-Fast-Pointer-Python-3 | class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
slow_ptr = 0
fast_ptr = 0
while slow_ptr < len(s) and fast_ptr < len(t):
if s[slow_ptr] == t[fast_ptr]:
slow_ptr += 1
fast_ptr += 1
else:
fast_ptr += 1
if slow_ptr == len(s):
return True
return False | is-subsequence | Slow and Fast Pointer [Python 3] | thchong-code | 0 | 1 | is subsequence | 392 | 0.49 | Easy | 6,800 |
https://leetcode.com/problems/is-subsequence/discuss/2780761/Python-clear-2-pointers-O(n) | class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
p_s, p_t = 0, 0
while p_t < len(t) and p_s < len(s):
if s[p_s] == t[p_t]:
p_s += 1
p_t += 1
if p_s == len(s):
return True
return False | is-subsequence | Python, clear 2-pointers, O(n) ✅ | Gagampy | 0 | 1 | is subsequence | 392 | 0.49 | Easy | 6,801 |
https://leetcode.com/problems/is-subsequence/discuss/2779538/Python3-or-Speedy | class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
if len(s) == 0: #edge case for ""
return True
indx = 0
sarr = [0 for x in range(len(s))] #create array size s
for st in t: #iterate through t
if st in s and st in s[indx]:
sarr[indx] = 1
indx += 1
for a in sarr: #search for non 1 values
if a == 1:
continue
else:
return False
return True | is-subsequence | Python3 | Speedy | vmb004 | 0 | 4 | is subsequence | 392 | 0.49 | Easy | 6,802 |
https://leetcode.com/problems/is-subsequence/discuss/2773748/Python3-Runtime%3A-33-ms-faster-than-94.34.-Memory-Usage%3A-13.8-MB-less-than-81.67 | class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
max_idx = -1
for si in s:
cur_idx = t.find(si)
if (cur_idx==-1) or (max_idx > cur_idx):
return False
max_idx = cur_idx
t = "_"*cur_idx+t[cur_idx+1:]
else:
return True | is-subsequence | [Python3] Runtime: 33 ms, faster than 94.34%. Memory Usage: 13.8 MB, less than 81.67% | huiseom | 0 | 2 | is subsequence | 392 | 0.49 | Easy | 6,803 |
https://leetcode.com/problems/is-subsequence/discuss/2771515/Simple-Fast-python-solution | class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
counter = 0
for c in s:
if c in t:
t = t[t.index(c) + 1:]
counter += 1
if len(s) == counter:
return True
return False | is-subsequence | Simple-Fast python solution | don_masih | 0 | 1 | is subsequence | 392 | 0.49 | Easy | 6,804 |
https://leetcode.com/problems/is-subsequence/discuss/2769787/Python3-Easy-solution-with-explanation | class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
if len(s) > len(t):
return False
if len(s) == 0:
return True
l=0
r=0
while(l!=len(s) and r!=len(t)):
if s[l] == t[r]:
l += 1
r += 1
else:
r += 1
if l == len(s):
return True
else:
return False | is-subsequence | Python3 Easy solution with explanation | sakthikavincit | 0 | 3 | is subsequence | 392 | 0.49 | Easy | 6,805 |
https://leetcode.com/problems/is-subsequence/discuss/2751738/Simple-Python-Solution | class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
for i in range(len(s)):
if s[i] in t:
t = t[t.index(s[i])+1:]
else:
return False
return True | is-subsequence | Simple Python Solution | yas_hh | 0 | 2 | is subsequence | 392 | 0.49 | Easy | 6,806 |
https://leetcode.com/problems/utf-8-validation/discuss/2568848/Python3-or-DP-or-Memoization-or-Neat-Solution-or-O(n) | class Solution:
def validUtf8(self, data: List[int]) -> bool:
n = len(data)
l = [2**i for i in range(7, -1, -1)]
def isXByteSeq(pos, X):
f = data[pos]
rem = data[pos+1:pos+X]
ret = (f&l[X]) == 0
for i in range(X):
ret &= (f&l[i]) != 0
for num in rem:
ret &= (num&l[0]) != 0
ret &= (num&l[1]) == 0
return ret
@cache
def res(pos = 0):
ret = False
if pos == n:
ret = True
if pos + 3 < n:
ret |= isXByteSeq(pos, 4) and res(pos + 4)
if pos + 2 < n:
ret |= isXByteSeq(pos, 3) and res(pos + 3)
if pos + 1 < n:
ret |= isXByteSeq(pos, 2) and res(pos + 2)
if pos < n:
ret |= isXByteSeq(pos, 0) and res(pos + 1)
return ret
return res() | utf-8-validation | Python3 | DP | Memoization | Neat Solution | O(n) | DheerajGadwala | 4 | 497 | utf 8 validation | 393 | 0.452 | Medium | 6,807 |
https://leetcode.com/problems/utf-8-validation/discuss/2577038/Python3-oror-10-lines-binary-pad-wexplanation-oror-TM%3A-9597 | class Solution:
def validUtf8(self, data: List[int]) -> bool:
count = 0 # Keep a tally of non-first bytes required
for byte in data: # Pad out bytes to nine digits and ignore the 1st 1
byte|= 256 # Ex: 35 = 0b100101 --> 35|256 = 0b1_00100101
# Check for bad bytes.
if (byte >> 3 == 0b1_11111 or # One of first five digits must be a 1
(byte >> 6 == 0b1_10)^(count>0)): # Non-first byte can happen if and only if the current count !=0.
return False
# Update counts after new byte. (1-byte -> no change
# to count required because count == 0.)
if byte >> 5 == 0b1_110 : count = 1 # 2-byte first byte
elif byte >> 4 == 0b1_1110: count = 2 # 3-byte first byte
elif byte >> 4 == 0b1_1111: count = 3 # 4-byte first byte
elif byte >> 6 == 0b1_10 : count-= 1 # non-first bytes
return not count # Check for zero-count at EOL | utf-8-validation | Python3 || 10 lines, binary pad, w/explanation || T/M: 95%/97% | warrenruud | 3 | 55 | utf 8 validation | 393 | 0.452 | Medium | 6,808 |
https://leetcode.com/problems/utf-8-validation/discuss/1380903/python-faster-100 | class Solution:
def validUtf8(self, data: List[int]) -> bool:
eighth_bit = 1 << 7
seventh_bit = 1 << 6
sixth_bit = 1 << 5
fifth_bit = 1 << 4
fourth_bit = 1 << 3
trailing_byte_count = 0
for byte in data:
if trailing_byte_count > 0:
if (byte & eighth_bit) and not (byte & seventh_bit): #10xx_xxxx
trailing_byte_count -= 1
if trailing_byte_count < 0:
return False
continue
else:
return False
else:
if not (byte & eighth_bit): # 0xxx_xxxx
continue
else: # 1xxx_xxxx
if not (byte & seventh_bit): #10xx_xxxx
return False
# 11xx_xxxx
if not (byte & sixth_bit): # 110x_xxxx
trailing_byte_count = 1
continue
# 111x_xxxx
if not (byte & fifth_bit): # 1110_xxxx
trailing_byte_count = 2
continue
# 1111_xxxx
if not (byte & fourth_bit): # 1111_0xxx
trailing_byte_count = 3
continue
return False
if trailing_byte_count != 0:
return False
return True | utf-8-validation | python faster 100% | Hemal-Mamtora | 3 | 518 | utf 8 validation | 393 | 0.452 | Medium | 6,809 |
https://leetcode.com/problems/utf-8-validation/discuss/825305/Python3-straightforward-solution | class Solution:
def validUtf8(self, data: List[int]) -> bool:
cnt = 0
for x in data:
x = bin(x)[2:].zfill(8)
if cnt: # in the middle of multi-byte
if x.startswith("10"): cnt -= 1
else: return False
else: # beginning
cnt = x.find("0")
if cnt == -1 or cnt == 1 or cnt > 4: return False
if cnt: cnt -= 1
return cnt == 0 | utf-8-validation | [Python3] straightforward solution | ye15 | 3 | 242 | utf 8 validation | 393 | 0.452 | Medium | 6,810 |
https://leetcode.com/problems/utf-8-validation/discuss/2569769/Simple-Python-Solution-oror-O(n)-Complexity | class Solution:
def validUtf8(self, data: List[int]) -> bool:
l = []
for i in range(len(data)):
l.append(bin(data[i])[2:])
if(len(l[i]) < 8):
l[i] = '0'*(8-len(l[i]))+l[i]
curr = 0
byte = 0
flag = True
for i in range(len(l)):
if(byte == 0):
j = 0
while(j < len(l[i]) and l[i][j] == '1'):
byte +=1
j += 1
flag = True
elif(byte > 0):
if(flag):
byte -= 1
flag = False
if l[i][:2] != '10':
return False
byte -= 1
if byte > 4:
return False
if(byte > 0 and len(l) == 1):
return False
if(byte > 0):
return False
return True | utf-8-validation | Simple Python Solution || O(n) Complexity | urmil_kalaria | 1 | 93 | utf 8 validation | 393 | 0.452 | Medium | 6,811 |
https://leetcode.com/problems/utf-8-validation/discuss/2568974/Easy-python-solution | class Solution:
def validUtf8(self, data: List[int]) -> bool:
unicode=[]
for i in range(len(data)):
x=bin(data[i]).replace("0b", "")
if len(x)<8:
x='0'*(8-len(x))+x
unicode.append(x)
curr=None
cont=0
for i in range(len(unicode)):
if cont>0:
if unicode[i][:2]!='10':
return False
cont-=1
elif cont==0 and unicode[i][:2]=='10':
return False
else:
for j in range(5):
if unicode[i][j]=='0':
if j==0:
curr=1
else:
curr=j
cont=j-1
break
else:
print("ok2")
return False
if cont>0:
return False
return True | utf-8-validation | Easy python solution | shubham_1307 | 1 | 282 | utf 8 validation | 393 | 0.452 | Medium | 6,812 |
https://leetcode.com/problems/utf-8-validation/discuss/2579204/Python-3-oror-136-ms-faster-than-83.28-of-Python3 | class Solution:
def validUtf8(self, data: List[int]) -> bool:
i = 0
l = len(data)
while (i < l):
bin_rep = format(data[i], '#010b')[-8:]
if '0' not in bin_rep:
return False
count = bin_rep.index('0')
if count == 0:
i += 1
continue
if count == 1 or count > 4:
return False
i += 1
while count != 1 and i < l:
bin_rep = format(data[i], '#010b')[-8:]
if bin_rep[:2] == '10':
count -= 1
i += 1
else:
return False
if count > 1:
return False
return True | utf-8-validation | Python 3 || 136 ms, faster than 83.28% of Python3 | sagarhasan273 | 0 | 15 | utf 8 validation | 393 | 0.452 | Medium | 6,813 |
https://leetcode.com/problems/utf-8-validation/discuss/2574468/OFCOURSE-NOT-THE-FASTEST-BUT-THE-EASIEST-METHOD | class Solution:
def help(self,ans,j):
if ans[j][0:5]=='11110':
if len(ans[j::])<4: return False
if ans[j+1][0:2]=='10' and ans[j+2][0:2]=='10' and ans[j+3][0:2]=='10':
if j+4<len(ans):
return self.help(ans,j+4)
else:
return True
else: return False
elif ans[j][0:4]=='1110':
print(j)
if len(ans[j::])<3: return False
print(ans[j+1][0:2],ans[j+2][0:2])
if ans[j+1][0:2]=='10' and ans[j+2][0:2]=='10':
if j+3<len(ans):
return self.help(ans,j+3)
else:
return True
else: return False
elif ans[j][0:3]=='110':
if len(ans[j::])<2: return False
if ans[j+1][0:2]=='10':
if j+2<len(ans): return self.help(ans,j+2)
else: return True
else: return False
elif ans[j][0]=='0':
if j+1<len(ans):
return self.help(ans,j+1)
else: return True
else:
return False
def validUtf8(self, data: List[int]) -> bool:
ans=[]
for i in data: ans.append(bin(i)[2::])
for k in range(len(ans)):
if len(ans[k])!=8:
ans[k]='0'*(8-len(ans[k]))+ans[k]
return self.help(ans,0) | utf-8-validation | OFCOURSE NOT THE FASTEST BUT THE EASIEST METHOD | DG-Problemsolver | 0 | 8 | utf 8 validation | 393 | 0.452 | Medium | 6,814 |
https://leetcode.com/problems/utf-8-validation/discuss/2572903/Python3-Straightforward-solution | class Solution:
def validUtf8(self, data: List[int]) -> bool:
case = dict()
case["11110"] = ["10","10","10"]
case["1110"] = ["10","10"]
case["110"] = ["10"]
case["0"] = []
i = 0
while i < len(data):
x = "{0:08b}".format(data[i])
if x[:5] in case:
expecting = case["11110"]
elif x[:4] in case:
expecting = case["1110"]
elif x[:3] in case:
expecting = case["110"]
elif x[0] in case:
expecting = case["0"]
else:
return False
sub_data = data[i+1:i+len(expecting)+1]
if len(sub_data) != len(expecting):
return False
for one_s,other_s in zip(sub_data, expecting):
one_s = "{0:08b}".format(one_s)[:2]
if one_s != other_s:
return False
i = i + 1 + len(expecting)
return True | utf-8-validation | [Python3] Straightforward solution | Saitama1v1 | 0 | 13 | utf 8 validation | 393 | 0.452 | Medium | 6,815 |
https://leetcode.com/problems/utf-8-validation/discuss/2571057/Python3-One-Pass | class Solution:
def validUtf8(self, data: List[int]) -> bool:
pt, num = 0, len(data)
while pt < num:
if data[pt] < 128:
pt += 1
elif 192 <= data[pt] < 224:
if pt+2>num or not all(128<=data[i]<192 for i in range(pt+1,pt+2)):
return False
pt += 2
elif 224 <= data[pt] < 240:
if pt+3>num or not all(128<=data[i]<192 for i in range(pt+1,pt+3)):
return False
pt += 3
elif 240 <= data[pt] < 248:
if pt+4>num or not all(128<=data[i]<192 for i in range(pt+1,pt+4)):
return False
pt += 4
else:
return False
return True | utf-8-validation | [Python3] One-Pass | ruosengao | 0 | 29 | utf 8 validation | 393 | 0.452 | Medium | 6,816 |
https://leetcode.com/problems/utf-8-validation/discuss/2571014/Easy-Python-O(n)-approach-(99.56) | class Solution:
def validUtf8(self, data: List[int]) -> bool:
# check if it is formed 10xxxxxx
def is_continuation(num):
return num >= 128 and num <= 191
i = 0
while i < len(data):
# 1-byte UTF8 character
if data[i] <= 127:
i += 1
# 2-byte UTF8 character
elif data[i] >= 192 and data[i] <= 223:
try:
if not is_continuation(data[i+1]):
return False
except IndexError: # not sufficient numbers for 2-byte UTF8 code
return False
i += 2
# 3-byte UTF8 character
elif data[i] >= 224 and data[i] <= 239:
try:
if not is_continuation(data[i+1]) or not is_continuation(data[i+2]):
return False
except IndexError: # not sufficient numbers for 3-byte UTF8 code
return False
i += 3
# 4-byte UTF8 chatacter
elif data[i] >= 240 and data[i] <= 247:
try:
if not is_continuation(data[i+1]) or not is_continuation(data[i+2]) or not is_continuation(data[i+3]):
return False
except IndexError: # not sufficient numbers for 4-byte UTF8 code
return False
i += 4
else:
return False
return True | utf-8-validation | Easy Python O(n) approach (99.56%) | MajimaAyano | 0 | 56 | utf 8 validation | 393 | 0.452 | Medium | 6,817 |
https://leetcode.com/problems/utf-8-validation/discuss/2569779/GolangPython-2-solutions | class Solution:
def validUtf8(self, data: List[int]) -> bool:
i=0
while i<len(data):
bin_rep = bin(data[i])[2:].rjust(8,"0")
number_of_ones = 0
for b in bin_rep:
if b == "0":
break
number_of_ones+=1
if number_of_ones == 1 or number_of_ones > 4:
return False
for j in range(number_of_ones-1):
i+=1
if i == len(data):
return False
bin_rep = bin(data[i])[2:].rjust(8,"0")
if bin_rep[:2] != "10":
return False
i+=1
return True | utf-8-validation | Golang/Python 2 solutions | vtalantsev | 0 | 35 | utf 8 validation | 393 | 0.452 | Medium | 6,818 |
https://leetcode.com/problems/utf-8-validation/discuss/2569779/GolangPython-2-solutions | class Solution:
def validUtf8(self, data: List[int]) -> bool:
mask1 = 128
mask2 = 192
mask3 = 224
mask4 = 240
mask5 = 248
i = 0
while i < len(data):
if data[i]&mask5 == mask4:
added = 3
elif data[i]&mask4 == mask3:
added = 2
elif data[i]&mask3 == mask2:
added = 1
elif data[i]&mask1 == 0:
added = 0
else:
return False
for _ in range(added):
i+=1
if i == len(data):
return False
if data[i]&mask2 != mask1:
return False
i+=1
return True | utf-8-validation | Golang/Python 2 solutions | vtalantsev | 0 | 35 | utf 8 validation | 393 | 0.452 | Medium | 6,819 |
https://leetcode.com/problems/utf-8-validation/discuss/2569774/Python-Shift-register-counting-or-faster-than-95 | class Solution:
def validUtf8(self, data: List[int]) -> bool:
idx = 0
while idx < len(data):
buf = data[idx]
n = 1
while buf & 0x80 != 0:
buf <<= 1
n += 1
if n == 1:
idx += 1
continue
elif n == 2:
return False
elif n >= 3 and n <= 5:
# n >= 3
n -= 1
else:
return False
for j in range(idx + 1, idx + n):
if j >= len(data):
return False
if data[j] & 0xc0 != 0x80:
return False
idx += n
return True | utf-8-validation | [Python] Shift register counting | faster than 95% | staytime | 0 | 17 | utf 8 validation | 393 | 0.452 | Medium | 6,820 |
https://leetcode.com/problems/utf-8-validation/discuss/2569448/Only-used-Conditional-Statements-Python | class Solution:
def validUtf8(self, data: List[int]) -> bool:
# one = [127, 0]
# two = [[223, 192], [191, 128]]
# three = [[239, 224], [191, 128], [191, 128]]
# four = [[247, 240], [191, 128], [191, 128], [191, 128]]
ptr = 0
while ptr<len(data):
if data[ptr]<128:
ptr += 1
if ptr==len(data):
return True
elif data[ptr]<=223:
if len(data)-ptr<2:
return False
if 128<=data[ptr+1]<=191:
ptr += 2
else:
return False
elif data[ptr]<=239:
if len(data)-ptr<3:
return False
if 128<=data[ptr+1]<=191 and 128<=data[ptr+2]<=191:
ptr += 3
else:
return False
elif data[ptr]<=247:
if len(data)-ptr<4:
return False
if 128<=data[ptr+1]<=191 and 128<=data[ptr+2]<=191 and 128<=data[ptr+3]<=191:
ptr += 4
else:
return False
else:
return False
return True | utf-8-validation | Only used Conditional Statements Python | Sahil1729 | 0 | 16 | utf 8 validation | 393 | 0.452 | Medium | 6,821 |
https://leetcode.com/problems/utf-8-validation/discuss/2569254/Python-or-Easy-to-read-nothing-fancy | class Solution:
def validUtf8(self, data: List[int]) -> bool:
n = len(data)
i = 0
while i < n:
if data[i] < 128: # 0xxxxxxx
k = 1
elif 192 <= data[i] < 224: # 110xxxxx
k = 2
elif 224 <= data[i] < 240: # 1110xxxx
k = 3
elif 240 <= data[i] < 248: # 11110xxx
k = 4
else:
return False
if n - i < k:
return False
else:
for j in range(i + 1, i + k):
if not 128 <= data[j] < 192: # 10xxxxxx
return False
i += k
return True | utf-8-validation | Python | Easy to read, nothing fancy | sr_vrd | 0 | 43 | utf 8 validation | 393 | 0.452 | Medium | 6,822 |
https://leetcode.com/problems/utf-8-validation/discuss/2569203/python3-bitwise-checking-sol-for-reference | class Solution:
def checkLength(self, d):
cnt = -1
for i in range(7,0,-1):
if d & (1 << i):
cnt += 1
else:
return cnt
return cnt
def validUtf8(self, data: List[int]) -> bool:
didx = 0
while didx < len(data):
seql = self.checkLength(data[didx])
# if there is only one byte, skip since its valid char.
if seql > 3 or seql == 0:
return False
if seql == -1:
didx += 1
continue
didx += 1
while didx < len(data) and seql:
if data[didx] & (1 << 7) and data[didx] & (1 << 6) == 0:
didx += 1
seql -= 1
else:
return False
if seql:
return False
return True | utf-8-validation | [python3] bitwise checking sol for reference | vadhri_venkat | 0 | 15 | utf 8 validation | 393 | 0.452 | Medium | 6,823 |
https://leetcode.com/problems/utf-8-validation/discuss/2569119/python-bit-manipulation | class Solution(object):
def validUtf8(self, data):
"""
:type data: List[int]
:rtype: bool
"""
n_bit = 0
for entry in data:
# check if it is 1 byte data
if n_bit == 0:
bit_7 = entry >> 7
if bit_7 == 0:
continue
for i in range(0, 7):
i_bit = (entry >> (8 - i - 1)) & 0x01
if i_bit == 1:
n_bit += 1
else:
break
if n_bit == 0:
continue
if n_bit == 1 or n_bit > 4:
return False
else:
if entry >> 6 != 2: # binary 10
return False
n_bit -= 1
if n_bit > 0:
return False
return True
data = [240,162,138,147,145]
sol = Solution()
print(sol.validUtf8(data)) | utf-8-validation | python - bit manipulation | user2354hl | 0 | 15 | utf 8 validation | 393 | 0.452 | Medium | 6,824 |
https://leetcode.com/problems/utf-8-validation/discuss/2569108/Python-solution | class Solution:
def validUtf8(self, data: List[int]) -> bool:
byte = 0
for num in data:
if (byte >= 1):
if(num >> 6) == 0b10: byte -=1
else: return False
elif(num >> 3) == 0b11110: byte = 3
elif(num >> 4) == 0b1110: byte = 2
elif(num >> 5) == 0b110: byte = 1
elif(num >> 7) == 0b0: byte = 0
else:
return False
return True if byte == 0 else False | utf-8-validation | Python solution | chh3chan | 0 | 38 | utf 8 validation | 393 | 0.452 | Medium | 6,825 |
https://leetcode.com/problems/utf-8-validation/discuss/2569030/Python-Accepted | class Solution:
def validUtf8(self, data: List[int]) -> bool:
def length(n):
return len('{:08b}'.format(n).split('0', 1)[0])
i = 0
while i < len(data):
le = length(data[i])
i += 1
if le == 1 or le > 4:
return False
if le > 1:
for _ in range(le-1):
if i == len(data) or length(data[i]) != 1:
return False
i += 1
return True | utf-8-validation | Python Accepted ✅ | Khacker | 0 | 50 | utf 8 validation | 393 | 0.452 | Medium | 6,826 |
https://leetcode.com/problems/utf-8-validation/discuss/2569020/Python-solution-(explanation-behind-logic-provided) | class Solution:
def validUtf8(self, data: List[int]) -> bool:
'''
1. Convert integer to the required format by removing the '0b' and fill it with preceding zeroes if necessary
2. Count number of ones at the start of the string
2a. If there is only 1 one, or there are more than 4 ones, it is invalid (return false!)
2b. If there are no ones, aka the string starts with a zero, you can stop checking :)
2c. Otherwise, check if there are sufficient strings behind that start with '10' (note that
there will be n-1 strings required, where n = number of ones)
3. Move index to next untouched string and repeat step 2 until everything is covered
'''
# convert to binary
data = list(map(lambda x: str(bin(x)[2:]).zfill(8),data))
i = 0
while i < len(data):
count_ones = 0
for j in data[i]:
if j == '1':
count_ones += 1
else:
break
if count_ones == 1 or count_ones > 4:
return False
else:
for _ in range(count_ones-1):
i += 1
if i >= len(data) or not data[i].startswith('10'):
return False
i += 1
return True | utf-8-validation | Python solution (explanation behind logic provided) | chkmcnugget | 0 | 20 | utf 8 validation | 393 | 0.452 | Medium | 6,827 |
https://leetcode.com/problems/utf-8-validation/discuss/2569014/Simple-python3-solution | class Solution:
# O(n) time,
# O(1) space,
# Approach: array,
def validUtf8(self, data: List[int]) -> bool:
n = len(data)
def findNumBytes(num: int) -> int:
if num < 128:
return 1
if num >= 192 and num < 224:
return 2
if num >= 224 and num < 240:
return 3
if num >= 240 and num < 248:
return 4
return -1
i = 0
while i < n:
num = data[i]
byte_num = findNumBytes(num)
# print(byte_num)
if byte_num == -1: return False
subseq_num_range = 128, 192
data_left = n - i
if data_left < byte_num - 1: return False
j = i+1
while j < byte_num + i:
num = data[j]
if num < subseq_num_range[0] or num >= subseq_num_range[1]: return False
j +=1
i = j
return True | utf-8-validation | Simple python3 solution | destifo | 0 | 16 | utf 8 validation | 393 | 0.452 | Medium | 6,828 |
https://leetcode.com/problems/utf-8-validation/discuss/2568920/EASY-PYTHON3-SOLUTION | class Solution:
def validUtf8(self, data: List[int]) -> bool:
n = len(data)
l = [2**i for i in range(7, -1, -1)]
def isXByteSeq(pos, X):
f = data[pos]
rem = data[pos+1:pos+X]
ret = (f&l[X]) == 0
for i in range(X):
ret &= (f&l[i]) != 0
for num in rem:
ret &= (num&l[0]) != 0
ret &= (num&l[1]) == 0
return ret
@cache
def res(pos = 0):
ret = False
if pos == n:
ret = True
if pos + 3 < n:
ret |= isXByteSeq(pos, 4) and res(pos + 4)
if pos + 2 < n:
ret |= isXByteSeq(pos, 3) and res(pos + 3)
if pos + 1 < n:
ret |= isXByteSeq(pos, 2) and res(pos + 2)
if pos < n:
ret |= isXByteSeq(pos, 0) and res(pos + 1)
return ret
return res() | utf-8-validation | ✅✔ EASY PYTHON3 SOLUTION ✅✔ | rajukommula | 0 | 42 | utf 8 validation | 393 | 0.452 | Medium | 6,829 |
https://leetcode.com/problems/utf-8-validation/discuss/1827360/Python-soln | class Solution:
def validUtf8(self, data: List[int]) -> bool:
i=0
while i<len(data):
x=bin(data[i])[2:]
if len(x)!=8:
#Means it's a 1 byte
i+=1
continue
cnt=0
j=0
while j<len(x) and x[j]=='1':
cnt+=1#Count num of 1 or bytes 1(num of 1 must be 2,3 or 4)
j+=1
if cnt<=1 or cnt>4 or i+cnt>len(data):#cnt means number if bytes
return False
i+=1
cnt-=1#because 1 one byte is used by current num
while cnt>0:
y=bin(data[i])[2:]
if len(y)!=8 or not y.startswith('10'):
return False
i+=1
cnt-=1
return True | utf-8-validation | Python soln | heckt27 | 0 | 81 | utf 8 validation | 393 | 0.452 | Medium | 6,830 |
https://leetcode.com/problems/decode-string/discuss/1400105/98-faster-oror-With-and-without-Stack-oror-Cleane-and-Concise | class Solution:
def decodeString(self, s: str) -> str:
res,num = "",0
st = []
for c in s:
if c.isdigit():
num = num*10+int(c)
elif c=="[":
st.append(res)
st.append(num)
res=""
num=0
elif c=="]":
pnum = st.pop()
pstr = st.pop()
res = pstr + pnum*res
else:
res+=c
return res | decode-string | 🐍 98% faster || With and without Stack || Cleane & Concise 📌📌 | abhi9Rai | 27 | 2,700 | decode string | 394 | 0.576 | Medium | 6,831 |
https://leetcode.com/problems/decode-string/discuss/1400105/98-faster-oror-With-and-without-Stack-oror-Cleane-and-Concise | class Solution:
def decodeString(self, s: str) -> str:
def dfs(s,p):
res = ""
i,num = p,0
while i<len(s):
asc = (ord(s[i])-48)
if 0<=asc<=9: # can also be written as if s[i].isdigit()
num=num*10+asc
elif s[i]=="[":
local,pos = dfs(s,i+1)
res+=local*num
i=pos
num=0
elif s[i]=="]":
return res,i
else:
res+=s[i]
i+=1
return res,i
return dfs(s,0)[0] | decode-string | 🐍 98% faster || With and without Stack || Cleane & Concise 📌📌 | abhi9Rai | 27 | 2,700 | decode string | 394 | 0.576 | Medium | 6,832 |
https://leetcode.com/problems/decode-string/discuss/1851228/Java-and-Python3-oror-Stack-oror-Clear-annotation | class Solution:
def decodeString(self, s):
# In python, List can be used as stack(by using pop()) and queue(by using pop(0))
result = []
for curr_char in s:
if curr_char == "]":
# Step2-1 : Find the (1)subStr and remove "[" in the stack
sub_str = []
while result[-1] != "[":
sub_str.append(result.pop())
sub_str = "".join(sub_str[::-1])
# Step2-2 : Find the (2)k and remove k in the stack
result.pop()
k = []
while len(result) > 0 and result[-1] <= "9":
k.append(result.pop())
k = int("".join(k[::-1]))
# Step2-3 : Repeat sub_str k times after stack
result += k*sub_str
else:
# Step1 : Put the char into the stack, except "]"
result.append(curr_char)
return "".join(result) | decode-string | Java and Python3 || Stack || Clear annotation | Sarah_Lene | 7 | 617 | decode string | 394 | 0.576 | Medium | 6,833 |
https://leetcode.com/problems/decode-string/discuss/714732/Python-solution-using-stacks.-O(n) | class Solution:
def decodeString(self, s: str) -> str:
# instantiate stacks to store the number and the string to repeat.
repeatStr = []
numRepeat = []
# initialize empty strings. One to store a multidigit number and other one to store the decoded string.
tempNum = ''
decodedStr = ''
# start iterating throught the encoded string
for char in s:
# check if the char is a digit.
if char.isdigit():
tempNum += char # add the number to tempNum
# check if the char is an opening bracket
elif char == '[':
repeatStr.append(decodedStr)
numRepeat.append(tempNum)
tempNum = ''
decodedStr = ''
# check when the bracket closes
elif char == ']':
decodedStr = repeatStr.pop() + (decodedStr * int(numRepeat.pop()))
# else build the substring to repeat
else:
decodedStr += char
return decodedStr | decode-string | Python solution using stacks. O(n) | darshan_22 | 6 | 490 | decode string | 394 | 0.576 | Medium | 6,834 |
https://leetcode.com/problems/decode-string/discuss/1638379/Very-Easy-Python-stack-O(n)-96-faster | class Solution:
def decodeString(self, s: str) -> str:
st = []
for c in s:
if c != ']':
st.append(c)
else:
# join the string inside the 1st balanced brackets
tmp = ""
while st and st[-1] != '[':
tmp = st.pop() + tmp
# pop out the opening `[`
st.pop()
num = ""
# calculate the multiplier
while st and st[-1].isdigit():
num = st.pop() + num
# add the multiplied string back to the stack
st.append(int(num)*tmp)
return ''.join(st) | decode-string | Very Easy Python stack ; O(n) ; 96% faster | shankha117 | 4 | 253 | decode string | 394 | 0.576 | Medium | 6,835 |
https://leetcode.com/problems/decode-string/discuss/1167364/Concise-and-simple-recursive-solution | class Solution:
def decodeString(self, s: str) -> str:
def recurse(s, pos):
result = ""
i, num = pos, 0
while i < len(s):
c = s[i]
if c.isdigit():
num = num * 10 + int(c)
elif c == '[':
string, end = recurse(s, i + 1)
result += num * string
i = end
num = 0
elif c == ']':
return result, i
else:
result += c
i += 1
return result, i
return recurse(s, 0)[0] | decode-string | Concise and simple recursive solution | swissified | 4 | 443 | decode string | 394 | 0.576 | Medium | 6,836 |
https://leetcode.com/problems/decode-string/discuss/2648343/Python-or-Easy-to-Understand-or-Stack | class Solution:
def decodeString(self, s: str) -> str:
'''
1.Use a stack and keep appending to the stack until you come across the first closing bracket(']')
2.When you come across the first closing bracket start popping until you encounter an opening bracket('[')),basically iterate unit the top of the stack is not an opening bracket and simultaneously keep on appending it to a seperate variable here its substr
3.Once that is done iterate unitl the stack is empty and if the top of the stack is a digit and append the popped values to a seperate string variable here its n
4.Once this is done append n and substr , we do this so that we get the repeated substring
5.Finally return the stack in a string format using .join
'''
stack = []
for i in range(len(s)):
if s[i]!="]":
stack.append(s[i])
else:
substr = ""
while stack[-1]!="[":
c = stack.pop()
substr = c + substr
stack.pop()
n = ""
while stack and stack[-1].isdigit():
nums = stack.pop()
n = nums + n
stack.append(int(n)*substr)
return "".join(stack) | decode-string | Python | Easy to Understand | Stack | Ron99 | 2 | 245 | decode string | 394 | 0.576 | Medium | 6,837 |
https://leetcode.com/problems/decode-string/discuss/2386986/Python-solution-using-Recursion | class Solution:
def decodeString(self, s: str) -> str:
def helper(index, encodedStr):
k = 0
string = ""
# len(s) will be diffrent depend of subString
while index < len(encodedStr):
if encodedStr[index] == "[": # we found opening bracket - call helper to find sub string
new_index , SubStr = helper(index+1, encodedStr)
# add SubStr to string
string += (k*SubStr)
k , index = 0 , new_index
elif encodedStr[index].isdigit():
k = k*10 + int(encodedStr[index])
elif encodedStr[index] == "]": # we found closing bracket - return sub string
return index, string
else:
string += encodedStr[index] # add curr char to sting
index +=1
return index, string
_ , decodedStr = helper(0,s)
return decodedStr | decode-string | Python solution using Recursion | amalk5 | 2 | 192 | decode string | 394 | 0.576 | Medium | 6,838 |
https://leetcode.com/problems/decode-string/discuss/1464324/Python-Simple-Recursion | class Solution:
def decodeString(self, s: str) -> str:
if not any(map(str.isdigit, s)):
return s
inner = self.find(s)
back = s.index(']')
times, val = self.getNumber(s, inner)
string = s[inner+ 1: back]
s = s.replace(s[val:back+1],string*int(times))
return self.decodeString(s)
def find(self, s):
back = s.index(']')
front = 0
for i in range(back, 0, -1):
if s[i] == '[':
front = i
break
return front
def getNumber(self, s, inner):
ans = ""
val = 0
for i in range(inner-1,-1, -1):
if s[i].isdigit():
ans += s[i]
val = i
else:
break
return ans[::-1], val | decode-string | Python Simple Recursion | bubae | 2 | 436 | decode string | 394 | 0.576 | Medium | 6,839 |
https://leetcode.com/problems/decode-string/discuss/2525162/Python3-Solution-oror-Stack-oror-Easy-and-Understandable | class Solution:
def decodeString(self, s: str) -> str:
stk = []
for i in range(len(s)):
if s[i] != ']':
stk.append(s[i])
else:
strr = ''
while stk[-1] != '[':
strr = stk.pop() + strr
stk.pop()
num = ''
while stk and stk[-1].isdigit():
num = stk.pop() + num
stk.append(int(num) * strr)
return ''.join(stk) | decode-string | Python3 Solution || Stack || Easy & Understandable | shashank_shashi | 1 | 82 | decode string | 394 | 0.576 | Medium | 6,840 |
https://leetcode.com/problems/decode-string/discuss/2348237/Python-or-Stack-or-Faster-than-80-or-Straight-forward | class Solution:
def decodeString(self, s: str) -> str:
i = 0
digitStart = []
leftBracket = []
while i < len(s):
if s[i].isdigit() and not len(digitStart) > len(leftBracket):
digitStart.append(i) # store index in stack
if s[i] == '[':
leftBracket.append(i) # store index in stack
if s[i] == ']': # extracting
# take the indices out from the stack
kStart = digitStart.pop()
leftBound = leftBracket.pop()
# get the extracted string
k = int(s[kStart:leftBound])
string = s[leftBound+1:i] * k
# insert into the original s
s = s[:kStart] + string + s[i + 1:]
# move index to the end of s[:kStart] + string
i = kStart + len(string) - 1
i += 1
return s | decode-string | Python | Stack | Faster than 80% | Straight forward | pcdean2000 | 1 | 126 | decode string | 394 | 0.576 | Medium | 6,841 |
https://leetcode.com/problems/decode-string/discuss/2288079/Python3-solution-using-stack-faster-97 | class Solution:
def decodeString(self, s: str) -> str:
int_stack = []
str_stack = []
int_value = ""
for i in s:
if i.isdigit():
int_value+=i
else:
if i=="]":
k = ""
while len(str_stack) and str_stack[-1]!="[":
k = str_stack.pop(-1)+k
str_stack.pop(-1)
k = k*int_stack.pop(-1)
for j in k:
str_stack.append(j)
else:
if int_value!="":
int_stack.append(int(int_value))
int_value = ""
str_stack.append(i)
return "".join(str_stack) | decode-string | 📌 Python3 solution using stack faster 97% | Dark_wolf_jss | 1 | 81 | decode string | 394 | 0.576 | Medium | 6,842 |
https://leetcode.com/problems/decode-string/discuss/2183469/Python3-Runtime%3A-42ms-55.87-Memory%3A-13.9mb-20.28 | class Solution:
# Runtime: 42ms 55.87% Memory: 13.9mb 20.28%
def decodeString(self, string: str) -> str:
return self.solTwo(string)
def solOne(self, string):
stack = []
currentString = str()
currentNum = 0
for char in string:
if char.isdigit():
currentNum = currentNum * 10 + int(char)
elif char == '[':
stack.append(currentString)
stack.append(currentNum)
currentString = ''
currentNum = 0
elif char == ']':
num = stack.pop()
prevString = stack.pop()
currentString = prevString + num * currentString
else:
currentString += char
return currentString
def solTwo(self, string):
stack = []
for i in string:
if i != ']':
stack.append(i)
else:
substring = ''
while stack and stack[-1] != '[':
substring = stack.pop() + substring
stack.pop()
k = ''
while stack and stack[-1].isdigit():
k = stack.pop() + k
stack.append(int(k) * substring)
return ''.join(stack) | decode-string | Python3 Runtime: 42ms 55.87% Memory: 13.9mb 20.28% | arshergon | 1 | 166 | decode string | 394 | 0.576 | Medium | 6,843 |
https://leetcode.com/problems/decode-string/discuss/2010668/Python-solution-using-stack | class Solution:
def decodeString(self, s: str) -> str:
stack = []
for ch in s:
if ch == "]" and stack:
el = ""
while stack and not el.startswith("["):
el = stack.pop() + el
while stack and stack[-1].isdigit():
el = stack.pop() + el
num, el = el.strip("]").split("[")
ch = el * int(num)
stack.append(ch)
return "".join(stack) | decode-string | Python solution using stack | n_inferno | 1 | 123 | decode string | 394 | 0.576 | Medium | 6,844 |
https://leetcode.com/problems/decode-string/discuss/1860736/Using-Python's-Magic-oror-Please-help-with-space-Complexity | class Solution:
def decodeString(self, s: str) -> str:
layer = {}
timesMap = {}
openCount = 0
idx = 0
while idx < len(s):
ch = s[idx]
if ch.isalpha():
layer[openCount] = layer.get(openCount, "") + ch
elif ch.isnumeric():
current = ""
while ch.isnumeric():
current += ch
idx += 1
ch = s[idx]
timesMap[openCount + 1] = int(current)
idx -= 1
elif ch == "[":
openCount += 1
elif ch == "]":
current = layer[openCount] * timesMap[openCount]
layer[openCount] = ""
layer[openCount-1] = layer.get(openCount-1,"") + current
openCount -= 1
idx += 1
return layer[0]
O(N) Time complexity | decode-string | Using Python's Magic || Please help with space Complexity | beginne__r | 1 | 84 | decode string | 394 | 0.576 | Medium | 6,845 |
https://leetcode.com/problems/decode-string/discuss/1776931/Easy-Understanding-Solution-with-Comments | class Solution:
def decodeString(self, s: str) -> str:
stack=[]
for i in s:
#if the character is not equal to closing bracket till then we will simply append the input
if i !="]":
stack.append(i)
else:
#now if it is closing bracket then first we will make one temp string we simply pop the character from the stack till we encounter opening bracket
substr=""
while stack[-1]!='[':
substr=stack.pop()+substr
#we will pop once more to pop the opening bracket
stack.pop()
#now there is some number which preceed the opening bracket
k=""
while stack and stack[-1].isdigit():
k=stack.pop()+k
#now we have the number that we need to multiply the string and put it into the stack
stack.append(int(k)*substr)
return "".join(stack) | decode-string | Easy Understanding Solution with Comments | dpatel1507 | 1 | 79 | decode string | 394 | 0.576 | Medium | 6,846 |
https://leetcode.com/problems/decode-string/discuss/1636383/Backward-pass-%3A-no-recursion-or-stacks | class Solution:
def decodeString(self, s: str) -> str:
for i in range(len(s) - 1, -1, -1):
if s[i].isdigit():
n = s[i]
k = i - 1
while k > - 1 and s[k].isdigit(): #Reading the full number
n = s[k] + n
k-=1
n = int(n)
j = i + 2 #Skip the opening bracket
while s[j] != ']': #Reading the full code
j += 1
code = s[i+2:j] * n
s = s[:k+1] + code + s[j+1:]
return s | decode-string | Backward pass : no recursion or stacks | Sima24 | 1 | 58 | decode string | 394 | 0.576 | Medium | 6,847 |
https://leetcode.com/problems/decode-string/discuss/825528/Python3-stack-O(N) | class Solution:
def decodeString(self, s: str) -> str:
stack = []
ans = num = ""
for c in s:
if c.isalpha(): ans += c
elif c.isdigit(): num += c
elif c == "[":
stack.append(num)
stack.append(ans)
ans = num = ""
else: # c == "]"
ans = stack.pop() + ans*int(stack.pop())
return ans | decode-string | [Python3] stack O(N) | ye15 | 1 | 102 | decode string | 394 | 0.576 | Medium | 6,848 |
https://leetcode.com/problems/decode-string/discuss/690861/simple-python-solution-using-stacks-(98.46) | class Solution:
def decodeString(self, s: str) -> str:
repeatStr = []
numRepeat = []
temp = ''
solution = ''
for char in s:
if char.isdigit():
temp += char
elif char == '[':
numRepeat.append(temp)
temp = ''
repeatStr.append(solution)
solution = ''
elif char == ']':
solution = repeatStr.pop() + (solution * int(numRepeat.pop()))
else:
solution += char
return solution | decode-string | simple python solution using stacks (98.46%) | darshan_22 | 1 | 178 | decode string | 394 | 0.576 | Medium | 6,849 |
https://leetcode.com/problems/decode-string/discuss/470592/Python3-simple-short-for()-loop | class Solution:
def decodeString(self, s: str) -> str:
stack,num,temp = [],"",""
for char in s:
if char == "[":
stack.append(temp),stack.append(num)
temp,num = "",""
elif char == "]":
count,prev = stack.pop(),stack.pop()
temp = prev + int(count)*temp
elif char.isdigit():
num += char
else:
temp += char
return temp | decode-string | Python3 simple short for() loop | jb07 | 1 | 100 | decode string | 394 | 0.576 | Medium | 6,850 |
https://leetcode.com/problems/decode-string/discuss/2846618/Python-solution-with-explanation-or-O(n) | class Solution:
def decodeString(self, s: str) -> str:
# finding if whole string is alphabetic or not with flag
flag = True
for letter in s:
if letter.isnumeric():
flag= False
break
# If whole string is alphabetic then return it
if(flag):
return s
ans = ""
index = 0
while(index < (len(s))):
# if the element at index is numeric then find out the number till '['
# if the s='32[abc]', index = 0, element at 0 is numeric i.e. 3
# we need to find out the whole number till '[' i.e. 32
if s[index].isnumeric():
j = index
stack = ['[']
# finding number
while(s[j]!='['):
j+=1
k = j+1
times = int(s[index:j])
# finding the closing bracket ']' for bracket next to number '[' using stack
while(stack):
if(s[k]=='['):
stack.append('[')
elif(s[k]==']'):
stack.pop()
k+=1
# Decoding the string inside the brackets
ans += self.decodeString(s[j+1:k-1])*times
# IMP - increment the index
index = k
else :
# If the element at index is alphabet simply append it
ans+=s[index]
index+=1
return ans | decode-string | Python solution with explanation | O(n) | samart3010 | 0 | 5 | decode string | 394 | 0.576 | Medium | 6,851 |
https://leetcode.com/problems/decode-string/discuss/2846347/python3-solution-98.3-beats | class Solution:
def decodeString(self, s: str) -> str:
if s=='':
return s
if '[' not in s:
return s
i_o_b = s.rfind('[')
i_c_b= s.find(']',i_o_b)
a = int(s[i_o_b-1])
cnt = i_o_b - 2
try:
if type(int(s[i_o_b - 2])) == int:
a += int(s[i_o_b-2])*10
cnt-=1
try :
if type(int(s[i_o_b - 3])) == int:
a += int(s[i_o_b - 3]) * 100
cnt-=1
except:
pass
except :
pass
s = s[:cnt+1]+a*s[i_o_b+1:i_c_b]+s[i_c_b+1:]
return self.decodeString(s) | decode-string | python3 solution / 98.3 beats | Cosmodude | 0 | 3 | decode string | 394 | 0.576 | Medium | 6,852 |
https://leetcode.com/problems/decode-string/discuss/2846284/python3-solution-98.3-beats | class Solution:
def decodeString(self, s: str) -> str:
if s=='':
return s
if '[' not in s:
return s
i_o_b = s.rfind('[')
i_c_b= s.find(']',i_o_b)
a = int(s[i_o_b-1])
cnt = i_o_b - 2
try:
if type(int(s[i_o_b - 2])) == int:
a += int(s[i_o_b-2])*10
cnt-=1
try :
if type(int(s[i_o_b - 3])) == int:
a += int(s[i_o_b - 3]) * 100
cnt-=1
except:
pass
except :
pass
s = s[:cnt+1]+a*s[i_o_b+1:i_c_b]+s[i_c_b+1:]
return self.decodeString(s) | decode-string | python3 solution / 98.3 beats | Cosmodude | 0 | 2 | decode string | 394 | 0.576 | Medium | 6,853 |
https://leetcode.com/problems/decode-string/discuss/2828189/Decode-String-or-Python-Solution-or-Beats-97.14 | class Solution:
def decodeString(self, s: str) -> str:
stack = []
for i in s:
if i != ']':
stack.append(i)
else:
encodeString = ''
while stack and stack[-1] != '[':
encodeString = stack.pop() + encodeString
stack.pop()
k = ''
while stack and stack[-1].isdigit():
k = stack.pop() + k
k = int(k)
stack.append(encodeString * k)
return "".join(stack) | decode-string | Decode String | Python Solution | Beats 97.14% | nishanrahman1994 | 0 | 4 | decode string | 394 | 0.576 | Medium | 6,854 |
https://leetcode.com/problems/decode-string/discuss/2827501/Python3-solution | class Solution:
def decodeString(self, s: str) -> str:
stack = []
output = []
i = len(s) - 1
while i >= 0:
if len(stack) == 0 and s[i] != ']':
output = [s[i]] + output
i -= 1
continue
if s[i] == ']':
stack.append(s[i])
i -= 1
continue
if len(stack) > 0 and s[i] != '[':
stack.append(s[i])
i -= 1
continue
if s[i] == '[':
j = i - 1
while s[j].isnumeric() and j >= 0:
j -= 1
cnt = int(s[j + 1:i])
substr = []
for _ in range(len(stack)):
el = stack.pop()
if el == ']':
break
substr.append(el)
substr = cnt * substr
if len(stack) > 0:
for _ in range(len(substr)):
stack.append(substr.pop())
else:
output = substr + output
i = j
return ''.join(output) | decode-string | Python3 solution | dmitrik | 0 | 5 | decode string | 394 | 0.576 | Medium | 6,855 |
https://leetcode.com/problems/decode-string/discuss/2824899/Python-easy-solution | class Solution:
def decodeString(self, s: str) -> str:
stack=[]
cur_level=[]
num=0
for char in s:
if char.isdigit():
num = num*10+int(char)
elif char.isalpha():
cur_level.append(char)
elif char == '[':
stack.append((num,[*cur_level]))
cur_level=[]
num=0
elif char == ']':
prev_level_num, prev_level = stack.pop()
cur_level_string="".join(cur_level)
cur_level=[*prev_level, prev_level_num*cur_level_string]
return "".join(cur_level) | decode-string | Python easy solution | welin | 0 | 2 | decode string | 394 | 0.576 | Medium | 6,856 |
https://leetcode.com/problems/decode-string/discuss/2803780/Stack-oror-O(n)-oror-54ms-oror-Python3 | class Solution:
def decodeString(self, s: str) -> str:
stack = []
num = 0
res = ""
for st in s:
if st.isdigit():
num = num*10 + int(st)
elif st == '[':
stack.append(res)
stack.append(num)
res = ""
num = 0
elif st == ']':
pnum = stack.pop()
pstr = stack.pop()
res = pstr + pnum * res
else:
res += st
return res | decode-string | Stack || O(n) || 54ms || Python3 | spi-der_3ks | 0 | 5 | decode string | 394 | 0.576 | Medium | 6,857 |
https://leetcode.com/problems/decode-string/discuss/2684869/python-solution-stack-method | class Solution:
def decodeString(self, s: str) -> str:
p = ""
n = 0
stack = []
for i in s:
if i.isdigit():
n = n * 10 + int(i)
elif i == '[':
stack.append((p,n))
p = ''
n = 0
elif i == ']':
prev_p , prev_n = stack.pop()
p = prev_p + prev_n*p
else:
p += i
return(p) | decode-string | python solution stack method | vivekraj185 | 0 | 89 | decode string | 394 | 0.576 | Medium | 6,858 |
https://leetcode.com/problems/decode-string/discuss/2660470/python-stack-solution | class Solution:
def decodeString(self, s: str) -> str:
stack = []
i = 0
N = len(s)
while i < N:
if s[i].isdigit():
d = ""
while s[i].isdigit():
d += s[i]
i += 1
stack.append(int(d))
elif s[i] == ']':
cur = ""
while stack[-1] != '[':
cur = stack.pop() + cur
stack.pop()
cur = stack.pop() * cur
stack.append(cur)
i += 1
else:
stack.append(s[i])
i += 1
return "".join(stack) | decode-string | python stack solution | danielturato | 0 | 11 | decode string | 394 | 0.576 | Medium | 6,859 |
https://leetcode.com/problems/decode-string/discuss/2650081/Easy-to-understand-Python-Solution | class Solution:
def decodeString(self, s: str) -> str:
res=""
b1,b2=0,0
i=len(s)-1
while i>=0:
if s[i].isnumeric():
b2=i
while s[i].isnumeric():
i-=1
b1=i+1
n=int(s[b1:b2+1])
j=b2+1
while s[j]!=']':
j+=1
s=s[:b1]+n*s[b2+2:j]+s[j+1:]
else:
i-=1
return s | decode-string | Easy to understand Python Solution | afrinmahammad | 0 | 17 | decode string | 394 | 0.576 | Medium | 6,860 |
https://leetcode.com/problems/decode-string/discuss/2490808/Easy-solution-using-RE-(regular-expression)-Python-3-faster-than-80 | class Solution:
def decodeString(self, s: str) -> str:
while True:
res = re.search('\d*\[[^[^\]]*?\]', s)
if not res:
return s
start, end = res.span()
string = s[start:end]
number, right = string.split('[')
right = right[:len(right)-1]
s = s[:start]+right*int(number)+s[end:]
return s | decode-string | Easy solution using RE (regular expression) Python 3 faster than 80% | JiaxuLi | 0 | 31 | decode string | 394 | 0.576 | Medium | 6,861 |
https://leetcode.com/problems/decode-string/discuss/2459877/Python3-Solution-29-ms-faster-than-95.43-of-Python3-online-submissions-for-Decode-String. | class Solution:
def decodeString(self, s: str) -> str:
st = ''
i = 0
while i < len(s):
if not s[i].isdigit():
st = st + s[i]
else:
findB = s.index('[', i)
d = int(s[i : findB])
j = findB + 1
countB = 1
temp = ''
#Find the string to multiply by d times
while True:
if s[j] == '[':
countB = countB + 1
elif s[j] == ']':
countB = countB - 1
if countB == 0:
break
else:
temp = temp + s[j]
j = j + 1
temp = self.decodeString(temp)
temp = d* temp
st = st + temp
i = j
i = i + 1
return st | decode-string | [Python3] Solution 29 ms, faster than 95.43% of Python3 online submissions for Decode String. | WhiteBeardPirate | 0 | 80 | decode string | 394 | 0.576 | Medium | 6,862 |
https://leetcode.com/problems/decode-string/discuss/2430278/Python3-or-Solved-Using-Recursion-%2B-Stack | class Solution:
def decodeString(self, s: str) -> str:
#base case: single character that's not a number!
if(len(s) == 1 and s.isdigit() == False and s[0] != '[' and s[0] != ']'):
return s
#otherwise, we need to intialize the ans variable which we will return at the end!
ans = ""
i = 0
current_num = ""
#iterate through each and every char until it goes out of bounds!
while i < len(s):
cur = s[i]
#append stand alone characters!
if(cur.isdigit() == False and cur != '[' and cur != ']'):
ans += cur
i += 1
continue
#otherwise, the other case we have to take account is if
#current character is number, in which we have to decode
#in recursive manner!
if(cur.isdigit()):
current_num += cur
i += 1
continue
if(cur == '['):
num = int(current_num)
#we have to find index positions of all characters
#between open and closed brackets -> recurse over
#those characters in substring -> append to ans
#the result num times!
#to know when we reached the appropriate closing char,
#we can use a stack!
#push initial opening char!
stack = ['[']
#since i assume input is valid, there gaurantees
#corresponding closing char!
#start index = i + 2 since i+1th index is bracket char!
start = i+1
while stack:
if(s[start] == '['):
stack.append('[')
if(s[start] == ']'):
stack.pop()
start += 1
#once we exit, we know range of chars to recurse over!
#it will go from index i +2 to index start - 2!
recurse = self.decodeString(s[i+1:start - 1])
#add to answer num times the rec. call!
for i in range(num):
ans += recurse
#update i to index start since start points to first char after the closing bracket of
#current decoded string!
i = start
current_num = ""
continue
return ans | decode-string | Python3 | Solved Using Recursion + Stack | JOON1234 | 0 | 69 | decode string | 394 | 0.576 | Medium | 6,863 |
https://leetcode.com/problems/decode-string/discuss/2291011/Python3-Solution-with-using-stack | class Solution:
def decodeString(self, s: str) -> str:
stack = ['']
num = 0
for ch in s:
if ch.isdigit():
num = num * 10 + int(ch)
elif ch == '[':
stack.append(num)
num = 0
stack.append("")
elif ch == ']':
_str = stack.pop()
repeat_count = stack.pop()
stack[-1] += _str * repeat_count
else:
stack[-1] += ch
return ''.join(stack) | decode-string | [Python3] Solution with using stack | maosipov11 | 0 | 53 | decode string | 394 | 0.576 | Medium | 6,864 |
https://leetcode.com/problems/decode-string/discuss/2223844/Python-Using-Stack-O(n2)-solution | class Solution:
def decodeString(self, s: str) -> str:
def solve(s):
ans = ""
stack = deque()
for i in range(len(s)):
if s[i] != ']':
stack.append(s[i])
if s[i] == ']':
temp = ""
while stack[-1].isalpha():
popped = stack.pop()
temp = popped+temp
num = ""
stack.pop()
while stack and stack[-1].isnumeric():
popped = stack.pop()
num = popped+num
stack.append(int(num)*temp)
# while stack:
# ans = stack.pop() + ans
return ''.join(stack)
return solve(s) | decode-string | Python Using Stack O(n^2) solution | Abhi_009 | 0 | 36 | decode string | 394 | 0.576 | Medium | 6,865 |
https://leetcode.com/problems/decode-string/discuss/2223464/Stack-Approach-oror-Clean-Code | class Solution:
def decodeString(self, s: str) -> str:
stack = []
n = len(s)
for i in range(n):
if s[i] != "]":
stack.append(s[i])
else:
substring = ""
while stack[-1] != "[":
substring = stack.pop() + substring
stack.pop()
k = ""
while stack and stack[-1].isdigit():
k = stack.pop() + k
stack.append(int(k)*substring)
return "".join(stack) | decode-string | Stack Approach || Clean Code | Vaibhav7860 | 0 | 96 | decode string | 394 | 0.576 | Medium | 6,866 |
https://leetcode.com/problems/decode-string/discuss/2144759/Python-recursive | class Solution:
def decodeString(self, s: str) -> str:
def decode():
result = ""
while self.i < len(s) and s[self.i] != ']':
if s[self.i].isdigit():
idx = s.index('[', self.i)
digit = int(s[self.i:idx])
self.i = idx + 1
result += digit * decode()
else:
result += s[self.i]
self.i += 1
self.i += 1
return result
self.i = 0
return decode() | decode-string | Python, recursive | blue_sky5 | 0 | 93 | decode string | 394 | 0.576 | Medium | 6,867 |
https://leetcode.com/problems/decode-string/discuss/2076218/Python-Stack-Solution | class Solution:
def decodeString(self, s: str) -> str:
stack = []
for _char in s:
if _char != ']':
stack.append(_char)
else:
decoded_str = ''
while stack[-1] != '[':
stored_char = stack.pop(-1)
decoded_str = stored_char + decoded_str
stack.pop(-1)
k = ''
while len(stack) and ord('0') <= ord(stack[-1]) <= ord('9'):
stored_char = stack.pop(-1)
k = stored_char + k
k = int(k)
for c in decoded_str*k:
stack.append(c)
return "".join(stack) | decode-string | Python Stack Solution | ankitkools | 0 | 164 | decode string | 394 | 0.576 | Medium | 6,868 |
https://leetcode.com/problems/decode-string/discuss/1967225/Easy-and-Fast-Solution-in-Python-using-Stack-T.C-greaterO(n) | class Solution:
def decodeString(self, s: str) -> str:
stack=[]
for i in range(len(s)):
if s[i] !="]":
stack.append(s[i])
else:
substring=""
while stack[-1]!="[":
substring=stack.pop()+substring
stack.pop() #pop for"["
k=""
while stack and stack[-1].isdigit():
k=stack.pop()+k
stack.append(int(k) * substring)
return "".join(stack) | decode-string | Easy and Fast Solution in Python using Stack T.C->O(n) | karansinghsnp | 0 | 61 | decode string | 394 | 0.576 | Medium | 6,869 |
https://leetcode.com/problems/decode-string/discuss/1867917/Python-Recursive-Solution-(beats-99.78-) | class Solution:
def decodeString(self, s: str, start=0) -> str:
self.start = start
result = []
number_str = []
while self.start < len(s) and s[self.start] != ']':
if s[self.start].isalpha():
result.append(s[self.start])
elif s[self.start].isdigit():
number_str.append(s[self.start])
else:
brackets_str = self.decodeString(s, self.start + 1)
number = int(''.join(number_str))
result.append(number * brackets_str)
number_str = []
self.start += 1
return ''.join(result) | decode-string | ✅ Python Recursive Solution (beats 99.78 %) | AntonBelski | 0 | 406 | decode string | 394 | 0.576 | Medium | 6,870 |
https://leetcode.com/problems/decode-string/discuss/1858574/Python-(non-recursive-no-stack-beats-99.79) | class Solution:
def decodeString(self, s: str) -> str:
# start from the back
i = len(s) - 1
while i >= 0:
# check to see if it is a number and capture the entire number if it is (chr 48-57 == 0-9)
n = i
while 47 < ord(s[i]) < 58:
i -= 1
if n != i:
# parse number
m = int(s[i + 1:n + 1])
# find range of substring between square brackets (chr 93 == ']')
n += 2
o = n
while ord(s[o]) != 93:
o += 1
# create a new string by concatenating the front, the multiplied section, and the rest
s = s[:i + 1] + s[n:o] * m + s[o + 1:]
i -= 1
return s | decode-string | Python (non recursive, no stack, beats 99.79%) | esun74 | 0 | 66 | decode string | 394 | 0.576 | Medium | 6,871 |
https://leetcode.com/problems/decode-string/discuss/1843162/Python-l-Simple-Pointers | class Solution:
def decodeString(self, s: str) -> str:
i = 0
j = len(s) - 1
while '[' in s and ']' in s:
while '[' in s[i+1:j]: i += 1
while ']' in s[i+1:j]: j -= 1
k = i - 1
nb = ''
while s[k].isdigit():
nb = s[k] + nb
k -= 1
decode = int(nb)*s[i+1:j]
s = s[:k+1] + decode + s[j+1:]
i = 0
j = len(s) - 1
return s | decode-string | Python l Simple Pointers | morpheusdurden | 0 | 93 | decode string | 394 | 0.576 | Medium | 6,872 |
https://leetcode.com/problems/decode-string/discuss/1637304/Python3-Use-stack-and-keep-track-of-state | class Solution:
def decodeString(self, s: str) -> str:
res = []
temp = ""
num = ""
content = []
for i, c in enumerate(s):
if c.isnumeric():
if temp:
res.append(temp)
temp = ""
num+=c
if c.isalpha():
if num:
res.append(int(num))
num = ""
temp+=c
if c=='[':
if temp:
res.append(temp)
temp = ""
if num:
res.append(int(num))
num = ""
res.append('[')
if c==']':
if temp:
res.append(temp)
temp = ""
while res and res[-1]!='[':
content = [res.pop()] + content
res.pop()
mul = res.pop()
res += content*mul
content = []
# print(f"res = {res}, temp = {temp}, num = {num}")
res.append(temp)
return ''.join(res) | decode-string | [Python3] Use stack and keep track of state | Rainyforest | 0 | 15 | decode string | 394 | 0.576 | Medium | 6,873 |
https://leetcode.com/problems/decode-string/discuss/1636259/Python-simple-solutionor-95.62 | class Solution:
def decodeString(self, s: str) -> str:
# pay attention to numbers larger than 9
if s.isalpha():
return s
n = len(s)
count = left = 0
num = -1
ret = ''
for i in range(n):
if count==0 and s[i].isalpha():
ret += s[i]
elif s[i]=='[':
count+=1
elif count==0 and num==-1 and s[i].isnumeric():
left = s.find('[',i)
num = int(s[i:left])
elif s[i]==']':
count-=1
if count==0:
ret += num*self.decodeString(s[left+1:i])
num = -1
return ret | decode-string | Python simple solution| 95.62% | 1579901970cg | 0 | 54 | decode string | 394 | 0.576 | Medium | 6,874 |
https://leetcode.com/problems/decode-string/discuss/1635930/Python-99-fast-solution | class Solution:
def decodeString(self, s: str) -> str:
ans = ""
for i in s:
# print(ans)
if i==']':
pos = len(ans)-1
temp = ""
while ans[pos]!='[':
temp = ans[pos] +temp
pos-=1
# print("temp: ",temp)
num = 0
pos-=1
c = 1
while pos>=0 and ans[pos] in "0123456789":
num+= c*(ord(ans[pos])-ord("0"))
pos-=1
c*=10
# print("num: ",num)
ans = ans[:pos+1]+temp*num
else:
ans+=i
return ans | decode-string | Python 99% fast solution | RedHeadphone | 0 | 250 | decode string | 394 | 0.576 | Medium | 6,875 |
https://leetcode.com/problems/decode-string/discuss/1635676/Recursion-with-stack-approachoror24ms-faster-than-95.62oror14.3MB-less-than-52.98ororPython3 | class Solution:
def decodeString(self, s: str) -> str:
def helper(sub):
res = '' # empty new string initailaized
i = 0 # every time we get a valid new substring, we need to traverse through all of it
while i < len(sub):
if sub[i].isdigit(): # if its a digit, we know the next would be an opening bracket,then our substring
d = '' # To find the whole number we do another while loop
while sub[i].isdigit():
d += sub[i]
i += 1
st = ["["] # preemptively intializing with "[" because we already know a number will always be followed by a opening bracket
new_sub = '' # We know that the next x characters will be the substring we need for recursion
i += 1 # This increment is because we already added '[' to the stack which would have been the open bracket at i
while st: # Now we get the substring using stack approach, just basic bracket validation
if sub[i+1] == "[": # i+1 to prevent going out of bounds since we are doing i+=1 after the check
st.append("[") # I think not doing i+=1 right before "while st" and doing i+=1 will then let you check using sub[i]
if sub[i+1] == "]":
st.pop()
new_sub += sub[i]
i += 1
for j in range(int(d)): # Now, we have whole substring and hence we need to execute that substring the amount of times the number we obtained
res += helper(new_sub) # recursively call the function on that particular substring
elif sub[i].isalpha(): # if the character of the current string is an alphabet add it to res
res += sub[i]
i += 1
return res # Return the res generated after traversing throughout the current string
return helper(s) # returns the result of the total string | decode-string | Recursion with stack approach||24ms faster than 95.62%||14.3MB less than 52.98%||Python3 | nandhakiran366 | 0 | 32 | decode string | 394 | 0.576 | Medium | 6,876 |
https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/1721267/Faster-than-97.6.-Recursion | class Solution:
def rec(self, s, k):
c = Counter(s)
if pattern := "|".join(filter(lambda x: c[x] < k, c)):
if arr := list(filter(lambda x: len(x) >= k, re.split(pattern, s))):
return max(map(lambda x: self.rec(x, k), arr))
return 0
return len(s)
def longestSubstring(self, s: str, k: int) -> int:
return self.rec(s, k) | longest-substring-with-at-least-k-repeating-characters | Faster than 97.6%. Recursion | mygurbanov | 3 | 244 | longest substring with at least k repeating characters | 395 | 0.448 | Medium | 6,877 |
https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/1041531/Python-Sliding-Window-Solution | class Solution:
def longestSubstring(self, s: str, k: int) -> int:
#sliding window and hashmap O(n) or Divide and conquer(O(n*n))
n=len(s)
ans=0
freq= Counter(s)
max_nums=len(freq)
for num in range(1,max_nums+1):
counter=defaultdict(int)
left=0
for right in range(n):
counter[s[right]]+=1
while len(counter)>num:
counter[s[left]]-=1
if counter[s[left]]==0:
del counter[s[left]]
left+=1
for key in counter:
if counter[key]>=k :
flag=1
else:
flag=0
break
if flag==1:
ans=max(ans,right-left+1)
return ans | longest-substring-with-at-least-k-repeating-characters | Python Sliding Window Solution | ShivamBunge | 3 | 1,000 | longest substring with at least k repeating characters | 395 | 0.448 | Medium | 6,878 |
https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/704604/Python-3Longest-Substring-with-Atleast-K-repeating-characters.-Beats-85. | class Solution:
def longestSubstring(self, s: str, k: int) -> int:
if len(s)==0:
return 0
cnt = collections.Counter(s)
for i in cnt:
if cnt[i] < k:
# print(s.split(i))
return max(self.longestSubstring(p,k) for p in s.split(i))
return len(s) | longest-substring-with-at-least-k-repeating-characters | [Python 3]Longest Substring with Atleast K repeating characters. Beats 85%. | tilak_ | 3 | 696 | longest substring with at least k repeating characters | 395 | 0.448 | Medium | 6,879 |
https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/2549197/easy-sliding-window-approach | class Solution:
def longestSubstring(self, s: str, k: int) -> int:
# number of unique characters available
max_chars = len(set(s))
n = len(s)
ans = 0
# for all char from 1 to max_chars
for available_char in range(1,max_chars+1):
h = {}
i = j = 0
# simple sliding window approach
while(j < n):
if(s[j] not in h):
h[s[j]] = 0
h[s[j]] += 1
# if len of h is less than no of available chars
if(len(h) < available_char):
j += 1
# if equal then check all have values >=k
elif(len(h) == available_char):
count = 0
for x in h.values():
if(x >= k):
count += 1
if(count == available_char):
ans = max(ans,j - i + 1)
j += 1
# if greater than remove from starting
else:
while(len(h) != available_char):
h[s[i]] -= 1
if(h[s[i]] == 0):
del h[s[i]]
i += 1
j += 1
return ans | longest-substring-with-at-least-k-repeating-characters | easy sliding window approach | jagdishpawar8105 | 2 | 267 | longest substring with at least k repeating characters | 395 | 0.448 | Medium | 6,880 |
https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/825847/Python3-divide-and-conquer | class Solution:
def longestSubstring(self, s: str, k: int) -> int:
if not s: return 0 # edge case
freq = {} # frequency table
for c in s: freq[c] = 1 + freq.get(c, 0)
if min(freq.values()) < k:
m = min(freq, key=freq.get)
return max(self.longestSubstring(ss, k) for ss in s.split(m))
return len(s) | longest-substring-with-at-least-k-repeating-characters | [Python3] divide & conquer | ye15 | 2 | 279 | longest substring with at least k repeating characters | 395 | 0.448 | Medium | 6,881 |
https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/1847012/Python-easy-to-read-and-understand-or-recursion | class Solution:
def solve(self, s, k):
if len(s) < k:
return 0
for i in set(s):
if s.count(i) < k:
split = s.split(i)
ans = 0
for substring in split:
ans = max(ans, self.solve(substring, k))
return ans
return len(s)
def longestSubstring(self, s: str, k: int) -> int:
return self.solve(s, k) | longest-substring-with-at-least-k-repeating-characters | Python easy to read and understand | recursion | sanial2001 | 1 | 238 | longest substring with at least k repeating characters | 395 | 0.448 | Medium | 6,882 |
https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/2781833/python | class Solution:
def longestSubstring(self, s: str, k: int) -> int:
ret = 0
n = len(s)
for t in range(len(set(s)) + 1):
l, r = 0, 0
cnt = [0] * 26
tot, less = 0, 0
while r < n:
cnt[ord(s[r]) - 97] += 1
if cnt[ord(s[r]) - 97] == 1:
tot += 1
less += 1
if cnt[ord(s[r]) - 97] == k:
less -= 1
while tot > t:
cnt[ord(s[l]) - 97] -= 1
if cnt[ord(s[l]) - 97] == k - 1:
less += 1
if cnt[ord(s[l]) - 97] == 0:
tot -= 1
less -= 1
l += 1
if less == 0:
ret = max(ret, r - l + 1)
r += 1
return ret | longest-substring-with-at-least-k-repeating-characters | python | xy01 | 0 | 12 | longest substring with at least k repeating characters | 395 | 0.448 | Medium | 6,883 |
https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/2781833/python | class Solution:
def longestSubstring(self, s, k):
def dfs(s, l , r, k):
cnt = [0] * 26
for i in range(l, r + 1):
cnt[ord(s[i]) - 97] += 1
split = 0
for i in range(26):
if cnt[i] > 0 and cnt[i] < k:
split = chr(i + 97)
break
if split == 0:
return r - l + 1
i = l
ret = 0
while i <= r:
while i <= r and s[i] == split:
i += 1
if i > r:
break
start = i
while i <= r and s[i] != split:
i += 1
length = dfs(s, start, i - 1, k)
ret = max(ret, length)
return ret
n = len(s)
return dfs(s, 0, n - 1, k) | longest-substring-with-at-least-k-repeating-characters | python | xy01 | 0 | 12 | longest substring with at least k repeating characters | 395 | 0.448 | Medium | 6,884 |
https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/2733987/Faster-than-98-Easy-and-Small-Solution | class Solution:
def longestSubstring(self, s: str, k: int) -> int:
if k > len(s):
return 0
for letter in set(s):
if s.count(letter) < k:
temp = s.split(letter)
return max(self.longestSubstring(division, k) for division in temp)
return len(s) | longest-substring-with-at-least-k-repeating-characters | Faster than 98%, Easy and Small Solution | user6770yv | 0 | 12 | longest substring with at least k repeating characters | 395 | 0.448 | Medium | 6,885 |
https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/2722139/python-easy-solution-faster | class Solution:
def longestSubstring(self, s: str, k: int) -> int:
if(len(s)==0):
return 0
cnt=Counter(s)
for i,j in cnt.items():
if(j<k):
return max(self.longestSubstring(p,k) for p in s.split(i))
return len(s) | longest-substring-with-at-least-k-repeating-characters | python easy solution faster | Raghunath_Reddy | 0 | 17 | longest substring with at least k repeating characters | 395 | 0.448 | Medium | 6,886 |
https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/2657162/Python3-Solution-Divide-and-Conquer-Skip-repeat-charaters-when-Divide | class Solution:
def longestSubstring(self, s: str, k: int) -> int:
from collections import Counter
s_counter = Counter(s)
print('initial Counter', s_counter)
for i in range(len(s)):
if s_counter[s[i]]<k:
print('i position', i)
print('s[i] is less than k time', s[i])
print('search for s[:i]', s[:i])
len_s1 = self.longestSubstring(s[:i], k)
while i+1<len(s) and s[i+1] == s[i] and i+1<len(s):
i+=1
print('search for s[j:]', s[i+1:])
len_s2 = self.longestSubstring(s[i+1:], k)
return len_s2 if len_s2>len_s1 else len_s1
return len(s) | longest-substring-with-at-least-k-repeating-characters | Python3 Solution - Divide and Conquer - Skip repeat charaters when Divide | ben_wei | 0 | 8 | longest substring with at least k repeating characters | 395 | 0.448 | Medium | 6,887 |
https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/2433742/Divide-an-Conquer-oror-Recursion-oror-Python3 | class Solution:
def longestSubstring(self, s: str, k: int) -> int:
def divideConquer(string):
left = 0
right = 0
counter = Counter(string)
for index, char in enumerate(string):
if index == len(string) - 1 and counter[char]>=k:
return len(string)
if counter[char] < k:
left = divideConquer(string[:index])
right = divideConquer(string[index+1:])
break
return max(left,right)
return divideConquer(s) | longest-substring-with-at-least-k-repeating-characters | Divide an Conquer || Recursion || Python3 | Sefinehtesfa34 | 0 | 25 | longest substring with at least k repeating characters | 395 | 0.448 | Medium | 6,888 |
https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/2407423/Python-Solution-or-Recursive-Solution-or-90-Faster-or-Divide-and-Conquer | class Solution:
def longestSubstring(self, s: str, k: int) -> int:
# consider this as base case
if len(s) < k:
return 0
# get character with lowest frequency
minFChar, minF = collections.Counter(s).most_common()[-1]
# is minimum frequency valid?
if minF >= k:
return len(s)
# divide the og string with minFChar and recurse on all splits
return max(self.longestSubstring(newS,k) for newS in s.split(minFChar)) | longest-substring-with-at-least-k-repeating-characters | Python Solution | Recursive Solution | 90% Faster | Divide and Conquer | Gautam_ProMax | 0 | 83 | longest substring with at least k repeating characters | 395 | 0.448 | Medium | 6,889 |
https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/1869291/Python3-Sliding-Window-with-distinct-character-limit | class Solution:
def longestSubstring(self, s: str, k: int) -> int:
max_chars = len(Counter(s))
ans = 0
for size in range(1, max_chars+1):
i = 0
mp = Counter()
for j in range(len(s)):
# limit sliding window by number of distinct characters
while len(mp.values())>size:
mp[s[i]] -= 1
if mp[s[i]]==0: mp.pop(s[i])
i += 1
mp[s[j]] += 1
# update ans when all the character frequencies >= k
if all(v>=k for v in mp.values()):
ans = max(ans, sum(mp.values()))
return ans | longest-substring-with-at-least-k-repeating-characters | Python3 Sliding Window with distinct character limit | zhuzhengyuan824 | 0 | 278 | longest substring with at least k repeating characters | 395 | 0.448 | Medium | 6,890 |
https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/1709125/Python-or-Hashmap-or-Recursion | class Solution:
def longestSubstring(self, s: str, k: int) -> int:
ans=0
def dfs(tmp):
nonlocal ans
for x in tmp:
if x:
ct=Counter(x)
if ct.most_common()[-1][-1]>=k:#Case like 'ababab or aaabbb' Means all the characters in the curr string are greater or equal to k
ans=max(ans,len(x))
else:#case like 'aaabb or ababa' so again do the splitting
t=x[::]
for key,v in ct.items():
if v<k:
t=t.replace(key,'_')
dfs(t.split('_'))
dfs([s])
return ans | longest-substring-with-at-least-k-repeating-characters | Python | Hashmap | Recursion | heckt27 | 0 | 108 | longest substring with at least k repeating characters | 395 | 0.448 | Medium | 6,891 |
https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/1601863/Recursive-or-8-lines-codes | class Solution:
def longestSubstring(self, s: str, k: int) -> int:
if not s:
return 0
if len(s) < k:
return 0
for i in set(s):
if s.count(i)< k:
return max([self.longestSubstring(substr, k) for substr in s.split(i)])
return len(s) | longest-substring-with-at-least-k-repeating-characters | Recursive | 8 lines codes | zixin123 | 0 | 142 | longest substring with at least k repeating characters | 395 | 0.448 | Medium | 6,892 |
https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/503083/Simple!-By-counting-consecutive-repeating-chars | class Solution:
def longestSubstring(self, s: str, k: int) -> int:
c_counts = []
pc = None
n = 0
for c in s:
if pc is None:
pc = s
n = 1
else:
if pc == c:
n += 1
else:
c_counts.append((pc, n))
n = 1
pc = c
if pc:
c_counts.append((pc, n))
max_sub = 0
for left in range(len(c_counts)):
chars = {}
for right in range(left, len(c_counts)):
if not chars.get(c_counts[right][0]):
chars[c_counts[right][0]] = 0
chars[c_counts[right][0]] += c_counts[right][1]
if min(chars.values()) > k - 1:
max_sub = max(max_sub, sum(chars.values()))
return max_sub | longest-substring-with-at-least-k-repeating-characters | Simple! By counting consecutive repeating chars | user1409N | 0 | 219 | longest substring with at least k repeating characters | 395 | 0.448 | Medium | 6,893 |
https://leetcode.com/problems/rotate-function/discuss/857056/Python-3-(Py3.8)-or-Math-O(n)-or-Explanation | class Solution:
def maxRotateFunction(self, A: List[int]) -> int:
s, n = sum(A), len(A)
cur_sum = sum([i*j for i, j in enumerate(A)])
ans = cur_sum
for i in range(n): ans = max(ans, cur_sum := cur_sum + s-A[n-1-i]*n)
return ans | rotate-function | Python 3 (Py3.8) | Math, O(n) | Explanation | idontknoooo | 6 | 588 | rotate function | 396 | 0.404 | Medium | 6,894 |
https://leetcode.com/problems/rotate-function/discuss/1913574/Python-easy-understanding-solution-with-comment | class Solution:
def maxRotateFunction(self, nums: List[int]) -> int:
s, n = sum(nums), len(nums)
rotate_sum = 0
for i in range(n):
rotate_sum += nums[i] * i # ex. [0, 1, 2, 3] --> 0*0 + 1*1 + 2*2 + 3*3
res = rotate_sum
for i in range(n-1, 0 , -1):
rotate_sum += s - n * nums[i] # 0*0 + 1*1 + 2*2 + 3*3 --> 0*1 + 1*2 + 2*3 + 3*4 --> 0*1 + 1*2 + 2*3 + 3*0
res = max(res, rotate_sum) # update res
return res | rotate-function | Python easy - understanding solution with comment | byroncharly3 | 1 | 104 | rotate function | 396 | 0.404 | Medium | 6,895 |
https://leetcode.com/problems/rotate-function/discuss/825648/Python3-O(N)-time | class Solution:
def maxRotateFunction(self, A: List[int]) -> int:
ans = val = sum(i*x for i, x in enumerate(A))
ss = sum(A)
for x in reversed(A):
val += ss - len(A)*x
ans = max(ans, val)
return ans | rotate-function | [Python3] O(N) time | ye15 | 1 | 189 | rotate function | 396 | 0.404 | Medium | 6,896 |
https://leetcode.com/problems/rotate-function/discuss/2832843/Beat-98-Eliminate-redundant-re-calculation-DP-or-memo-python-simple-solution | class Solution:
def maxRotateFunction(self, nums: List[int]) -> int:
# 25 - 6 * (N - 1) + sum(nums) - 6
# cur - last_element * N + sum(nums)
# eliminate overlapping sub-problem, no need re-calculation
# only keep track last element
N = len(nums)
total = sum(nums)
cur = 0
for i in range(N):
cur += i * nums[i]
ret = cur
for i in range(N - 1, -1, -1):
cur = cur - nums[i] * N + total
ret = max(ret, cur)
return ret | rotate-function | Beat 98% / Eliminate redundant re-calculation / DP or memo / python simple solution | Lara_Craft | 0 | 2 | rotate function | 396 | 0.404 | Medium | 6,897 |
https://leetcode.com/problems/rotate-function/discuss/2800420/Python-(Simple-Dynamic-Programming) | class Solution:
def maxRotateFunction(self, nums):
n, total = len(nums), sum(nums)
dp = [0]*n
dp[0] = sum([i*j for i,j in enumerate(nums)])
for i in range(1,n):
dp[i] = dp[i-1] + (total - nums[n-i]*n)
return max(dp) | rotate-function | Python (Simple Dynamic Programming) | rnotappl | 0 | 3 | rotate function | 396 | 0.404 | Medium | 6,898 |
https://leetcode.com/problems/rotate-function/discuss/2705033/Python3-Solution-or-O(n) | class Solution:
def maxRotateFunction(self, A):
csum, n = sum(A), len(A)
ans = cur = sum(i * A[i] for i in range(n))
for i in range(n - 1):
cur += csum - A[n - i - 1] * n
ans = max(ans, cur)
return ans | rotate-function | ✔ Python3 Solution | O(n) | satyam2001 | 0 | 7 | rotate function | 396 | 0.404 | Medium | 6,899 |
Subsets and Splits