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/to-lower-case/discuss/2737982/LOWER-CASE-IN-SINGLE-LINE-CODE | class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower()
``` | to-lower-case | LOWER CASE IN SINGLE LINE CODE | festusmaithya264 | 0 | 1 | to lower case | 709 | 0.82 | Easy | 11,700 |
https://leetcode.com/problems/to-lower-case/discuss/2730435/Python3-solution | class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower() | to-lower-case | Python3 solution | sipi09 | 0 | 1 | to lower case | 709 | 0.82 | Easy | 11,701 |
https://leetcode.com/problems/to-lower-case/discuss/2710025/using-lower()-built-in-method | class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower() | to-lower-case | using lower() built in method | sindhu_300 | 0 | 6 | to lower case | 709 | 0.82 | Easy | 11,702 |
https://leetcode.com/problems/to-lower-case/discuss/2699417/Python-simple-one-liner | class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower() | to-lower-case | Python simple one liner | imkprakash | 0 | 3 | to lower case | 709 | 0.82 | Easy | 11,703 |
https://leetcode.com/problems/to-lower-case/discuss/2694934/PYTHON3-BEST | class Solution:
def toLowerCase(self, s: str) -> str:
ans = ""
for c in s:
n = ord(c)
ans += chr(n+32) if n > 64 and n < 91 else c
return ans | to-lower-case | PYTHON3 BEST | Gurugubelli_Anil | 0 | 3 | to lower case | 709 | 0.82 | Easy | 11,704 |
https://leetcode.com/problems/to-lower-case/discuss/2489010/Using-Python-String-lower() | class Solution:
def toLowerCase(self, s: str) -> str:
return(s.lower()) | to-lower-case | Using Python String lower() | payek | 0 | 19 | to lower case | 709 | 0.82 | Easy | 11,705 |
https://leetcode.com/problems/to-lower-case/discuss/2409821/simple-ororone-line-solution-ororpython | class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower() | to-lower-case | simple ||one line solution ||python | Sneh713 | 0 | 5 | to lower case | 709 | 0.82 | Easy | 11,706 |
https://leetcode.com/problems/to-lower-case/discuss/2251671/Python-using-ord()-and-chr()-to-utilize-ascii-values | class Solution:
def toLowerCase(self, s: str) -> str:
ascii_A, ascii_Z, diff_aA = ord('A'), ord('Z'), ord('a') - ord('A')
chars = []
# Iterate each char in string
for ch in s:
# Get the ascii numeric value of char
ascii_value = ord(ch)
# If value indicates char is uppercase
if ascii_A <= ascii_value <= ascii_Z:
# Add to the ascii value, the difference to make into its lowercase version
ascii_value += diff_aA
# Add the char version of transformed/not ascii value into chars
chars.append(chr(ascii_value))
# Return the stringified version
return ''.join(chars) | to-lower-case | Python using ord() and chr() to utilize ascii values | graceiscoding | 0 | 11 | to lower case | 709 | 0.82 | Easy | 11,707 |
https://leetcode.com/problems/to-lower-case/discuss/2198620/Python-Simple-Python-Solution-Using-Two-Approach | class Solution:
def toLowerCase(self, s: str) -> str:
s = list(s)
lowercase = 'abcdefghijklmnopqrstuvwxyz'
uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for i in range(len(s)):
if s[i] in uppercase:
index = uppercase.index(s[i])
s[i] = lowercase[index]
return ''.join(s) | to-lower-case | [ Python ] β
β
Simple Python Solution Using Two Approach π₯³βπ | ASHOK_KUMAR_MEGHVANSHI | 0 | 58 | to lower case | 709 | 0.82 | Easy | 11,708 |
https://leetcode.com/problems/to-lower-case/discuss/2198620/Python-Simple-Python-Solution-Using-Two-Approach | class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower() | to-lower-case | [ Python ] β
β
Simple Python Solution Using Two Approach π₯³βπ | ASHOK_KUMAR_MEGHVANSHI | 0 | 58 | to lower case | 709 | 0.82 | Easy | 11,709 |
https://leetcode.com/problems/to-lower-case/discuss/2160093/Python-one-liner | class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower() | to-lower-case | Python one liner | pro6igy | 0 | 30 | to lower case | 709 | 0.82 | Easy | 11,710 |
https://leetcode.com/problems/to-lower-case/discuss/2137886/lower-case | class Solution(object):
def toLowerCase(self, s):
"""
:type s: str
:rtype: str
"""
return s.lower() | to-lower-case | lower case | abhinav0904 | 0 | 42 | to lower case | 709 | 0.82 | Easy | 11,711 |
https://leetcode.com/problems/to-lower-case/discuss/2130039/Python-inbuilt-function | class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower() | to-lower-case | Python inbuilt function | yashkumarjha | 0 | 54 | to lower case | 709 | 0.82 | Easy | 11,712 |
https://leetcode.com/problems/to-lower-case/discuss/2064621/Python-List-Comprehension-2-liners-lambda-%2B-walrus | class Solution:
def toLowerCase(self, s: str) -> str:
hmap = dict(zip(string.ascii_uppercase,string.ascii_lowercase))
# Solution 1
return ''.join(hmap.get(letter, letter) for letter in s)
# Solution 2
# lambda + walrus (assignment expression)
# to_lower = lambda x: hmap.get(x, x)
# return ''.join(
# (x := to_lower(letter))
# for letter in s
# ) | to-lower-case | Python List Comprehension [2 liners] / lambda + walrus | kedeman | 0 | 32 | to lower case | 709 | 0.82 | Easy | 11,713 |
https://leetcode.com/problems/to-lower-case/discuss/1866445/Python3-Easy-One-line-Solution | class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower() | to-lower-case | [Python3] Easy One-line Solution | natscripts | 0 | 71 | to lower case | 709 | 0.82 | Easy | 11,714 |
https://leetcode.com/problems/to-lower-case/discuss/1854482/Python-one-line-solution | class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower() | to-lower-case | Python one line solution | alishak1999 | 0 | 35 | to lower case | 709 | 0.82 | Easy | 11,715 |
https://leetcode.com/problems/to-lower-case/discuss/1780847/python-oneliner | class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower() | to-lower-case | python oneliner | kakchaudhary | 0 | 54 | to lower case | 709 | 0.82 | Easy | 11,716 |
https://leetcode.com/problems/to-lower-case/discuss/1368988/Python3-ASCII-Solution | class Solution:
def toLowerCase(self, s: str) -> str:
retstring = ""
for i in range(0, len(s)):
if ord(s[i]) in range(65, 91):
newchar = ord(s[i]) + 32
retstring += chr(newchar)
else:
retstring += s[i]
return retstring | to-lower-case | Python3 ASCII Solution | RobertObrochta | 0 | 80 | to lower case | 709 | 0.82 | Easy | 11,717 |
https://leetcode.com/problems/to-lower-case/discuss/1228849/python-ez-understanding-solution | class Solution:
def toLowerCase(self, s: str) -> str:
DIFF_BETWEEN_LOWER_UPPER = ord('a') - ord('A')
output = ''
for char in s:
# A to Z
if ord(char) >= 65 and ord(char) <= 90:
output += chr(ord(char) + DIFF_BETWEEN_LOWER_UPPER)
else:
output += char
return output | to-lower-case | python ez understanding solution | yingziqing123 | 0 | 25 | to lower case | 709 | 0.82 | Easy | 11,718 |
https://leetcode.com/problems/to-lower-case/discuss/1208766/Python-Easy-ASCII-Code-Solution | class Solution:
def toLowerCase(self, str: str) -> str:
diff = ord('a') - ord('A')
res = ""
print(ord('a'))
print(ord('z'))
print(ord('A'))
print(ord('Z'))
for i in range(len(str)):
idx = ord(str[i])
if(idx>=97 and idx<=122 or idx>=65 and idx<=90):
if (idx<97):
res += chr(idx+diff)
else:
res += str[i]
else:
res += str[i]
return res
# return str.lower() | to-lower-case | Python Easy ASCII Code Solution | bagdaulet881 | 0 | 105 | to lower case | 709 | 0.82 | Easy | 11,719 |
https://leetcode.com/problems/to-lower-case/discuss/1146502/Python3-solution-(ASCII) | class Solution:
def toLowerCase(self, string: str) -> str:
if not string:
return string
result: str = ''
for char in string:
result += chr(ord(char) + 32) if 65 <= ord(char) <= 90 else char
return result | to-lower-case | Python3 solution (ASCII) | alexforcode | 0 | 74 | to lower case | 709 | 0.82 | Easy | 11,720 |
https://leetcode.com/problems/to-lower-case/discuss/1011962/Runtime%3A-20-ms-solution-with-Python-Generators | class Solution:
def toLowerCase(self, str: str) -> str:
def gen(string):
for i in string:
yield chr(ord(i) + 32) if 65 <= ord(i) <= 90 else i
return "".join(gen(str)) | to-lower-case | Runtime: 20 ms solution with Python Generators | hotassun | 0 | 81 | to lower case | 709 | 0.82 | Easy | 11,721 |
https://leetcode.com/problems/to-lower-case/discuss/915045/Memory-and-time-efficient-Python-3-solution | class Solution:
def toLowerCase(self, str: str) -> str:
res = []
for i in str:
avalue = ord(i)
if(avalue<91 and avalue>64):
res.append(chr(avalue + 32))
else:
res.append(i)
return ''.join(res) | to-lower-case | Memory and time efficient Python 3 solution | billvamva | 0 | 57 | to lower case | 709 | 0.82 | Easy | 11,722 |
https://leetcode.com/problems/to-lower-case/discuss/781487/Python-Easy-Solution | class Solution:
def toLowerCase(self, str: str) -> str:
for i in str:
if 65<=ord(i)<=97:
str=str.replace(i,chr(ord(i)+32))
return str | to-lower-case | Python Easy Solution | lokeshsenthilkumar | 0 | 308 | to lower case | 709 | 0.82 | Easy | 11,723 |
https://leetcode.com/problems/to-lower-case/discuss/762158/Python-3-using-ASCII-Trick. | class Solution:
def toLowerCase(self, str: str) -> str:
res = ''
space = ord(' ')
for letter in str:
if ord(letter) in range(65,91):
res += chr(ord(letter) ^ space)
else:
res += letter
return res | to-lower-case | Python 3 using ASCII Trick. | Renegade9819 | 0 | 118 | to lower case | 709 | 0.82 | Easy | 11,724 |
https://leetcode.com/problems/to-lower-case/discuss/384694/Python3-a-few-solutions | class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower() | to-lower-case | [Python3] a few solutions | ye15 | 0 | 145 | to lower case | 709 | 0.82 | Easy | 11,725 |
https://leetcode.com/problems/to-lower-case/discuss/384694/Python3-a-few-solutions | class Solution:
def toLowerCase(self, s: str) -> str:
mp = dict(zip(ascii_uppercase, ascii_lowercase))
return "".join(mp.get(c, c) for c in s) | to-lower-case | [Python3] a few solutions | ye15 | 0 | 145 | to lower case | 709 | 0.82 | Easy | 11,726 |
https://leetcode.com/problems/to-lower-case/discuss/384694/Python3-a-few-solutions | class Solution:
def toLowerCase(self, s: str) -> str:
s = list(s)
for i in range(len(s)):
if s[i].isupper(): s[i] = chr(ord(s[i]) ^ 32) # convert lowercase to uppercase or uppercase to lowercase
return "".join(s) | to-lower-case | [Python3] a few solutions | ye15 | 0 | 145 | to lower case | 709 | 0.82 | Easy | 11,727 |
https://leetcode.com/problems/to-lower-case/discuss/294452/python-soultion | class Solution:
def toLowerCase(self, s: str) -> str:
output = ''
for char in s:
ascii_index = ord(char)
if 65 <= ascii_index <= 90:
output += chr(ascii_index+32)
else:
output += char
return output | to-lower-case | python soultion | mike_d0_ob | 0 | 237 | to lower case | 709 | 0.82 | Easy | 11,728 |
https://leetcode.com/problems/random-pick-with-blacklist/discuss/2389935/faster-than-99.73-or-Python3-or-solution | class Solution:
def __init__(self, n: int, blacklist: List[int]):
self.hashmap={}
for b in blacklist:
self.hashmap[b]=-1
self.length=n-len(blacklist)
flag=n-1
for b in blacklist:
if b<self.length:
while flag in self.hashmap:
flag-=1
self.hashmap[b]=flag
flag-=1
def pick(self) -> int:
seed=random.randrange(self.length)
return self.hashmap.get(seed,seed)
# Your Solution object will be instantiated and called as such:
# obj = Solution(n, blacklist)
# param_1 = obj.pick() | random-pick-with-blacklist | faster than 99.73% | Python3 | solution | vimla_kushwaha | 1 | 152 | random pick with blacklist | 710 | 0.337 | Hard | 11,729 |
https://leetcode.com/problems/random-pick-with-blacklist/discuss/1683829/710.-Random-Pick-with-Blacklist-via-Hash-map | class Solution:
def __init__(self, n, blacklist):
self.whiteSize = n - len(blacklist)
self.hmap = {ele: 1 for ele in blacklist}
idx = n - 1
for ele in self.hmap:
if ele >= self.whiteSize:
continue
while idx in self.hmap:
idx -= 1
self.hmap[ele] = idx
idx -= 1
def pick(self):
index = randint(0, self.whiteSize - 1)
if index in self.hmap:
return self.hmap[index]
return index | random-pick-with-blacklist | 710. Random Pick with Blacklist via Hash map | zwang198 | 1 | 102 | random pick with blacklist | 710 | 0.337 | Hard | 11,730 |
https://leetcode.com/problems/random-pick-with-blacklist/discuss/2806536/Python-ranges | class Solution:
def __init__(self, n: int, blacklist):
self.n = n
self.ranges = []
self.index = 0
def insertIntoRanges(n):
left = 0
right = len(self.ranges) - 1
while left <= right:
middle = left + (right - left) // 2
a, b = self.ranges[middle]
if n >= a and n <= b:
return
if n - 1 == b:
self.ranges[middle][1] = n
if middle + 1 < len(self.ranges):
a1, b1 = self.ranges[middle + 1]
if n + 1 == a1:
self.ranges[middle] = [a, b1]
self.ranges.pop(middle + 1)
else:
self.ranges[middle] = [a, n]
else:
self.ranges[middle] = [a, n]
return
if n + 1 == a:
self.ranges[middle][0] = n
if middle - 1 >= 0:
a1, b1 = self.ranges[middle - 1]
if n - 1 == b1:
self.ranges[middle] = [a1, b]
self.ranges.pop(middle - 1)
else:
self.ranges[middle] = [n, b]
else:
self.ranges[middle] = [n, b]
return
if n > b:
left = middle + 1
elif n < a:
right = middle - 1
self.ranges.insert(left, [n, n])
for n in blacklist:
if not self.ranges:
self.ranges.append([n, n])
continue
insertIntoRanges(n)
if self.ranges:
self.ranges.append([self.n, float('inf')])
self.current = -1
self.allBanned = self.ranges and (self.ranges[0][0] <= 0 and self.ranges[0][1] >= self.n - 1)
def pick(self) -> int:
if self.allBanned:
return -1
self.current += 1
if self.current >= self.n:
self.current = 0
self.index = 0
if not self.ranges:
return self.current
a, b = self.ranges[self.index]
while self.current >= a:
self.current = b + 1
if self.current >= self.n:
self.current = 0
self.index = 0
else:
self.index += 1
a, b = self.ranges[self.index]
return self.current | random-pick-with-blacklist | Python, ranges | swepln | 0 | 3 | random pick with blacklist | 710 | 0.337 | Hard | 11,731 |
https://leetcode.com/problems/random-pick-with-blacklist/discuss/2757505/Map-invalid-to-valid%3A-dict() | class Solution:
def __init__(self, n: int, blacklist: List[int]):
self.black2valid = dict()
self.n = n
self.validSize = n - len(blacklist)
# Save all blacks in map, make sure mapping destinations are not in blacklist
for b in blacklist:
self.black2valid[b] = -1
last = n-1
for b in blacklist:
#[!] Only swap blacks in [0, validSize) to [validSize, n)
if b >= self.validSize:
continue
while last in self.black2valid:
last -= 1
self.black2valid[b] = last
#[!] DONT forget to update 'last'
last -= 1
def pick(self) -> int:
res = random.randint(0, self.validSize-1)
if res in self.black2valid:
res = self.black2valid[res]
return res | random-pick-with-blacklist | Map invalid to valid: dict() | KKCrush | 0 | 6 | random pick with blacklist | 710 | 0.337 | Hard | 11,732 |
https://leetcode.com/problems/random-pick-with-blacklist/discuss/2736861/Python-Hashmap-Simple | class Solution:
def __init__(self, n: int, blacklist: List[int]):
d = len(blacklist)
m = {}
bs = set(blacklist)
tb_mapped = [x for x in range(d+1) if x not in bs]
for x in blacklist:
if x >= d: # its in the second half
y = tb_mapped.pop(0)
m[x] = y
self.m = m
start, end = d, n-1
self.randint = lambda : randint(start, end)
def pick(self) -> int:
i = self.randint()
return self.m.get(i, i)
# Your Solution object will be instantiated and called as such:
# obj = Solution(n, blacklist)
# param_1 = obj.pick() | random-pick-with-blacklist | Python - Hashmap - Simple | naraharisetti | 0 | 11 | random pick with blacklist | 710 | 0.337 | Hard | 11,733 |
https://leetcode.com/problems/random-pick-with-blacklist/discuss/2666338/python-or-hashmap | class Solution:
def __init__(self, n: int, blacklist: List[int]):
# because the size of blacklist may be much smaller than blacklist
# so I am supposed to use blacklist mapping
m = len(blacklist)
# we will search the whitelist in this area, size is n - m
self.newsize, last = n - m, n - 1
# in order to search info in o(1)
black = set(blacklist)
self.mapping = {}
for num in blacklist:
if num >= self.newsize:
continue
while last in black:
last -= 1
self.mapping[num] = last
# don't forget reduce the scale of mapping
last -= 1
def pick(self) -> int:
# index of the whitelist array is (0, n - m - 1)
rand = random.randint(0, self.newsize - 1)
return self.mapping[rand] if rand in self.mapping else rand | random-pick-with-blacklist | python | hashmap | MichelleZou | 0 | 27 | random pick with blacklist | 710 | 0.337 | Hard | 11,734 |
https://leetcode.com/problems/random-pick-with-blacklist/discuss/1780188/Python-Dict-Mapping-or-O(1) | class Solution:
def __init__(self, n: int, blacklist: List[int]):
# The size of whitelist
self.white_len = n - len(blacklist)
# Last index of the array
self.last_idx = n - 1
# Mapping dictionary
self.mapping = {}
# Set the index of blacklist element all to -1
for i in blacklist:
self.mapping[i] = -1
for i in blacklist:
# skip blacklist
if i >= self.white_len:
continue
while self.last_idx in blacklist:
self.last_idx -= 1
self.mapping[i] = self.last_idx
self.last_idx -= 1
def pick(self) -> int:
idx = randint(0,self.white_len-1)
if idx in self.mapping:
return self.mapping[idx]
return idx | random-pick-with-blacklist | Python Dict Mapping | O(1) | Fayeyf | 0 | 115 | random pick with blacklist | 710 | 0.337 | Hard | 11,735 |
https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/discuss/1516574/Greedy-oror-DP-oror-Same-as-LCS | class Solution:
def minimumDeleteSum(self, s1: str, s2: str) -> int:
def lcs(s,p):
m,n = len(s),len(p)
dp = [[0 for _ in range(n+1)] for _ in range(m+1)]
for i in range(m):
for j in range(n):
if s[i]==p[j]:
dp[i+1][j+1] = dp[i][j]+ord(s[i])
else:
dp[i+1][j+1] = max(dp[i+1][j],dp[i][j+1])
return dp[-1][-1]
common = lcs(s1,s2)
total,res = 0,0
for c in s1:
total+=ord(c)
for c in s2:
total+=ord(c)
res = total - common*2
return res | minimum-ascii-delete-sum-for-two-strings | ππ Greedy || DP || Same as LCS π | abhi9Rai | 4 | 94 | minimum ascii delete sum for two strings | 712 | 0.623 | Medium | 11,736 |
https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/discuss/534770/Python3-top-down-dp | class Solution:
def minimumDeleteSum(self, s1: str, s2: str) -> int:
@lru_cache(None)
def fn(i, j):
"""Return minimum ASCII delete sum for s1[i:] and s2[j:]."""
if i == len(s1): return sum(ord(s2[jj]) for jj in range(j, len(s2)))
if j == len(s2): return sum(ord(s1[ii]) for ii in range(i, len(s1)))
if s1[i] == s2[j]: return fn(i+1, j+1)
return min(ord(s1[i]) + fn(i+1, j), ord(s2[j]) + fn(i, j+1))
return fn(0, 0) | minimum-ascii-delete-sum-for-two-strings | [Python3] top-down dp | ye15 | 1 | 63 | minimum ascii delete sum for two strings | 712 | 0.623 | Medium | 11,737 |
https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/discuss/2789414/python-super-easy-understand-dp-top-down | class Solution:
def minimumDeleteSum(self, s1: str, s2: str) -> int:
def ascii_sum(s):
return sum(map(lambda x: ord(x), list(s)))
@functools.lru_cache(None)
def dp(s1, s2):
if not s1 and not s2:
return 0
if not s1:
return ascii_sum(s2)
if not s2:
return ascii_sum(s1)
ans = float("inf")
if s1[0] == s2[0]:
ans = min(ans, dp(s1[1:], s2[1:]))
ans = min(ans, ord(s2[0]) + dp(s1, s2[1:]), ord(s1[0]) + dp(s1[1:], s2), ord(s1[0]) + ord(s2[0]) + dp(s1[1:], s2[1:]))
return ans
return dp(s1, s2) | minimum-ascii-delete-sum-for-two-strings | python super easy understand dp top down | harrychen1995 | 0 | 1 | minimum ascii delete sum for two strings | 712 | 0.623 | Medium | 11,738 |
https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/discuss/2785187/Python-oror-easy-solu-oror-using-DP-Bottom-up-approach | class Solution:
def minimumDeleteSum(self, s1: str, s2: str) -> int:
m=len(s1)
n=len(s2)
dp=[]
for i in range (m+1):
dp.append([0]*(n+1))
asc=0
for i in range (1,m+1):
asc+=ord(s1[i-1])
dp[i][0]=asc
asc=0
for j in range (1,n+1):
asc+=ord(s2[j-1])
dp[0][j]=asc
#print(dp)
for i in range (1,m+1):
for j in range (1,n+1):
if s1[i-1]==s2[j-1]:
dp[i][j]=dp[i-1][j-1]
else:
dp[i][j]=min(dp[i-1][j]+ord(s1[i-1]),dp[i][j-1]+ord(s2[j-1]))
return dp[-1][-1] | minimum-ascii-delete-sum-for-two-strings | Python || easy solu || using DP Bottom up approach | tush18 | 0 | 3 | minimum ascii delete sum for two strings | 712 | 0.623 | Medium | 11,739 |
https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/discuss/2750790/Python3-or-Easy-Solution | class Solution:
def minimumDeleteSum(self, s1: str, s2: str) -> int:
m = len(s1)
n = len(s2)
table = [[0 for x in range(n+1)] for x in range(m+1)]
total = 0
Flag = True
for i in range(1,m+1):
total+=ord(s1[i-1])
for j in range(1,n+1):
if(Flag):
total+=ord(s2[j-1])
if(s1[i-1]==s2[j-1]):
table[i][j] = max(table[i-1][j],table[i][j-1],table[i-1][j-1]+ord(s1[i-1]))
else:
table[i][j] = max(table[i-1][j],table[i][j-1])
Flag = False
return total-table[-1][-1]*2 | minimum-ascii-delete-sum-for-two-strings | Python3 | Easy Solution | ty2134029 | 0 | 4 | minimum ascii delete sum for two strings | 712 | 0.623 | Medium | 11,740 |
https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/discuss/2305648/Python3-Solution-with-using-dp | class Solution:
def minimumDeleteSum(self, s1: str, s2: str) -> int:
dp = [[0] * (len(s2) + 1) for _ in range(len(s1) + 1)]
for i in range(1, len(s1) + 1):
dp[i][0] = ord(s1[i - 1]) + dp[i - 1][0]
for j in range(1, len(s2) + 1):
dp[0][j] = ord(s2[j - 1]) + dp[0][j - 1]
for i in range(1, len(s1) + 1):
for j in range(1, len(s2) + 1):
if s1[i - 1] == s2[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
else:
dp[i][j] = min(dp[i - 1][j] + ord(s1[i - 1]), dp[i][j - 1] + ord(s2[j - 1]))
return dp[-1][-1] | minimum-ascii-delete-sum-for-two-strings | [Python3] Solution with using dp | maosipov11 | 0 | 18 | minimum ascii delete sum for two strings | 712 | 0.623 | Medium | 11,741 |
https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/discuss/1673245/Python-DP-1-D | class Solution:
def minimumDeleteSum(self, s1: str, s2: str) -> int:
@lru_cache(None)
def getASCII(char):
return ord(char)
if len(s1) < len(s2):
s1, s2 = s2, s1
m, n = len(s1), len(s2)
dp = [0]*(n+1)
for i in range(1, n+1):
dp[i] += dp[i-1] + getASCII(s2[i-1])
for i in range(1, m+1):
new_dp = [0]*(n+1)
new_dp[0] = dp[0] + getASCII(s1[i-1])
for j in range(1, n+1):
if s1[i-1] == s2[j-1]:
new_dp[j] = dp[j-1]
else:
new_dp[j] = min(getASCII(s1[i-1])+dp[j], getASCII(s2[j-1])+new_dp[j-1])
dp = new_dp
return dp[-1] | minimum-ascii-delete-sum-for-two-strings | Python DP 1-D | sankitshane | 0 | 33 | minimum ascii delete sum for two strings | 712 | 0.623 | Medium | 11,742 |
https://leetcode.com/problems/subarray-product-less-than-k/discuss/481917/Python-sol.-based-on-sliding-window.-run-time-90%2B-w-Explanation | class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
if k <= 1:
# Quick response for invalid k on product of positive numbers
return 0
else:
left_sentry = 0
num_of_subarray = 0
product_of_subarry = 1
# update right bound of sliding window
for right_sentry in range( len(nums) ):
product_of_subarry *= nums[right_sentry]
# update left bound of sliding window
while product_of_subarry >= k:
product_of_subarry //= nums[left_sentry]
left_sentry += 1
# Note:
# window size = right_sentry - left_sentry + 1
# update number of subarrary with product < k
num_of_subarray += right_sentry - left_sentry + 1
return num_of_subarray | subarray-product-less-than-k | Python sol. based on sliding window. run-time 90%+ [ w/ Explanation ] | brianchiang_tw | 3 | 723 | subarray product less than k | 713 | 0.452 | Medium | 11,743 |
https://leetcode.com/problems/subarray-product-less-than-k/discuss/1805381/Python-3-sliding-window-O(n)-O(1) | class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
if k <= 1:
return 0
res = 0
product = 1
left = 0
for right, num in enumerate(nums):
product *= num
while product >= k:
product //= nums[left]
left += 1
res += right - left + 1
return res | subarray-product-less-than-k | Python 3, sliding window, O(n) / O(1) | dereky4 | 2 | 242 | subarray product less than k | 713 | 0.452 | Medium | 11,744 |
https://leetcode.com/problems/subarray-product-less-than-k/discuss/1616411/Easy-to-understand-python3-sliding-window-solution | class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
n=len(nums)
left=0
res=0
prod=1
for right in range(n):
prod*=nums[right]
while prod>=k and left<=right:
prod=prod/nums[left]
left+=1
res+=(right-left+1)
return res | subarray-product-less-than-k | Easy to understand python3 sliding window solution | Karna61814 | 1 | 54 | subarray product less than k | 713 | 0.452 | Medium | 11,745 |
https://leetcode.com/problems/subarray-product-less-than-k/discuss/1023283/Python-From-TLE-to-AC-greater-Leading-and-Lagging-Two-Pointer-Approach | class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
prefix, result = [1] + list(itertools.accumulate(nums, operator.mul)), 0
for i in range(1, len(prefix)):
for j in range(0, i):
if prefix[i] // prefix[j] < k:
result += (i-j)
break
return result | subarray-product-less-than-k | [Python] From TLE to AC --> Leading & Lagging Two Pointer Approach | dev-josh | 1 | 117 | subarray product less than k | 713 | 0.452 | Medium | 11,746 |
https://leetcode.com/problems/subarray-product-less-than-k/discuss/1023283/Python-From-TLE-to-AC-greater-Leading-and-Lagging-Two-Pointer-Approach | class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
result = 0
product = 1
lagging = 0
for leading in range(len(nums)):
product *= nums[leading]
while product >= k and lagging <= leading:
product /= nums[lagging]
lagging += 1
sub_arr_len = leading - lagging + 1
result += sub_arr_len
return result | subarray-product-less-than-k | [Python] From TLE to AC --> Leading & Lagging Two Pointer Approach | dev-josh | 1 | 117 | subarray product less than k | 713 | 0.452 | Medium | 11,747 |
https://leetcode.com/problems/subarray-product-less-than-k/discuss/869622/Python3-Simple-Sliding-Window-with-comments | class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
# Edge cases
if len(nums) < 1: return 0
if len(nums) < 2: return 1 if nums[0] < k else 0
# Count all the single element subset of the arrays that are less than k
count = 0
for num in nums:
count += 1 if num < k else 0
# Maintain a sliding window from left=[0] to right=[1]. Whenever the current product of the window reaches over
# the limit - k, move the left pointer until the limit (of product < k) is satisfied again.
cur = nums[0]
left, right = 0, 1
while right < len(nums):
cur *= nums[right]
while left < right and cur >= k:
cur //= nums[left]
left += 1
count += (right - left)
right += 1
return count | subarray-product-less-than-k | [Python3] Simple Sliding Window with comments | nachiketsd | 1 | 71 | subarray product less than k | 713 | 0.452 | Medium | 11,748 |
https://leetcode.com/problems/subarray-product-less-than-k/discuss/869070/Python3-sliding-window | class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
ans = ii = 0
prod = 1
for i, x in enumerate(nums):
prod *= x
while ii <= i and k <= prod:
prod //= nums[ii]
ii += 1
ans += i - ii + 1
return ans | subarray-product-less-than-k | [Python3] sliding window | ye15 | 1 | 88 | subarray product less than k | 713 | 0.452 | Medium | 11,749 |
https://leetcode.com/problems/subarray-product-less-than-k/discuss/2833258/Python-O(n)-solution-Accepted | class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
if k <= 1: return 0
ans: int = 0
left: int = 0
prod: int = 1
for right, val in enumerate(nums):
prod *= val
while prod >= k:
prod /= nums[left]
left += 1
ans += right - left + 1
return ans | subarray-product-less-than-k | Python O(n) solution [Accepted] | lllchak | 0 | 1 | subarray product less than k | 713 | 0.452 | Medium | 11,750 |
https://leetcode.com/problems/subarray-product-less-than-k/discuss/2812575/Python-Easy-Solution-Sliding-Window | class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
ans = 0
left = 0
right = 0
product = 1
while right < len(nums):
# Get the number, extend right part of the window, and record product
n = nums[right]
product = product * n
while product >= k and left <= right:
# update left part of the window by conditions
d = nums[left]
product = product / d
left += 1
ans += right - left + 1 # update answer, +1 because of the update of right part of the window
right += 1
return ans | subarray-product-less-than-k | Python Easy Solution Sliding Window | yl9539 | 0 | 1 | subarray product less than k | 713 | 0.452 | Medium | 11,751 |
https://leetcode.com/problems/subarray-product-less-than-k/discuss/2793423/Python-or-Simple-or-Sliding-Window-or-O(n) | class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
start, product, result = 0, 1, 0
for end in range(len(nums)):
curr_val = nums[end]
product *= curr_val
while product >= k and start <= end:
product = product / nums[start]
start += 1
if product < k:
result += end - start + 1
return result | subarray-product-less-than-k | Python | Simple | Sliding Window | O(n) | david-cobbina | 0 | 4 | subarray product less than k | 713 | 0.452 | Medium | 11,752 |
https://leetcode.com/problems/subarray-product-less-than-k/discuss/2723155/Python3-Two-pointers-Solution | class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
left = 0
mult = 1
ans = 0
if k <= 1:
return 0
for right in range(len(nums)):
mult *= nums[right]
while mult >= k:
mult = mult // nums[left]
left += 1
ans += (right-left+1)
return ans | subarray-product-less-than-k | Python3 Two pointers Solution | DietCoke777 | 0 | 7 | subarray product less than k | 713 | 0.452 | Medium | 11,753 |
https://leetcode.com/problems/subarray-product-less-than-k/discuss/2722993/Two-Pointer-Python-Solution | class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
left = 0
mult = 1
ans = 0
if k <= 1:
return 0
for right in range(len(nums)):
mult *= nums[right]
while mult >= k:
mult = mult // nums[left]
left += 1
ans += (right-left+1)
return ans | subarray-product-less-than-k | Two Pointer Python Solution | DietCoke777 | 0 | 2 | subarray product less than k | 713 | 0.452 | Medium | 11,754 |
https://leetcode.com/problems/subarray-product-less-than-k/discuss/2711317/Python-EASY-sliding-window | class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
prod = 1
left = 0
count = 0
for right,v in enumerate(nums):
prod *= v
while prod >= k and left <= right:
prod //= nums[left]
left += 1
count += right - left + 1
return count | subarray-product-less-than-k | Python EASY sliding window | anu1rag | 0 | 4 | subarray product less than k | 713 | 0.452 | Medium | 11,755 |
https://leetcode.com/problems/subarray-product-less-than-k/discuss/2641534/Python-easy-approach-pattern-fixed-size-sliding-windows | class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
count = 0
i = 0
multi = 1
for j in range(len(nums)):
multi *= nums[j]
while(multi >= k and i <= j):
multi //= nums[i]
i += 1
if(multi < k):
count += j-i+1
return count | subarray-product-less-than-k | Python easy approach pattern fixed size sliding windows | rajitkumarchauhan99 | 0 | 6 | subarray product less than k | 713 | 0.452 | Medium | 11,756 |
https://leetcode.com/problems/subarray-product-less-than-k/discuss/1465457/PyPy3-Simple-solution-using-two-for-loops-w-comments | class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
# Init
n = len(nums)
m = 0 # no. of subarrays
# Base Case
if k == 0:
return 0
# Base Case
if sum(nums) == n:
return (n)*(n+1)//2 if k > 1 else 0
# For each element
for i,num_i in enumerate(nums):
# Calc curr product
curr_prod = num_i
# Check if is less then k, else continue
if curr_prod < k:
m += 1
else:
continue
# For each j from i+1 to n-1
for num_j in nums[i+1:]:
# calc current product
curr_prod = curr_prod * num_j
# Check if is less then k, else break
if curr_prod < k:
m += 1
else:
break
return m | subarray-product-less-than-k | [Py/Py3] Simple solution using two for loops w/ comments | ssshukla26 | 0 | 74 | subarray product less than k | 713 | 0.452 | Medium | 11,757 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/1532323/Python3-dp | class Solution:
def maxProfit(self, prices: List[int]) -> int:
buy, sell = inf, 0
for x in prices:
buy = min(buy, x)
sell = max(sell, x - buy)
return sell | best-time-to-buy-and-sell-stock-with-transaction-fee | [Python3] dp | ye15 | 4 | 78 | best time to buy and sell stock with transaction fee | 714 | 0.644 | Medium | 11,758 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/1532323/Python3-dp | class Solution:
def maxProfit(self, prices: List[int]) -> int:
buy, sell = inf, 0
for x in prices:
buy = min(buy, x - sell)
sell = max(sell, x - buy)
return sell | best-time-to-buy-and-sell-stock-with-transaction-fee | [Python3] dp | ye15 | 4 | 78 | best time to buy and sell stock with transaction fee | 714 | 0.644 | Medium | 11,759 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/1532323/Python3-dp | class Solution:
def maxProfit(self, prices: List[int]) -> int:
buy, sell = [inf]*2, [0]*2
for x in prices:
for i in range(2):
if i: buy[i] = min(buy[i], x - sell[i-1])
else: buy[i] = min(buy[i], x)
sell[i] = max(sell[i], x - buy[i])
return sell[1] | best-time-to-buy-and-sell-stock-with-transaction-fee | [Python3] dp | ye15 | 4 | 78 | best time to buy and sell stock with transaction fee | 714 | 0.644 | Medium | 11,760 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/1532323/Python3-dp | class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
if k >= len(prices)//2: return sum(max(0, prices[i] - prices[i-1]) for i in range(1, len(prices)))
buy, sell = [inf]*k, [0]*k
for x in prices:
for i in range(k):
if i: buy[i] = min(buy[i], x - sell[i-1])
else: buy[i] = min(buy[i], x)
sell[i] = max(sell[i], x - buy[i])
return sell[-1] if k and prices else 0 | best-time-to-buy-and-sell-stock-with-transaction-fee | [Python3] dp | ye15 | 4 | 78 | best time to buy and sell stock with transaction fee | 714 | 0.644 | Medium | 11,761 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/1532323/Python3-dp | class Solution:
def maxProfit(self, prices: List[int]) -> int:
buy, cooldown, sell = inf, 0, 0
for x in prices:
buy = min(buy, x - cooldown)
cooldown = sell
sell = max(sell, x - buy)
return sell | best-time-to-buy-and-sell-stock-with-transaction-fee | [Python3] dp | ye15 | 4 | 78 | best time to buy and sell stock with transaction fee | 714 | 0.644 | Medium | 11,762 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/1532323/Python3-dp | class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
buy, sell = inf, 0
for x in prices:
buy = min(buy, x - sell)
sell = max(sell, x - buy - fee)
return sell | best-time-to-buy-and-sell-stock-with-transaction-fee | [Python3] dp | ye15 | 4 | 78 | best time to buy and sell stock with transaction fee | 714 | 0.644 | Medium | 11,763 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/2179215/Python-or-4-Approaches-or-Entire-DP-or | class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
n = len(prices)
dp = [[-1 for i in range(2)] for i in range(n+1)]
dp[n][0] = dp[n][1] = 0
ind = n-1
while(ind>=0):
for buy in range(2):
if(buy):
profit = max(-prices[ind]-fee + dp[ind+1][0], 0 + dp[ind+1][1])
else:
profit = max(prices[ind] + dp[ind+1][1], 0 + dp[ind+1][0])
dp[ind][buy] = profit
ind -= 1
return dp[0][1] | best-time-to-buy-and-sell-stock-with-transaction-fee | Python | 4 Approaches | Entire DP | | LittleMonster23 | 2 | 68 | best time to buy and sell stock with transaction fee | 714 | 0.644 | Medium | 11,764 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/2179215/Python-or-4-Approaches-or-Entire-DP-or | class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
n = len(prices)
ahead = [0 for i in range(2)]
curr = [0 for i in range(2)]
ahead[0] = ahead[1] = 0
ind = n-1
while(ind>=0):
for buy in range(2):
if(buy):
profit = max(-prices[ind]-fee + ahead[0], 0 + ahead[1])
else:
profit = max(prices[ind] + ahead[1], 0 + ahead[0])
curr[buy] = profit
ahead = [x for x in curr]
ind -= 1
return ahead[1] | best-time-to-buy-and-sell-stock-with-transaction-fee | Python | 4 Approaches | Entire DP | | LittleMonster23 | 2 | 68 | best time to buy and sell stock with transaction fee | 714 | 0.644 | Medium | 11,765 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/1772301/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up) | class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
n = len(prices)
@lru_cache(None)
def dp(i: int, holding: int):
if i == n:
return 0
do_nothing = dp(i+1, holding)
do_something = 0
if holding:
# sell stock
do_something = prices[i]-fee + dp(i+1, 0)
else:
# buy stock
do_something = -prices[i] + dp(i+1, 1)
return max(do_nothing, do_something)
return dp(0, 0) | best-time-to-buy-and-sell-stock-with-transaction-fee | β
[Java / Python3] Simple DP Solution (Top-Down & Bottom-Up) | JawadNoor | 2 | 108 | best time to buy and sell stock with transaction fee | 714 | 0.644 | Medium | 11,766 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/1772301/Java-Python3-Simple-DP-Solution-(Top-Down-and-Bottom-Up) | class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
n = len(prices)
dp = [[0]*2 for _ in range(n+1)]
for i in range(n-1, -1, -1):
for holding in range(2):
do_nothing = dp[i+1][holding]
if holding:
# sell stock
do_something = prices[i]-fee+dp[i+1][0]
else:
do_something = -prices[i] + dp[i+1][1]
dp[i][holding] = max(do_nothing, do_something)
return dp[0][0] | best-time-to-buy-and-sell-stock-with-transaction-fee | β
[Java / Python3] Simple DP Solution (Top-Down & Bottom-Up) | JawadNoor | 2 | 108 | best time to buy and sell stock with transaction fee | 714 | 0.644 | Medium | 11,767 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/2430429/Python-Easy-Memoization-Solution | class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
memo = {}
def dfs(index, buy):
if index>=len(prices):
return 0
if (index, buy) in memo:
return memo[(index, buy)]
res = 0
if buy:
yb = dfs(index+1, not buy)-prices[index]
nb = dfs(index+1, buy)
res = max(yb, nb)
else:
ys = dfs(index+1, not buy)+prices[index]-fee
ns = dfs(index+1, buy)
res = max(ys, ns)
memo[(index,buy)] = res
return res
return dfs(0,True) | best-time-to-buy-and-sell-stock-with-transaction-fee | Python Easy Memoization Solution | joelkurien | 1 | 65 | best time to buy and sell stock with transaction fee | 714 | 0.644 | Medium | 11,768 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/1592779/Python-oror-Easy-Solution-oror-O(n)-and-without-extra-space | class Solution:
def maxProfit(self, lst: List[int], fee: int) -> int:
old_buy, old_sell = -lst[0], 0
for i in range(1, len(lst)):
new_buy, new_sell = 0, 0
if (old_sell - lst[i]) > old_buy:
new_buy = (old_sell - lst[i])
else:
new_buy = old_buy
if (lst[i] + old_buy - fee) > old_sell:
new_sell = (lst[i] + old_buy - fee)
else:
new_sell = old_sell
old_buy, old_sell = new_buy, new_sell
return old_sell | best-time-to-buy-and-sell-stock-with-transaction-fee | Python || Easy Solution || O(n) and without extra space | naveenrathore | 1 | 74 | best time to buy and sell stock with transaction fee | 714 | 0.644 | Medium | 11,769 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/840566/very-simple-python3-solution-or-memoization-or-recursive | class Solution:
def Util(self, i, prices, fee, bought, l, mem):
if i >= l:
return 0
if (i, bought) in mem:
return mem[(i, bought)]
if not bought:
cur = max((self.Util(i + 1, prices, fee, True, l, mem) - prices[i]), self.Util(i + 1, prices, fee, False, l, mem))
else:
cur = max((self.Util(i + 1, prices, fee, False, l, mem) + prices[i] - fee), self.Util(i + 1, prices, fee, True, l, mem))
mem[(i, bought)] = cur
return cur
def maxProfit(self, prices: List[int], fee: int) -> int:
return self.Util(0, prices, fee, False, len(prices), dict()) | best-time-to-buy-and-sell-stock-with-transaction-fee | very simple python3 solution | memoization | recursive | _YASH_ | 1 | 161 | best time to buy and sell stock with transaction fee | 714 | 0.644 | Medium | 11,770 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/2817354/Python-(Simple-DP) | class Solution:
def maxProfit(self, prices, fee):
@lru_cache(None)
def dp(idx,canBuy):
if idx >= len(prices):
return 0
max_val = dp(idx+1,canBuy)
if canBuy:
max_val = max(max_val,dp(idx+1,False)-prices[idx])
else:
max_val = max(max_val,dp(idx+1,True)+prices[idx]-fee)
return max_val
return dp(0,True) | best-time-to-buy-and-sell-stock-with-transaction-fee | Python (Simple DP) | rnotappl | 0 | 2 | best time to buy and sell stock with transaction fee | 714 | 0.644 | Medium | 11,771 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/2731047/Python3-or-O(n)-Solution | class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
stack = []
ans = 0
for price in prices:
if(len(stack)==0):
stack.append(price)
elif(len(stack)==1):
if(price-stack[-1]>fee):
stack.append(price)
elif(price<stack[-1]):
stack[-1] = price
else:
if(price>stack[-1]):
stack[-1] = price
elif(stack[-1]-price>=fee):
ans+=stack[-1]-stack[-2]-fee
stack = [price]
if(len(stack)>1):
ans+=stack[-1]-stack[-2]-fee
return ans | best-time-to-buy-and-sell-stock-with-transaction-fee | Python3 | O(n) Solution | ty2134029 | 0 | 4 | best time to buy and sell stock with transaction fee | 714 | 0.644 | Medium | 11,772 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/2691596/Simple-Python-solution-or-Caching-or-DP | class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
dp = {}
def dfs(i, buying):
if i >= len(prices):
return 0
if (i,buying) in dp:
return dp[(i,buying)]
ans = dfs(i+1, buying)
if buying:
buy = dfs(i+1, False)
ans = max(ans, buy - prices[i])
else:
sell = dfs(i+1, True)
ans = max(ans, sell + prices[i] - fee)
dp[(i,buying)] = ans
return dp[(i,buying)]
return dfs(0, True) | best-time-to-buy-and-sell-stock-with-transaction-fee | Simple Python solution | Caching | DP | user1508i | 0 | 10 | best time to buy and sell stock with transaction fee | 714 | 0.644 | Medium | 11,773 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/2639528/DP-Table-solution-in-Python | class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
# dp[i][0 or 1] indicates the max profit on i-th day when currently holding stock(1) or not(0) with unlimited buys/sells
n = len(prices) # number of days
dp = [[0] * 2 for i in range(n)]
dp[0][1] = -prices[0] - fee
for i in range(1, n):
dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i]) # sell stock on i-th day
dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i] - fee) # buy stock on i-th day
return dp[n-1][0] | best-time-to-buy-and-sell-stock-with-transaction-fee | DP Table solution in Python | leqinancy | 0 | 6 | best time to buy and sell stock with transaction fee | 714 | 0.644 | Medium | 11,774 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/2431697/Python-DP-solution-(Memoization) | class Solution:
def maxProfit(self, prices: List[int], fee : int) -> int:
d = {}
def bs(index, buyOrNotBuy):
if index >= len(prices):
return 0
# if we are able to buy the stock, if we already sold it before or
# if we have not bought any stock
if buyOrNotBuy == "buy":
# if buy stock at this index
if (index+1, "notBuy") not in d:
profit = -1 * prices[index] + bs(index+1, "notBuy")
else:
profit = -1 * prices[index] + d[(index+1, "notBuy")]
# if buy later, not now at this index
if (index+1, "buy") not in d:
profit1 = bs(index+1, "buy")
else:
profit1 = d[(index+1, "buy")]
d[(index, buyOrNotBuy)] = max(profit, profit1)
return d[(index, buyOrNotBuy)]
else:
# sell stock, if we sell 2nd argument is buy
# sell stock at this index
if (index+1, "buy") not in d:
profit = prices[index] + bs(index+1, "buy") - fee
else:
profit = prices[index] + d[(index+1, "buy")] - fee
# sell stock not at this index now, sell it later
if (index+1, "notBuy") not in d:
profit1 = bs(index+1, "notBuy")
else:
profit1 = d[(index+1, "notBuy")]
d[(index, buyOrNotBuy)] = max(profit, profit1)
return d[(index, buyOrNotBuy)]
return bs(0, "buy") | best-time-to-buy-and-sell-stock-with-transaction-fee | Python DP solution (Memoization) | DietCoke777 | 0 | 21 | best time to buy and sell stock with transaction fee | 714 | 0.644 | Medium | 11,775 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/2238166/Buy-and-sell-stock-2-variation-slight-change-pythin | class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
n=len(prices)
dp=[[0 for _ in range(2)] for _ in range(n+1)]
# base case , when array get exhausted , profit is always 0
for buy in range(2):
dp[n][buy]=0
for i in range(n-1,-1,-1):
for buy in range(2):
profit=0
# Buy or do-not buy
if buy:
profit+=max(-prices[i]+dp[i+1][0],dp[i+1][1])
else:
# sell or don't sell , subtract transaction fees after each transaction
profit+=max(prices[i]-fee+dp[i+1][1],dp[i+1][0])
dp[i][buy]=profit
return dp[0][1] | best-time-to-buy-and-sell-stock-with-transaction-fee | Buy and sell stock 2 variation , slight change , pythin | Aniket_liar07 | 0 | 37 | best time to buy and sell stock with transaction fee | 714 | 0.644 | Medium | 11,776 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/1784145/Python-easy-to-read-and-understand-or-DP | class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
n = len(prices)
t = [[0 for _ in range(2)] for _ in range(n)]
t[0][0], t[0][1] = -prices[0], 0
for i in range(1, n):
t[i][0] = max(t[i-1][0], t[i-1][1]-prices[i])
t[i][1] = max(t[i-1][1], t[i-1][0]+prices[i]-fee)
return max(t[n-1]) | best-time-to-buy-and-sell-stock-with-transaction-fee | Python easy to read and understand | DP | sanial2001 | 0 | 73 | best time to buy and sell stock with transaction fee | 714 | 0.644 | Medium | 11,777 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/1735709/Python-%2B-Easy-Approach | class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
obsp = -prices[0] # Old Bought State Profit
ossp = 0 # Old Sell State Profit
for i in range(1, len(prices)):
nbsp = 0
nssp = 0
# Time to Buy...
if ossp-prices[i] > obsp:
nbsp = ossp-prices[i]
else:
nbsp = obsp
# Time to Sell...
if obsp+prices[i]-fee > ossp:
nssp = obsp+prices[i]-fee
else:
nssp = ossp
obsp = nbsp
ossp = nssp
return ossp | best-time-to-buy-and-sell-stock-with-transaction-fee | [Python] + Easy Approach β | leet_satyam | 0 | 93 | best time to buy and sell stock with transaction fee | 714 | 0.644 | Medium | 11,778 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/1601380/Python3-One-pass-solution | class Solution:
def maxProfit(self, prices, fee):
if len(prices) < 2:
return 0
res = 0
buy = prices[0]
for i in range(1, len(prices)):
if prices[i] < buy:
buy = prices[i]
elif prices[i] - buy > fee:
res += prices[i] - buy - fee
buy = prices[i] - fee # we pay the commission as if once
return res | best-time-to-buy-and-sell-stock-with-transaction-fee | [Python3] One pass solution | maosipov11 | 0 | 36 | best time to buy and sell stock with transaction fee | 714 | 0.644 | Medium | 11,779 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/1475941/Python3-or-Recursion%2BMemoization | class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
self.dp=[[-1 for i in range(2)] for i in range(50001)]
return self.dfs(0,0,prices,fee)
def dfs(self,day,own,prices,fee):
if day==len(prices):
return 0
if self.dp[day][own]!=-1:
return self.dp[day][own]
if own:
p1=prices[day]-fee+self.dfs(day+1,not own,prices,fee)
p2=self.dfs(day+1,own,prices,fee)
self.dp[day][own]=max(p1,p2)
else:
p1=-(prices[day])+self.dfs(day+1,not own,prices,fee) #here we are sending(not own) bcoz own is 0
p2=self.dfs(day+1,own,prices,fee)# here we are sending(own) bcoz own is 0
self.dp[day][own]=max(p1,p2)
return self.dp[day][own] | best-time-to-buy-and-sell-stock-with-transaction-fee | [Python3] | Recursion+Memoization | swapnilsingh421 | 0 | 75 | best time to buy and sell stock with transaction fee | 714 | 0.644 | Medium | 11,780 |
https://leetcode.com/problems/1-bit-and-2-bit-characters/discuss/2012976/Python-Clean-and-Simple! | class Solution:
def isOneBitCharacter(self, bits):
i, n, numBits = 0, len(bits), 0
while i < n:
bit = bits[i]
if bit == 1:
i += 2
numBits = 2
else:
i += 1
numBits = 1
return numBits == 1 | 1-bit-and-2-bit-characters | Python - Clean and Simple! | domthedeveloper | 2 | 146 | 1 bit and 2 bit characters | 717 | 0.46 | Easy | 11,781 |
https://leetcode.com/problems/1-bit-and-2-bit-characters/discuss/1049624/optimal-solution-for-python | class Solution:
def isOneBitCharacter(self, bits: List[int]) -> bool:
i=0
count=0
while i<len(bits):
if bits[i]==1:
count=2
i+=2
else:
count=1
i+=1
return count%2 | 1-bit-and-2-bit-characters | optimal solution for python | captain10x | 1 | 118 | 1 bit and 2 bit characters | 717 | 0.46 | Easy | 11,782 |
https://leetcode.com/problems/1-bit-and-2-bit-characters/discuss/380693/Solution-in-Python-3-(three-lines) | class Solution:
def isOneBitCharacter(self, b: List[int]) -> bool:
L, i = len(b)-1, 0
while i < L: i += 1 + b[i]
return True if i == L else False
- Junaid Mansuri
(LeetCode ID)@hotmail.com | 1-bit-and-2-bit-characters | Solution in Python 3 (three lines) | junaidmansuri | 1 | 354 | 1 bit and 2 bit characters | 717 | 0.46 | Easy | 11,783 |
https://leetcode.com/problems/1-bit-and-2-bit-characters/discuss/2802345/It's-that-easy-oror-Simplest-solution | class Solution:
def isOneBitCharacter(self, bits: List[int]) -> bool:
idx =0
flag = True
while(idx<len(bits)):
if(bits[idx]==0):
idx+=1
flag =True
else:
idx+=2
flag = False
return flag | 1-bit-and-2-bit-characters | It's that easy || Simplest solution | hasan2599 | 0 | 3 | 1 bit and 2 bit characters | 717 | 0.46 | Easy | 11,784 |
https://leetcode.com/problems/1-bit-and-2-bit-characters/discuss/2774562/Python-one-liner-99.57-BUT-I-DON'T-KNOW-WHY! | class Solution:
def isOneBitCharacter(self, bits: List[int]) -> bool:
return '1' not in ''.join([str(bit) for bit in bits[:-1]]).replace('11', '').replace('10', '') | 1-bit-and-2-bit-characters | Python one liner 99.57% BUT I DON'T KNOW WHY! | Kros-ZERO | 0 | 6 | 1 bit and 2 bit characters | 717 | 0.46 | Easy | 11,785 |
https://leetcode.com/problems/1-bit-and-2-bit-characters/discuss/2535185/Python-Clear-iterative-solution | class Solution:
def isOneBitCharacter(self, bits: List[int]) -> bool:
# go through the array
was_one = False
for num in bits[:-1]:
if was_one:
was_one = False
continue
if num:
was_one = True
return not was_one | 1-bit-and-2-bit-characters | [Python] - Clear iterative solution | Lucew | 0 | 39 | 1 bit and 2 bit characters | 717 | 0.46 | Easy | 11,786 |
https://leetcode.com/problems/1-bit-and-2-bit-characters/discuss/1883540/Python-3-oror-4-lines-oror-O(n)O(1) | class Solution:
def isOneBitCharacter(self, bits: List[int]) -> bool:
i, n = 0, len(bits)
while i < n - 1:
i += bits[i] + 1
return i == n - 1 | 1-bit-and-2-bit-characters | Python 3 || 4 lines || O(n)/O(1) | dereky4 | 0 | 81 | 1 bit and 2 bit characters | 717 | 0.46 | Easy | 11,787 |
https://leetcode.com/problems/1-bit-and-2-bit-characters/discuss/1831009/4-Lines-Python-Solution-oror-30-Faster-oror-Memory-less-than-60 | class Solution:
def isOneBitCharacter(self, bits: List[int]) -> bool:
while len(bits)>2:
if bits[0]==0: bits=bits[1:] ; continue
else: bits=bits[2:]
return bits in [[0],[0,0]] | 1-bit-and-2-bit-characters | 4-Lines Python Solution || 30% Faster || Memory less than 60% | Taha-C | 0 | 52 | 1 bit and 2 bit characters | 717 | 0.46 | Easy | 11,788 |
https://leetcode.com/problems/1-bit-and-2-bit-characters/discuss/1831009/4-Lines-Python-Solution-oror-30-Faster-oror-Memory-less-than-60 | class Solution:
def isOneBitCharacter(self, bits: List[int]) -> bool:
return reduce(lambda x, y: not y if x else True, bits[:-1], True) | 1-bit-and-2-bit-characters | 4-Lines Python Solution || 30% Faster || Memory less than 60% | Taha-C | 0 | 52 | 1 bit and 2 bit characters | 717 | 0.46 | Easy | 11,789 |
https://leetcode.com/problems/1-bit-and-2-bit-characters/discuss/1784010/Python3-greedy | class Solution:
def isOneBitCharacter(self, bits: List[int]) -> bool:
i = 0
while i < len(bits)-1:
if bits[i] == 0: i += 1
else: i += 2
return i == len(bits)-1 | 1-bit-and-2-bit-characters | [Python3] greedy | ye15 | 0 | 57 | 1 bit and 2 bit characters | 717 | 0.46 | Easy | 11,790 |
https://leetcode.com/problems/1-bit-and-2-bit-characters/discuss/1271599/python-solution(faster-than-64.8-and-memory-less-than-97.5) | class Solution:
def isOneBitCharacter(self, b: List[int]) -> bool:
n=len(b)
if n==1:
return True
if n==2:
if b[0]==0:
return True
else:
return False
for i in range(n-2):
if b[i]==1:
b[i]=5
b[i+1]=5
b=list(filter(lambda x: x!=5,b))
t=len(b)
if t==1:
return True
elif t==0:
return False
elif t>=2:
if 1 not in b:
return True
else:
return False | 1-bit-and-2-bit-characters | python solution(faster than 64.8% and memory less than 97.5%) | sakshigoel123 | 0 | 124 | 1 bit and 2 bit characters | 717 | 0.46 | Easy | 11,791 |
https://leetcode.com/problems/1-bit-and-2-bit-characters/discuss/520118/easy-python-solution | class Solution:
def isOneBitCharacter(self, bits: List[int]) -> bool:
i = 0
while i < len(bits)-1:
if bits[i] == 1: i+=1
i+=1
return i == len(bits)-1 | 1-bit-and-2-bit-characters | easy python solution | Jahr | 0 | 96 | 1 bit and 2 bit characters | 717 | 0.46 | Easy | 11,792 |
https://leetcode.com/problems/1-bit-and-2-bit-characters/discuss/463038/Get-desired-result-base-on-conditions | class Solution:
def isOneBitCharacter(self, bits: List[int]) -> bool:
n = len(bits)
if n == 1:
return True
if n == 2:
return bits[0] == 0
if bits[n - 2] == 0:
return True
if bits[n - 3] == 0:
return False
idx = n - 4
while idx >= 0 and bits[idx] == 1:
idx -= 1
return (n - 3 - idx + 1) % 2 == 0 | 1-bit-and-2-bit-characters | Get desired result base on conditions | tp99 | 0 | 46 | 1 bit and 2 bit characters | 717 | 0.46 | Easy | 11,793 |
https://leetcode.com/problems/1-bit-and-2-bit-characters/discuss/333086/Python-solution-using-stack-(straight-forward) | class Solution:
def isOneBitCharacter(self, bits: List[int]) -> bool:
stack=[]
for i in bits:
if i==1:
if not stack:stack.append(i)
elif stack[-1]==1:stack.pop()
elif stack[-1]==0:
stack.pop()
stack.append(i)
else:
if not stack:stack.append(i)
elif stack[-1]==1:stack.pop()
if not stack:
return False
return True | 1-bit-and-2-bit-characters | Python solution using stack (straight forward) | ketan35 | 0 | 68 | 1 bit and 2 bit characters | 717 | 0.46 | Easy | 11,794 |
https://leetcode.com/problems/1-bit-and-2-bit-characters/discuss/1234319/Python3-simple-solution-using-while-loop | class Solution:
def isOneBitCharacter(self, bits: List[int]) -> bool:
i = 0
while i in range(len(bits)):
if i == len(bits)-1:
return True
if bits[i] == 0:
i += 1
else:
i += 2
return False | 1-bit-and-2-bit-characters | Python3 simple solution using while loop | EklavyaJoshi | -2 | 75 | 1 bit and 2 bit characters | 717 | 0.46 | Easy | 11,795 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2599501/LeetCode-The-Hard-Way-Explained-Line-By-Line | class Solution:
# DP Approach - Similar to 1143. Longest Common Subsequence
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
n, m = len(nums1), len(nums2)
# dp[i][j] means the length of repeated subarray of nums1[:i] and nums2[:j]
dp = [[0] * (m + 1) for _ in range(n + 1)]
ans = 0
for i in range(1, n + 1):
for j in range(1, m + 1):
# if both character is same
if nums1[i - 1] == nums2[j - 1]:
# then we add 1 to the previous state, which is dp[i - 1][j - 1]
# in other word, we extend the repeated subarray by 1
# e.g. a = [1], b = [1], length of repeated array is 1
# a = [1,2], b = [1,2], length of repeated array is the previous result + 1 = 2
dp[i][j] = dp[i - 1][j - 1] + 1
# record the max ans here
ans = max(ans, dp[i][j])
# else:
# if you are looking for longest common sequence,
# then you put dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); here
# however, this problem is looking for subarray,
# since both character is not equal, which means we need to break it here
# hence, set dp[i][j] to 0
return ans | maximum-length-of-repeated-subarray | π₯ [LeetCode The Hard Way] π₯ Explained Line By Line | wingkwong | 32 | 2,000 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,796 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2599501/LeetCode-The-Hard-Way-Explained-Line-By-Line | class Solution:
# Binary Search Approach
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
N, M = len(nums1), len(nums2)
def ok(k):
# the idea is to use binary search to find the length `k`
# then we check if there is any nums1[i : i + k] == nums2[i : i + k]
s = set(tuple(nums1[i : i + k]) for i in range(N - k + 1))
return any(tuple(nums2[i : i + k]) in s for i in range(M - k + 1))
# init possible boundary
l, r = 0, min(N, M)
while l < r:
# get the middle one
# for even number of elements, take the upper one
m = (l + r + 1) // 2
if ok(m):
# include m
l = m
else:
# exclude m
r = m - 1
return l | maximum-length-of-repeated-subarray | π₯ [LeetCode The Hard Way] π₯ Explained Line By Line | wingkwong | 32 | 2,000 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,797 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2599253/Python3-Runtime%3A-178-ms-faster-than-99.92-or-Memory%3A-13.8-MB-less-than-99.81 | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
strnum2 = ''.join([chr(x) for x in nums2])
strmax = ''
ans = 0
for num in nums1:
strmax += chr(num)
if strmax in strnum2:
ans = max(ans,len(strmax))
else:
strmax = strmax[1:]
return ans | maximum-length-of-repeated-subarray | [Python3] Runtime: 178 ms, faster than 99.92% | Memory: 13.8 MB, less than 99.81% | anubhabishere | 30 | 2,300 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,798 |
https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/1324567/well-explained-oror-With-and-Without-DP-oror-99.66-faster-oror-Easily-Understandable | class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
nums2_str = ''.join([chr(x) for x in nums2])
max_str = ''
res = 0
for num in nums1:
max_str+=chr(num)
if max_str in nums2_str:
res = max(res,len(max_str))
else:
max_str = max_str[1:]
return res | maximum-length-of-repeated-subarray | π well-explained || [ With and Without DP ] || 99.66 % faster || Easily-Understandable π | abhi9Rai | 10 | 994 | maximum length of repeated subarray | 718 | 0.515 | Medium | 11,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.