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/best-time-to-buy-and-sell-stock-ii/discuss/2557423/Python3-or-C%2B%2B-or-Easy | class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
mx = 0
for i in range(len(prices) - 1):
profit = prices[i+1] - prices[i]
if profit > 0:
mx += profit
return mx | best-time-to-buy-and-sell-stock-ii | Python3 | C++ | Easy | joshua_mur | 0 | 6 | best time to buy and sell stock ii | 122 | 0.634 | Medium | 1,300 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/discuss/2474168/python-simple-intuit-solution | class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
pre = prices[0]
for i in range(len(prices)):
profit += max((prices[i] - pre) , 0)
pre = prices[i]
return profit | best-time-to-buy-and-sell-stock-ii | python simple intuit solution | rajitkumarchauhan99 | 0 | 32 | best time to buy and sell stock ii | 122 | 0.634 | Medium | 1,301 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/discuss/2405500/Pythonor-Easy-to-understand-or-Beginner-or-Faster-than-90 | class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit=0
l=0
r=0
while r<len(prices):
if prices[r]>prices[l]:
profit+=prices[r]-prices[l]
l=r
elif prices[r]<prices[l]:
l=r
r+=1
return profit | best-time-to-buy-and-sell-stock-ii | Python| Easy to understand | Beginner | Faster than 90% | user2559cj | 0 | 47 | best time to buy and sell stock ii | 122 | 0.634 | Medium | 1,302 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/discuss/2370372/Python3-O(n)-time-easy-and-simple-solution | class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
for i in range(1,len(prices)):
if prices[i]>prices[i-1]:
profit += prices[i]-prices[i-1]
pass
return profit | best-time-to-buy-and-sell-stock-ii | Python3/ O(n) time / easy and simple solution | abhinav_kumar07 | 0 | 34 | best time to buy and sell stock ii | 122 | 0.634 | Medium | 1,303 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/discuss/2338819/DP-by-Python-easy-to-understand! | class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""sell is the maximum benifit we can get,
buy is if you buy this stock.
So, sell=buy+"this stock" if it>sell, that means we buy last stock and sell now.
buy=sell-"this stock"
Time comlexity: O(n), space complexity: O(1)
"""
buy,sell=-prices[0],0
for i in prices[1:]:
sell=buy+i if buy+i>sell else sell
buy=sell-i
return sell | best-time-to-buy-and-sell-stock-ii | DP by Python, easy to understand! | XRFXRF | 0 | 31 | best time to buy and sell stock ii | 122 | 0.634 | Medium | 1,304 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/discuss/2326954/O(n)timeBEATS-99.97-MEMORYSPEED-0ms-JULY-2022 | class Solution:
def maxProfit(self, prices: List[int]) -> int:
@cache
def trade(day_d):
if day_d == 0:
# Hold on day_#0 = buy stock at the price of day_#0
# Not-hold on day_#0 = doing nothing on day_#0
return -prices[day_d], 0
prev_hold, prev_not_hold = trade(day_d-1)
hold = max(prev_hold, prev_not_hold - prices[day_d] )
not_hold = max(prev_not_hold, prev_hold + prices[day_d] )
return hold, not_hold
# --------------------------------------------------
last_day= len(prices)-1
# Max profit must come from not_hold state (i.e., no stock position) on last day
return trade(last_day)[1] | best-time-to-buy-and-sell-stock-ii | O(n)time/BEATS 99.97% MEMORY/SPEED 0ms JULY 2022 | cucerdariancatalin | 0 | 105 | best time to buy and sell stock ii | 122 | 0.634 | Medium | 1,305 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/2040316/O(n)timeBEATS-99.97-MEMORYSPEED-0ms-MAY-2022 | 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-iii | O(n)time/BEATS 99.97% MEMORY/SPEED 0ms MAY 2022 | cucerdariancatalin | 16 | 821 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,306 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/795456/Python-Simple-Solution-Fully-Explained-(video-%2B-code-%2B-image) | class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices:
return 0
A = -prices[0]
B = float('-inf')
C = float('-inf')
D = float('-inf')
for price in prices:
A = max(A, -price)
B = max(B, A + price)
C = max(C, B - price)
D = max(D, C + price)
return D | best-time-to-buy-and-sell-stock-iii | Python Simple Solution Fully Explained (video + code + image) | spec_he123 | 10 | 1,000 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,307 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/1477485/Well-Explained-oror-98-faster-oror-Clean-and-Concise | class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
profit = [0]*n
global_min = prices[0]
for i in range(1,n):
global_min = min(global_min,prices[i])
profit[i] = max(profit[i-1],prices[i]-global_min)
res = max(profit[-1],0)
global_max = 0
for i in range(n-1,0,-1):
global_max = max(global_max,prices[i])
res = max(res,profit[i-1]+global_max-prices[i])
return res | best-time-to-buy-and-sell-stock-iii | ๐ Well-Explained || 98% faster || Clean & Concise ๐๐ | abhi9Rai | 8 | 527 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,308 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/2480095/Python-O(N*2*3)-All-Easy-soln-Easy-approch | class Solution:
def f(self,ind,buy,cap,n,price,dp):
if ind==n:
return 0
if cap==0:
return 0
if dp[ind][buy][cap]!=-1:
return dp[ind][buy][cap]
if buy:
profit=max(-price[ind]+self.f(ind+1,0,cap,n,price,dp),0+self.f(ind+1,1,cap,n,price,dp))
else:
profit=max(price[ind]+self.f(ind+1,1,cap-1,n,price,dp),0+self.f(ind+1,0,cap,n,price,dp))
dp[ind][buy][cap]=profit
return dp[ind][buy][cap]
def maxProfit(self, prices: List[int]) -> int:
n=len(prices)
dp=[[[-1 for i in range(3)]for j in range(2)]for k in range(n)]
return self.f(0,1,2,n,prices,dp) | best-time-to-buy-and-sell-stock-iii | Python O(N*2*3) All Easy soln Easy approchโ | adarshg04 | 7 | 254 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,309 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/1243694/Python-O(kn)-and-O(n)-time-complexity-DP-solutions | class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
dp = [[[0 for i in range(2)] for i in range(n)] for i in range(3)]
for k in range(1,3):
for i in range(n):
if i == 0 and k == 1:
dp[k][i][1] = -prices[i]
elif i == 0 and k == 2:
continue
elif i == 1 and k == 2:
dp[k][i][0] = dp[k - 1][i][0]
elif i == 2 and k == 2:
dp[k][i][1] = dp[k - 1][i - 1][0]-prices[i]
dp[k][i][0] = dp[k - 1][i][0]
else:
dp[k][i][0] = max(dp[k][i - 1][1] + prices[i], max(dp[k - 1][i][0],dp[k][i - 1][0]))
dp[k][i][1] = max(dp[k][i - 1][1], dp[k - 1][i - 1][0] - prices[i])
return dp[2][n - 1][0] | best-time-to-buy-and-sell-stock-iii | Python O(kn) & O(n) time complexity DP solutions | m0biu5 | 4 | 460 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,310 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/1243694/Python-O(kn)-and-O(n)-time-complexity-DP-solutions | class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
dp = [[0 for i in range(n)] for i in range(3)]
for k in range(1,3):
buy = -999999
for i in range(n):
if i == 0:
buy = -prices[i]
elif k == 2 and i == 1:
buy = max(buy, -prices[i])
dp[k][i] = dp[k - 1][i] if i > 0 else 0
else:
dp[k][i] = max(buy + prices[i], max(dp[k - 1][i], dp[k][i - 1]))
buy = max(buy, dp[k - 1][i - 1] - prices[i])
return dp[2][n - 1] | best-time-to-buy-and-sell-stock-iii | Python O(kn) & O(n) time complexity DP solutions | m0biu5 | 4 | 460 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,311 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/1243694/Python-O(kn)-and-O(n)-time-complexity-DP-solutions | class Solution:
def maxProfit(self, prices: List[int]) -> int:
n, buy1, buy2, sell1, sell2, temp = len(prices), 999999, 999999, 0, 0, 0
for i in range(n):
buy1 = min(buy1, prices[i])
sell1 = max(prices[i] - buy1, sell1)
buy2 = min(buy2, prices[i] - sell1)
sell2 = max(prices[i] - buy2, sell2)
return sell2 | best-time-to-buy-and-sell-stock-iii | Python O(kn) & O(n) time complexity DP solutions | m0biu5 | 4 | 460 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,312 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/702602/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-iii | [Python3] dp | ye15 | 4 | 269 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,313 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/702602/Python3-dp | class Solution:
def maxProfit(self, prices: List[int]) -> int:
pnl = [0]*len(prices)
for _ in range(2):
most = 0
for i in range(1, len(prices)):
most = max(pnl[i], most + prices[i] - prices[i-1])
pnl[i] = max(pnl[i-1], most)
return pnl[-1] | best-time-to-buy-and-sell-stock-iii | [Python3] dp | ye15 | 4 | 269 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,314 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/2320972/O(N)-Solution-With-Explanation-Using-A-Running-Example | class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
"""
The solution to this problem is based on several observations
- We can make a maximum of 2 transactions.
- Since we can make a maximum of 2 transactions, there will always
be 2 windows for it. If we make the first transaction in [0 -> k], the second
transaction can only happen in [k+1 -> n).
Thus our problem statement gets resolved to finding those two windows.
With the above, the solution to this problem can be expressed as follows:
For example, if the prices denoted are:
prices = [3,3,5,0,0,3,1,4]
Then the maximum profit in window 0->k will be:
profit_k = [0,0,2,2,2,3,3,4]
e.g., if k = 1, then the maximum profit can be 2
if k = 3, the maximum profit remains the same as 2
if k = n-1, the maximum profit becomes 4, (4-0 = 4), where 0 is the minimum price
encountered
Now that we know the MAX profit from 0->k, if we iterate backwards, we can
at any point in time, know the profit from k+1 -> n
For example, for k = 7, max profit from k+1 will be 0
for k = 6, max profit from k+1 will be 3 (since we buy at 1 and sell at 4)
Here is how the profit_kn looks like when filled backwards
profit_kn = [4,4,4,4,4,3,3,0]
Now we profit_k and profit_kn as :
[0,0,2,2,2,3,3,4]
[4,4,4,4,4,3,3,0]
Here profit[i] represents MAX profit made in 1 transaction until ith day and profit_kn[i]
represents the MAX profit made in 1 transaction when starting from i and moving till n-1
Thus MAX = MAX(profit_k[i]+profit_kn[i])
"""
if len(prices) == 1:
return 0
min_price_k = float("+inf")
profit_k = []
max_profit_k = 0
for p in prices:
if min_price_k > p:
min_price_k = p
else:
max_profit_k = max(max_profit_k, p - min_price_k)
profit_k.append(max_profit_k)
max_price_kn = float("-inf")
profit_kn = [0]*len(prices)
max_profit_kn = 0
for i in range(len(prices)-1,-1,-1):
p = prices[i]
if p > max_price_kn:
max_price_kn = p
else:
max_profit_kn = max(max_profit_kn, max_price_kn - p)
profit_kn[i] = max_profit_kn
max_profit = 0
for i in range(len(prices)):
max_profit = max(max_profit, profit_k[i] + profit_kn[i])
return max_profit | best-time-to-buy-and-sell-stock-iii | O(N) Solution With Explanation Using A Running Example | suhail03 | 2 | 112 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,315 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/2120983/Python-or-DP-or | class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
dp = [[[0 for i in range(3)] for i in range(2)] for i in range(n+1)]
ind = n-1
while(ind >= 0):
for buy in range(2):
for cap in range(1,3):
if(buy):
profit = max(-prices[ind]+ dp[ind+1][0][cap] , 0 + dp[ind+1][1][cap])
else:
profit = max(prices[ind] + dp[ind+1][1][cap-1], 0 + dp[ind+1][0][cap])
dp[ind][buy][cap] = profit
ind -= 1
return dp[0][1][2] | best-time-to-buy-and-sell-stock-iii | Python | DP | | LittleMonster23 | 2 | 156 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,316 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/2120983/Python-or-DP-or | class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
after = [[0 for i in range(3)] for i in range(2)]
curr = [[0 for i in range(3)] for i in range(2)]
ind = n-1
while(ind >= 0):
for buy in range(2):
for cap in range(1,3):
if(buy):
profit = max(-prices[ind]+ after[0][cap] , 0 + after[1][cap])
else:
profit = max(prices[ind] + after[1][cap-1], 0 + after[0][cap])
curr[buy][cap] = profit
ind -= 1
after = [x for x in curr]
return after[1][2] | best-time-to-buy-and-sell-stock-iii | Python | DP | | LittleMonster23 | 2 | 156 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,317 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/2326951/O(n)timeBEATS-99.97-MEMORYSPEED-0ms-JULY-2022 | 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-iii | O(n)time/BEATS 99.97% MEMORY/SPEED 0ms JULY 2022 | cucerdariancatalin | 1 | 195 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,318 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/1608947/O(n)-and-O(1)-beats-90-98-easy-to-understand-python-code | class Solution:
def maxProfit(self, prices: List[int]) -> int:
if (len(prices) == 1): return 0
profit_11 = profit_12 = -prices[0]
profit_01 = profit_02 = profit_03 = 0
for price in prices[1:]:
profit_11 = max(profit_11, profit_01 - price)
profit_12 = max(profit_12, profit_02 - price)
profit_02 = max(profit_02, profit_11 + price)
profit_03 = max(profit_03, profit_12 + price)
return max(profit_01, profit_02, profit_03) | best-time-to-buy-and-sell-stock-iii | O(n) & O(1), beats 90% 98%, easy to understand python code | jhps73 | 1 | 227 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,319 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/1476696/Python3-or-Recusrion%2BMemoization | class Solution:
def maxProfit(self, prices: List[int]) -> int:
self.dp={}
return self.dfs(0,0,prices,2)
def dfs(self,day,own,prices,k):
if k==0 or day==len(prices):
return 0
if (day,k,own) in self.dp:
return self.dp[(day,k,own)]
if own:
p1=prices[day]+self.dfs(day+1,0,prices,k-1)
p2=self.dfs(day+1,1,prices,k)
else:
p1=-prices[day]+self.dfs(day+1,1,prices,k)
p2=self.dfs(day+1,0,prices,k)
self.dp[(day,k,own)]=max(p1,p2)
return self.dp[(day,k,own)] | best-time-to-buy-and-sell-stock-iii | [Python3] | Recusrion+Memoization | swapnilsingh421 | 1 | 158 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,320 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/1458121/Simple-Python-O(n)-two-pass-solution | class Solution:
def maxProfit(self, prices: List[int]) -> int:
# forward pass to find the maximum profit
# between index 0 and index i
# (same as Best Time to Buy and Sell Stock I)
cur_min, max_profit = float("inf"), 0
max_profit_first = []
for i in range(len(prices)):
cur_min = min(cur_min, prices[i])
max_profit = max(max_profit, prices[i]-cur_min)
max_profit_first.append(max_profit)
# backward pass to find the maximum total
# profit through keeping track of the maximum
# future highest price. future_max-prices[i] is how
# much profit we can make in the second trasaction
# while max_profit_first[i] is how much we can make
# in the first
future_max, ret = -float("inf"), 0
for i in range(len(prices)-1, -1, -1):
future_max = max(future_max, prices[i])
ret = max(ret, max_profit_first[i]+(future_max-prices[i]))
return ret | best-time-to-buy-and-sell-stock-iii | Simple Python O(n) two pass solution | Charlesl0129 | 1 | 254 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,321 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/2788230/Python-solution-generalizing-to-K-transactions | class Solution:
def maxProfit(self, prices: List[int]) -> int:
#You can replace K with any number
K = 2
T = [[0 for _ in range(len(prices))] for _ in range(2*K+2)]
for i in range(3, len(T), 2):
T[i][0] = -prices[0]
for i in range(1,3):
for j in range(1, len(prices)):
T[i*2][j] = max(T[i*2][j-1], T[i*2+1][j-1] + prices[j])
T[i*2+1][j] = max(T[(i-1)*2][j] - prices[j], T[i*2+1][j-1])
return T[-2][-1] | best-time-to-buy-and-sell-stock-iii | Python solution generalizing to K transactions | dominhnhut01 | 0 | 6 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,322 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/2741142/Intuitive-Python-Recursion-%2B-Memoization | class Solution:
def maxProfit(self, prices: List[int]) -> int:
@cache
def max_profit(idx, phase):
'''
Starting from idx and phase, what is the max profit?
Phase = 1 --> starting point
= 2 --> holding
= 3 --> cash, bought once
= 4 --> holding for the second time
= 5 --> cash, done
'''
# Exit conditions
if phase == 5 or idx == len(prices):
return 0
# Buy/sell or skip current idx
best = 0
if phase in (1, 3):
buy = -prices[idx] + max_profit(idx+1, phase+1)
skip = max_profit(idx+1, phase)
return max(buy, skip)
else: # phase in (2, 4)
sell = prices[idx] + max_profit(idx+1, phase+1)
skip = max_profit(idx+1, phase)
return max(sell, skip)
return max_profit(0, 1) | best-time-to-buy-and-sell-stock-iii | Intuitive Python Recursion + Memoization | npa02012 | 0 | 9 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,323 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/2641628/Linear-traversal-no-DP-beat-94-Runtime-and-96-Memory | class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
if n<2: return 0
left_diff = [0 for i in range(n)] #define this to be the max diff for the sub array ending in index i
cur_min = prices[0]
cur_diff = 0
for i in range(1,len(prices)):
if prices[i] > cur_min:
cur_diff = max(cur_diff, prices[i]-cur_min)
else:
cur_min= prices[i]
left_diff[i] = cur_diff
#we now do the same thing in reverse, but now want the largest as we go right to left
right_diff = [0 for i in range(n)]
cur_max = prices[-1]
cur_diff = 0
best = 0
for j in range(n-2,-1,-1):
if prices[j] < cur_max:
cur_diff = max(cur_diff, cur_max-prices[j])
else:
cur_max = prices[j]
right_diff[j] = cur_diff
best = max(best, right_diff[j]+left_diff
[j])
return best | best-time-to-buy-and-sell-stock-iii | Linear traversal, no DP, beat 94% Runtime and 96% Memory | bjht3 | 0 | 7 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,324 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/2618166/92-faster-Python-solution-oror-Dynamic-programming-oror-Prefix-Sum-oror-Greedy | class Solution:
def maxProfit(self, prices: List[int]) -> int:
leftPrefix = self.leftPrefix(prices, 0, 1)
left = len(prices) - 2
right = len(prices) - 1
profit = maxProfit = 0
while left > 0:
profit = max(profit, prices[right] - prices[left])
maxProfit = max(maxProfit, profit + leftPrefix[left], leftPrefix[left])
if prices[left] > prices[right]:
right = left
left -= 1
else:
left -= 1
return max(maxProfit, leftPrefix[-1])
def leftPrefix(self, prices, left,right):
profit = 0
leftPrefix = [0]*(len(prices))
while right < len(prices):
profit = max(profit, prices[right] - prices[left])
leftPrefix[right] = profit
if prices[right] < prices[left]:
left = right
right += 1
else:
right += 1
return leftPrefix | best-time-to-buy-and-sell-stock-iii | 92% faster Python solution || Dynamic programming || Prefix Sum || Greedy | Sefinehtesfa34 | 0 | 63 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,325 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/2558613/Easy-Solution-Dynamic-Programming | class Solution:
def maxProfit(self, prices: List[int]) -> int:
k=2
min_price = [float("inf")] * (k + 1)
max_profit = [0] * (k + 1)
for price in prices:
for i in range(1, k + 1):
min_price[i] = min(min_price[i], price - max_profit[i-1])
max_profit[i] = max(max_profit[i], price - min_price[i])
return max_profit[k] | best-time-to-buy-and-sell-stock-iii | Easy Solution Dynamic Programming | mehtadeepparesh | 0 | 19 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,326 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/2434728/Fast-and-Simple-Python3-or-O(n) | class Solution:
def maxProfit(self, prices: List[int]) -> int:
cur_max, max_after = float('-inf'), []
for price in reversed(prices):
cur_max = max(cur_max, price)
max_after.append(cur_max)
max_after.reverse()
cur_min, max_prof_left, max_so_far = float('inf'), [], 0
for price in prices:
cur_min = min(cur_min, price)
max_so_far = max(max_so_far, price - cur_min)
max_prof_left.append(max_so_far)
max_profit = 0
for i, price in enumerate(prices):
max_profit = max(max_profit, max_prof_left[i] + max_after[i] - price)
return max_profit | best-time-to-buy-and-sell-stock-iii | Fast & Simple Python3 | O(n) | ryangrayson | 0 | 54 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,327 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/2431055/Python-DP-Solution-(Memoization) | class Solution:
def maxProfit(self, prices: List[int]) -> int:
d = {}
def bs(index, buyOrNotBuy, timesRemaining):
if index >= len(prices):
return 0
if timesRemaining == 0:
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", timesRemaining) not in d:
profit = -1 * prices[index] + bs(index+1, "notBuy", timesRemaining)
else:
profit = -1 * prices[index] + d[(index+1, "notBuy", timesRemaining)]
# if buy later, not now at this index
if (index+1, "buy", timesRemaining) not in d:
profit1 = bs(index+1, "buy", timesRemaining)
else:
profit1 = d[(index+1, "buy",timesRemaining)]
d[(index, buyOrNotBuy,timesRemaining)] = max(profit, profit1)
return d[(index, buyOrNotBuy,timesRemaining)]
else:
# sell stock, if we sell 2nd argument is buy
# sell stock at this index
if (index+1, "buy",timesRemaining) not in d:
profit = prices[index] + bs(index+1, "buy", timesRemaining-1)
else:
profit = prices[index] + d[(index+1, "buy",timesRemaining-1)]
# sell stock not at this index now, sell it later
if (index+1, "notBuy",timesRemaining) not in d:
profit1 = bs(index+1, "notBuy",timesRemaining)
else:
profit1 = d[(index+1, "notBuy",timesRemaining)]
d[(index, buyOrNotBuy,timesRemaining)] = max(profit, profit1)
return d[(index, buyOrNotBuy, timesRemaining)]
return bs(0, "buy", 2) | best-time-to-buy-and-sell-stock-iii | Python DP Solution (Memoization) | DietCoke777 | 0 | 52 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,328 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/2425324/Best-time-to-buy-and-sell-3-oror-Python3 | class Solution:
def maxProfit(self, prices: List[int]) -> int:
mat = [0] * len(prices)
min_buy = math.inf
max_sell_profit = -math.inf
# 1st traversal from start to end maintaining the optimal sell at or before that point
for i in range(0, len(prices)):
min_buy = min(min_buy, prices[i])
max_sell_profit = max(max_sell_profit, prices[i] - min_buy)
mat[i] = max_sell_profit
ans = -math.inf
# 2nd traversal from last to first index maintaining the optimal buy at or after that point
max_sell = prices[len(prices)-1]
max_buy_profit = -math.inf
for i in range(len(prices)-1, -1, -1):
max_sell = max(max_sell, prices[i])
max_buy_profit = max(max_buy_profit, max_sell - prices[i])
ans = max(ans, mat[i] + max_buy_profit)
return ans | best-time-to-buy-and-sell-stock-iii | Best time to buy and sell 3 || Python3 | vanshika_2507 | 0 | 43 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,329 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/2060382/Python-Solution | class Solution:
def maxProfit(self, l: List[int]) -> int:
n = len(l)
l1 = [0 for i in range(n)]
l2 = [0 for i in range(n)]
mi = l[0]
ma = l[-1]
for i in range(n):
if i!=0:
l1[i] = max(l1[i-1],l[i]-mi)
mi = min(mi,l[i])
l2[n-i-1] = max(l2[n-i],ma-l[n-i-1])
ma = max(ma,l[n-i-1])
ans = l2[0]
for i in range(1,n):
ans = max(ans,l1[i-1]+l2[i])
return ans | best-time-to-buy-and-sell-stock-iii | Python Solution | Shivamk09 | 0 | 103 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,330 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/1789138/Python-easy-to-read-and-understand-or-Memoization | class Solution:
def solve(self, prices, index, option, trans):
if index == len(prices) or trans == 0:
return 0
res = 0
if option == 0:
buy = self.solve(prices, index + 1, 1, trans) - prices[index]
cool = self.solve(prices, index + 1, 0, trans)
res = max(buy, cool)
if option == 1:
sell = self.solve(prices, index + 1, 0, trans - 1) + prices[index]
cool = self.solve(prices, index + 1, 1, trans)
res = max(sell, cool)
return res
def maxProfit(self, prices: List[int]) -> int:
return self.solve(prices, 0, 0, 2) | best-time-to-buy-and-sell-stock-iii | Python easy to read and understand | Memoization | sanial2001 | 0 | 268 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,331 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/1789138/Python-easy-to-read-and-understand-or-Memoization | class Solution_memo:
def solve(self, prices, index, option, trans):
if index == len(prices) or trans == 0:
return 0
if (index, option, trans) in self.dp:
return self.dp[(index, option, trans)]
if option == 0:
buy = self.solve(prices, index + 1, 1, trans) - prices[index]
cool = self.solve(prices, index + 1, 0, trans)
self.dp[(index, option, trans)] = max(buy, cool)
if option == 1:
sell = self.solve(prices, index + 1, 0, trans - 1) + prices[index]
cool = self.solve(prices, index + 1, 1, trans)
self.dp[(index, option, trans)] = max(sell, cool)
return self.dp[(index, option, trans)]
def maxProfit(self, prices: List[int]) -> int:
self.dp = {}
return self.solve(prices, 0, 0, 2) | best-time-to-buy-and-sell-stock-iii | Python easy to read and understand | Memoization | sanial2001 | 0 | 268 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,332 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/1523578/Python-State-machine-easy-to-understand | class Solution:
def maxProfit(self, prices: List[int]) -> int:
oneBuy = -math.inf
oneBuyOneSell = 0
twoBuy = -math.inf
twoBuyTwoSell = 0
for price in prices:
oneBuy = max(oneBuy, -price)
oneBuyOneSell = max(oneBuyOneSell, oneBuy+price)
twoBuy = max(twoBuy, oneBuyOneSell-price)
twoBuyTwoSell = max(twoBuyTwoSell, twoBuy+price)
return twoBuyTwoSell | best-time-to-buy-and-sell-stock-iii | Python - State machine - easy to understand | zoro_55 | 0 | 80 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,333 |
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/1523195/Python3-Easy-DFS-%2B-Memoization | class Solution:
def maxProfit(self, prices: List[int]) -> int:
@cache
def dfs(i, hasBought, transactions):
if (i >= len(prices) or transactions >= 2):
return 0
maxProfit = 0
if (hasBought):
maxProfit = prices[i] + dfs(i + 1, False, transactions + 1)
else:
maxProfit = -prices[i] + dfs(i + 1, True, transactions)
return max(maxProfit, dfs(i + 1, hasBought, transactions))
return dfs(0, False, 0) | best-time-to-buy-and-sell-stock-iii | Python3 - Easy DFS + Memoization โ
| Bruception | 0 | 185 | best time to buy and sell stock iii | 123 | 0.449 | Hard | 1,334 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/2040330/O(n)timeBEATS-99.97-MEMORYSPEED-0ms-MAY-2022 | class Solution:
def __init__(self):
self.maxSum = float('-inf')
def maxPathSum(self, root: TreeNode) -> int:
def traverse(root):
if root:
left = traverse(root.left)
right = traverse(root.right)
self.maxSum = max(self.maxSum,root.val, root.val + left, root.val + right, root.val + left + right)
return max(root.val,root.val + left,root.val + right)
else:
return 0
traverse(root)
return self.maxSum | binary-tree-maximum-path-sum | O(n)time/BEATS 99.97% MEMORY/SPEED 0ms MAY 2022 | cucerdariancatalin | 17 | 1,100 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,335 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/577860/Python-beats-89.49-basic-recursion-structure-w-algorithm-explanation | class Solution:
def __init__(self):
self.maxSum = float('-inf')
def maxPathSum(self, root: TreeNode) -> int:
def traverse(root):
if root:
left = traverse(root.left)
right = traverse(root.right)
self.maxSum = max(self.maxSum,root.val, root.val + left, root.val + right, root.val + left + right)
return max(root.val,root.val + left,root.val + right)
else:
return 0
traverse(root)
return self.maxSum | binary-tree-maximum-path-sum | Python beats 89.49%, basic recursion structure w/ algorithm explanation | alexlee1995 | 6 | 175 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,336 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/982680/Simple-Python-Recursive-Solution-easy-to-understand | class Solution:
def maxPathSum(self, root: TreeNode) -> int:
def helper(node):
if not node:
return (float('-inf'),float('-inf'))
l_TBC,l_Complete = helper(node.left)
r_TBC,r_Complete = helper(node.right)
rt_TBC = max(node.val,node.val+l_TBC,node.val+r_TBC)
rt_Complete = max(rt_TBC,node.val+l_TBC+r_TBC,l_Complete,r_Complete)
return (rt_TBC,rt_Complete)
return helper(root)[1] | binary-tree-maximum-path-sum | Simple Python Recursive Solution, easy to understand | KevinZzz666 | 3 | 331 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,337 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/2098751/Python3-Recursive-Solution-with-Comments-Easy-To-Understand | class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
if not root: return
self.res = root.val
def solve(root):
# Base case
if not root: return 0
# l and r store maximum path sum going through left and right child of root respectively
l = solve(root.left)
r = solve(root.right)
# Max path for parent call of root. This path must include at most one child of root
temp = max(root.val + max(l, r), root.val)
# ans represents the sum when the node under consideration is the root of the maxSum path and no ancestor of root are there in max sum path
ans = max(temp, root.val + l + r)
self.res = max(self.res, ans) # max across the whole tree
return temp # for considering other subtrees also
solve(root)
return self.res
# Time Complexity: O(n) where n is number of nodes in Binary Tree.
# Space Complexity: O(1) | binary-tree-maximum-path-sum | [Python3] Recursive Solution with Comments Easy To Understand | samirpaul1 | 2 | 129 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,338 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/1383476/Concise-recursion-97-speed | class Solution:
def maxPathSum(self, root: TreeNode) -> int:
max_path = -inf
def traverse(node: TreeNode):
nonlocal max_path
left = traverse(node.left) if node.left else 0
right = traverse(node.right) if node.right else 0
max_path = max(max_path, node.val, node.val + left,
node.val + right, node.val + left + right)
return node.val + max(left, right, 0)
if root:
traverse(root)
return max_path | binary-tree-maximum-path-sum | Concise recursion, 97% speed | EvgenySH | 2 | 241 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,339 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/2748344/O(N)-python-diagramatically-explained-solution | class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
self.maxsum = -inf
#get the continuous path sum with "node" as the root/middle of the path
def pathsum(node):
if not node:
return 0
#no point in adding negetive path
left = max(pathsum(node.left),0)
right = max(pathsum(node.right),0)
#see if the path with "node" as root is maximum
self.maxsum = max(self.maxsum,node.val+left+right)
#only one of the left or right subtree will allow continous path
#when attached to the upper subtree
return node.val+max(left,right)
pathsum(root)
return self.maxsum | binary-tree-maximum-path-sum | O(N) python diagramatically explained solution | user9611y | 1 | 81 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,340 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/1757401/Python-or-DFS | class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
maxy=-inf
def dfs(node):
nonlocal maxy
if not node:
return 0
l=dfs(node.left)
r=dfs(node.right)
maxy=max(l+node.val,r+node.val,l+r+node.val,node.val,maxy)
return max(l+node.val,r+node.val,node.val)
dfs(root)
return maxy | binary-tree-maximum-path-sum | Python | DFS | heckt27 | 1 | 154 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,341 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/1636863/Python-Recursion-beats-90-runtime-92-memory | class Solution:
# time: O(n)
# space: O(H) - O(logn) if balanced tree else O(n)
def maxPathSum(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
self.max_sum = -float('inf')
self.search_path(root)
return self.max_sum
def search_path(self, node):
if not node:
return 0
# no left and no right, itself as a subtree's root
if not node.left and not node.right:
self.max_sum = max(self.max_sum, node.val)
return node.val
# if connect with left and right
left_sum = self.search_path(node.left)
right_sum = self.search_path(node.right)
# use current node as root, no need to return
full_path = max(left_sum + right_sum + node.val, node.val)
self.max_sum = max(full_path, self.max_sum)
# use parent node as root, this return as a choice of left/right
max_sum_connect = max(left_sum+node.val, right_sum+node.val, node.val)
self.max_sum = max(max_sum_connect, self.max_sum)
return max_sum_connect | binary-tree-maximum-path-sum | [Python] Recursion beats 90% runtime 92% memory | sh3956 | 1 | 174 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,342 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/1583626/python-simple-dfs-with-explanation-oror-include-and-exclude-parent-oror-beats-99 | class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
def dfs(node):
if not node.left and not node.right:
return node.val, float('-inf')
left_i = left_e = right_i = right_e = float('-inf')
if node.left:
left_i, left_e = dfs(node.left)
if node.right:
right_i, right_e = dfs(node.right)
sum_i = max(node.val, left_i+node.val, right_i+node.val)
sum_e = max(left_i, left_e, right_i, right_e, left_i+right_i+node.val)
return (sum_i, sum_e)
return max(dfs(root)) | binary-tree-maximum-path-sum | [python] simple dfs with explanation || include and exclude parent || beats 99% | kevintancs | 1 | 225 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,343 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/1409592/Easy-to-Understand-Python-Solution-w-Comments | class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
res = float('-inf')
def recur(root):
nonlocal res
if root is None:
return 0
#the maximum path-sum from the left and right subtree
left_max, right_max = recur(root.left), recur(root.right)
#we don't want previous recursive calls to use paths that go from left-root-right
#because it wouldn't be a one-way path
max_nocross_path = max(root.val, root.val + left_max, root.val + right_max)
#here we take account for the left-root-right path
#this is the only "cross path" that will work
cross_path = root.val + left_max + right_max
#if the cross path is the best, res will be updated. Otherwise, the nocross path
#can be the best
res = max(res, max_nocross_path, cross_path)
return max_nocross_path
recur(root)
return res | binary-tree-maximum-path-sum | Easy to Understand Python Solution w/ Comments | mguthrie45 | 1 | 169 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,344 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/533568/Self-explanatory-python-code | class Solution:
def maxPathSum(self, root: TreeNode) -> int:
totalsum = -math.inf
def dfs(node):
if not node:
return 0
lsum = dfs(node.left)
rsum = dfs(node.right)
diam_sum = max(lsum + rsum + node.val, node.val, lsum+node.val, rsum+node.val)
nonlocal totalsum
totalsum = max(totalsum, diam_sum)
return max(lsum + node.val, rsum+node.val, node.val)
dfs(root)
return totalsum | binary-tree-maximum-path-sum | Self explanatory python code | purushottam3 | 1 | 207 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,345 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/2808450/Simple-Python3-DFS-or-Beats-98 | class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
max_sum = float('-inf')
def dfs(root):
if not root:
return float('-inf')
left_max = dfs(root.left)
right_max = dfs(root.right)
curr_val = root.val
curr_res = max(curr_val, left_max + curr_val, right_max + curr_val)
curr_max = max(curr_res, left_max + right_max + curr_val)
nonlocal max_sum
max_sum = max(max_sum, curr_max)
return curr_res
dfs(root)
return max_sum | binary-tree-maximum-path-sum | Simple Python3 DFS | Beats 98% | burnsdy | 0 | 9 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,346 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/2657347/Python-DFS-with-explanations. | class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
self.res = float('-inf') # save largest sum
def dfs(root): # return max path sums with (root.val + left or right)
if not root: return float('-inf') # boarder condition
l = dfs(root.left)
r = dfs(root.right)
# 4 conditions:
# 1. root itself;
# 2. root with dfs(left);
# 3. root with dfs(right);
# 4. left or right itself.
self.res = max(self.res, root.val, l, r, root.val + max(l, 0) + max(0, r))
return max(root.val, root.val + max(l, r))
dfs(root)
return self.res | binary-tree-maximum-path-sum | Python DFS with explanations. | xiangyupeng1994 | 0 | 7 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,347 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/2521484/Python-3-Recursive-Approach-Explained | class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
max_sum = root.val
def recursion(node):
nonlocal max_sum
if not node:
return 0
left = recursion(node.left)
right = recursion(node.right)
max_non_root = max(
left + node.val,
right + node.val,
node.val)
max_sum = max(
max_non_root,
left + right + node.val,
max_sum)
return max_non_root
recursion(root)
return max_sum | binary-tree-maximum-path-sum | Python 3 Recursive Approach Explained | sebikawa | 0 | 57 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,348 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/2489925/Python-DFS-with-full-working-explanation | class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int: # Time: O(n) and Space: O(h)
max_path = float('-inf')
def get_max_gain(node):
nonlocal max_path
if node is None:
return 0
gain_on_left = max(get_max_gain(node.left), 0)
gain_on_right = max(get_max_gain(node.right), 0)
current_max_path = node.val + gain_on_left + gain_on_right
max_path = max(max_path, current_max_path)
return node.val + max(gain_on_left, gain_on_right)
get_max_gain(root)
return max_path
# Input:
# 1
# / \
# 2 3
# /\ /\
# 4 5 6 -7 | binary-tree-maximum-path-sum | Python DFS with full working explanation | DanishKhanbx | 0 | 54 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,349 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/2326947/O(n)timeBEATS-99.97-MEMORYSPEED-0ms-JULY-2022 | class Solution:
def __init__(self):
self.maxSum = float('-inf')
def maxPathSum(self, root: TreeNode) -> int:
def traverse(root):
if root:
left = traverse(root.left)
right = traverse(root.right)
self.maxSum = max(self.maxSum,root.val, root.val + left, root.val + right, root.val + left + right)
return max(root.val,root.val + left,root.val + right)
else:
return 0
traverse(root)
return self.maxSum | binary-tree-maximum-path-sum | O(n)time/BEATS 99.97% MEMORY/SPEED 0ms JULY 2022 | cucerdariancatalin | 0 | 120 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,350 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/2326940/O(n)timeBEATS-99.97-MEMORYSPEED-0ms-JULY-2022 | class Solution:
def __init__(self):
self.maxSum = float('-inf')
def maxPathSum(self, root: TreeNode) -> int:
def traverse(root):
if root:
left = traverse(root.left)
right = traverse(root.right)
self.maxSum = max(self.maxSum,root.val, root.val + left, root.val + right, root.val + left + right)
return max(root.val,root.val + left,root.val + right)
else:
return 0
traverse(root)
return self.maxSum | binary-tree-maximum-path-sum | O(n)time/BEATS 99.97% MEMORY/SPEED 0ms JULY 2022 | cucerdariancatalin | 0 | 56 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,351 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/2264280/Python-Easy-Solution | class Solution(object):
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
max_sum = [root.val]
def dfs(node):
if not node:
return 0
left = dfs(node.left)
right = dfs(node.right)
left = max(left,0)
right = max(right,0)
max_sum[0] = max(max_sum[0],(right+left+node.val))
return max(left,right)+node.val
dfs(root)
return max_sum[0] | binary-tree-maximum-path-sum | Python Easy Solution | Abhi_009 | 0 | 62 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,352 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/2016178/Python-Easy-to-Understand-Solution | class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
self.ans = -float('inf')
def dfs(root):
if root:
l = dfs(root.left)
r = dfs(root.right)
ans = root.val
ans = max(ans, l + ans)
ans = max(ans, r + ans)
self.ans = max(self.ans, ans)
return max(root.val, root.val + max(l, r))
else:
return 0
dfs(root)
return self.ans | binary-tree-maximum-path-sum | Python Easy to Understand Solution | user6397p | 0 | 65 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,353 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/1987089/Python-or-Easy-to-understand-or-DFS | class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
return self.maxPathSumOfTree(root)[0]
# return a 2-elements-tuple: (maxPathSum of tree, pathSum includes the root node)
# notice the "maxPathSum of tree" may or may not include the root node's value
# notice: the "pathSum includes the root node", which includes the root node's value and "left subtree's value"/"right subtree's value"(that is, we can't take both left subtree's value and right subtree's value, because it is an invalid path when used by parent node), is used to calculate the potential maxPathSum for parent node
def maxPathSumOfTree(self, root):
if root is None:
return (None, None)
leftMax, leftRootMax = (None, None)
if root.left is not None:
leftMax, leftRootMax = self.maxPathSumOfTree(root.left)
rightMax, rightRootMax = (None, None)
if root.right is not None:
rightMax, rightRootMax = self.maxPathSumOfTree(root.right)
if leftMax is not None and rightMax is not None:
rootMaxWithTwoBranch = root.val + (leftRootMax if leftRootMax > 0 else 0) + (rightRootMax if rightRootMax > 0 else 0)
# use left subtree's value or right subtree's value or none of both
rootMax = max(root.val + (leftRootMax if leftRootMax > 0 else 0), root.val + (rightRootMax if rightRootMax > 0 else 0))
return (max(rootMaxWithTwoBranch, leftMax, rightMax), rootMax)
elif leftMax is not None:
rootMax = root.val + (leftRootMax if leftRootMax > 0 else 0)
return (max(rootMax, leftMax), rootMax)
elif rightMax is not None:
rootMax = root.val + (rightRootMax if rightRootMax > 0 else 0)
return (max(rootMax, rightMax), rootMax)
else:
return (root.val, root.val) | binary-tree-maximum-path-sum | Python | Easy to understand | DFS | AdairCLO | 0 | 37 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,354 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/1836722/Python-Easy-Recursive-Solution-with-explanation-O(n)-complexities | class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
res = [root.val] # using list as global variable
def dfs(root):
if not root : return 0 # if not root then go back
left = dfs(root.left) # as its dfs . so go deeper baby
left = max(left,0) # wait a minute. we have to check if the tree has any negative elemnts or not, if the sum become -ve then any single positive element can be the max sum path , thats why comparing wiht zeros
right = dfs(root.right) # same
right = max(right,0) # same
res[0] = max(res[0] , root.val + right + left) # now the tricky part : counting the brach sum .. then comparing if its the max or not
return root.val + max(left, right) # but returnig only the root split max sum .. hehe triggered ? . its a recursive approach bro .. thats why
dfs(root)
return res[0] # retunring val | binary-tree-maximum-path-sum | [Python] Easy Recursive Solution , with explanation ; O(n) complexities | Into_You | 0 | 74 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,355 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/1740397/Python-DFS | class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
def dfs(node):
if not node:
return 0
left = dfs(node.left)
right = dfs(node.right)
self.result = max(self.result, max(0, left) + node.val + max(0, right))
return node.val + max(0, left, right)
self.result = -math.inf
dfs(root)
return self.result | binary-tree-maximum-path-sum | Python, DFS | blue_sky5 | 0 | 83 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,356 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/1632388/Python3-Recursion-similar-way-to-finding-the-HEIGHT-for-each-node | class Solution:
def __init__(self):
self.maxSum = float(-inf)
def maxPathSum(self, root: Optional[TreeNode]) -> int:
self.recur_path(root)
return self.maxSum
def recur_path(self, current):
if current is None:
return 0
left = max(0,self.recur_path(current.left))
right = max(0,self.recur_path(current.right))
self.maxSum = max(self.maxSum, left+right+current.val)
return max(left, right)+current.val | binary-tree-maximum-path-sum | [Python3] Recursion, similar way to finding the HEIGHT for each node | mch0717 | 0 | 23 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,357 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/1597035/Python3-recursion | class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
self.sum = float('-inf')
self.helper(root)
return self.sum
def helper(self, root):
if not root:
return 0
left, right = self.helper(root.left), self.helper(root.right)
self.sum = max(self.sum, root.val + left + right)
return max(root.val + max(left, right), 0) | binary-tree-maximum-path-sum | Python3 recursion | Mandyzmr | 0 | 77 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,358 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/1579889/Python3-Solution-or-99.89-faster | class Solution:
def maxPathSum(self, root) -> int:
self.ans = float('-inf')
def PathSum(node):
if not node: return 0
left,right = PathSum(node.left),PathSum(node.right)
self.ans = max(self.ans, node.val+left+right)
return max(0, node.val+left, node.val+right)
PathSum(root)
return self.ans | binary-tree-maximum-path-sum | Python3 Solution | 99.89% faster | satyam2001 | 0 | 186 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,359 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/1513230/Python-verbose-with-comments | class TreeInfo:
def __init__(self, max_as_branch, max_as_branch_or_triangle):
self.max_as_branch = max_as_branch
# max continuous path as branch/tree
self.max_as_branch_or_triangle = max_as_branch_or_triangle
class Solution:
def maxPathSum(self, root):
if not root:
return 0
return self.max_path(root).max_as_branch_or_triangle
def max_path(self, root):
if not root:
# handle negatives with float('-inf')
# return TreeInfo(float('-inf'), float('-inf')) # <- also works.
return TreeInfo(0, float('-inf'))
left = self.max_path(root.left)
right = self.max_path(root.right)
# longest continuous branch/straight line.
curr_max_as_branch = max(
root.val,
root.val + left.max_as_branch,
root.val + right.max_as_branch
)
# longest branch/triangle we have seen so far note: curr_max_as_branch is automatically included
curr_max_as_branch_or_triangle = max(
curr_max_as_branch,
root.val + left.max_as_branch + right.max_as_branch, # curr_max_as_triangle
left.max_as_branch_or_triangle,
right.max_as_branch_or_triangle
)
return TreeInfo(curr_max_as_branch, curr_max_as_branch_or_triangle) | binary-tree-maximum-path-sum | Python verbose with comments | paulonteri | 0 | 125 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,360 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/1478762/python-3-easy-to-understand-recursion-dfs-O(n)-beats-98 | class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
ans = -1000
def dfs(curr):
nonlocal ans
if curr is None:
return 0
left = dfs(curr.left)
right = dfs(curr.right)
ans = max(ans, left + right + curr.val)
return max(0, max(0, left, right) + curr.val)
dfs(root)
return ans | binary-tree-maximum-path-sum | python 3 easy to understand recursion dfs O(n) beats 98% | ashish_chiks | 0 | 83 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,361 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/1445709/124.-Binary-Tree-Maximum-Path-Sum-or-Python-Solution | class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
self._maxPathSum = -pow(2, 31) - 1
self.findMaxPathSum(root)
return self._maxPathSum
def findMaxPathSum(self, node):
if node is None:
return 0
leftTreeSum = self.findMaxPathSum(node.left)
rightTreeSum = self.findMaxPathSum(node.right)
treeSum = max(max(leftTreeSum, rightTreeSum) + node.val, node.val)
subtreeSum = leftTreeSum + rightTreeSum + node.val
pathSum = max(treeSum, subtreeSum)
self._maxPathSum = max(self._maxPathSum, pathSum)
return treeSum | binary-tree-maximum-path-sum | 124. Binary Tree Maximum Path Sum | Python Solution | rohanpednekar_ | 0 | 236 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,362 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/1290757/Python-DP-recursion-with-three-cases | class Solution:
def maxPathSum(self, root: TreeNode) -> int:
single = {} # maxsum using the root and at most one child
double = {} # maxsum using the root and at most two child
no = {} # maxsum not using the root at all (i.e. using the substructures)
def process(root):
if not root:
return
if root in single:
return single[root]
ls = rs = ld = rd = ln = rn = -float("inf")
if root.left:
ls, ld, ln = process(root.left)
if root.right:
rs, rd, rn = process(root.right)
# The three DP recursions
single[root] = root.val + max(0, ls, rs)
double[root] = max(single[root], root.val + ls + rs)
no[root] = max(rd, ld, ln, rn)
return single[root], double[root], no[root]
process(root)
return max(single[root], double[root], no[root]) | binary-tree-maximum-path-sum | Python DP recursion with three cases | wanghua_wharton | 0 | 122 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,363 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/1245720/Python-or-Javascript-O(n)-solution-using-DFS | class Solution:
def __init__(self, ans = -999999):
self.ans = ans
def MaxPathSum(self, root: TreeNode) -> int:
if root == None:
return 0
left_sum, right_sum = self.MaxPathSum(root.left), self.MaxPathSum(root.right)
var1, var2 = (left_sum if left_sum >= 0 else 0) + (right_sum if right_sum >= 0 else 0), max((left_sum if left_sum >= 0 else 0),(right_sum if right_sum >= 0 else 0))
self.ans = max(self.ans, root.val + var1)
return root.val + var2
def maxPathSum(self, root: TreeNode) -> int:
self.MaxPathSum(root)
return self.ans | binary-tree-maximum-path-sum | Python | Javascript O(n) solution using DFS | m0biu5 | 0 | 70 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,364 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/882668/python3-beats-99.64 | class Solution:
gmax = 0
def maxPathSum(self, root: TreeNode) -> int:
self.gmax = root.val
self.mp(root)
return self.gmax
def mp(self,node):
if not node:
return 0
left = self.mp(node.left) + node.val
right = self.mp(node.right) + node.val
self.gmax = max(left + right - node.val, self.gmax, left, right)
return max(left, right,0,node.val) | binary-tree-maximum-path-sum | python3 beats 99.64% | amrmahmoud96 | 0 | 331 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,365 |
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/367906/Python-Recursive-Not-sure-why-it's-incorrect | class Solution:
def maxPathSum(self, root: TreeNode) -> int:
return self.maxPathSumHelper(root)[2]
def maxPathSumHelper(self, root: TreeNode):
"""
(alo, connected, sum)
"""
if root == None:
return (False, False, 0)
(l_alo, l_connected, l_subtree) = self.maxPathSumHelper(root.left)
(r_alo, r_connected, r_subtree) = self.maxPathSumHelper(root.right)
max_sum = max( \
(root.val + l_subtree + r_subtree) if r_connected and l_connected else root.val, \
(root.val + l_subtree) if l_connected else root.val, \
(root.val + r_subtree) if r_connected else root.val, \
root.val
)
if (l_alo and l_subtree > max_sum) or (r_alo and r_subtree > max_sum):
if l_alo and not r_alo:
return (True, False, l_subtree)
elif not l_alo and r_alo:
return (True, False, r_subtree)
else:
return (True, False, max(l_subtree, r_subtree))
else: | binary-tree-maximum-path-sum | Python Recursive - Not sure why it's incorrect | Olshansky | 0 | 105 | binary tree maximum path sum | 124 | 0.385 | Hard | 1,366 |
https://leetcode.com/problems/valid-palindrome/discuss/350929/Solution-in-Python-3-(beats-~100)-(two-lines)-(-O(1)-solution-as-well-) | class Solution:
def isPalindrome(self, s: str) -> bool:
s = [i for i in s.lower() if i.isalnum()]
return s == s[::-1] | valid-palindrome | Solution in Python 3 (beats ~100%) (two lines) ( O(1) solution as well ) | junaidmansuri | 50 | 8,600 | valid palindrome | 125 | 0.437 | Easy | 1,367 |
https://leetcode.com/problems/valid-palindrome/discuss/350929/Solution-in-Python-3-(beats-~100)-(two-lines)-(-O(1)-solution-as-well-) | class Solution:
def isPalindrome(self, s: str) -> bool:
i, j = 0, len(s) - 1
while i < j:
a, b = s[i].lower(), s[j].lower()
if a.isalnum() and b.isalnum():
if a != b: return False
else:
i, j = i + 1, j - 1
continue
i, j = i + (not a.isalnum()), j - (not b.isalnum())
return True
- Junaid Mansuri
(LeetCode ID)@hotmail.com | valid-palindrome | Solution in Python 3 (beats ~100%) (two lines) ( O(1) solution as well ) | junaidmansuri | 50 | 8,600 | valid palindrome | 125 | 0.437 | Easy | 1,368 |
https://leetcode.com/problems/valid-palindrome/discuss/1151720/Python3-O(n)-time-O(1)-space.-Well-explained | class Solution:
def isPalindrome(self, s: str) -> bool:
# i starts at beginning of s and j starts at the end
i, j = 0, len(s) - 1
# While i is still before j
while i < j:
# If i is not an alpha-numeric character then advance i
if not s[i].isalnum():
i += 1
# If j is not an alpha-numeric character then advance i
elif not s[j].isalnum():
j -= 1
# Both i and j are alpha-numeric characters at this point so if they do not match return the fact that input was non-palendromic
elif s[i].lower() != s[j].lower():
return False
# Otherwise characters matched and we should look at the next pair of characters
else:
i, j = i + 1, j - 1
# The entire stirng was verified and we return the fact that the input string was palendromic
return True | valid-palindrome | Python3 O(n) time, O(1) space. Well-explained | ryancodrai | 16 | 1,200 | valid palindrome | 125 | 0.437 | Easy | 1,369 |
https://leetcode.com/problems/valid-palindrome/discuss/2438656/Very-Easy-oror-100-oror-Fully-Explained-(Java-C%2B%2B-Python-JS-Python3) | class Solution(object):
def isPalindrome(self, s):
# Initialize two pointer variables, left and right and point them with the two ends of the input string...
left, right = 0, len(s) - 1
# Traverse all elements through the loop...
while left < right:
# Move the left pointer to right so it points to a alphanumeric character...
while left < right and not s[left].isalnum():
left += 1
# Similarly move right pointer to left so it also points to a alphanumeric character...
while left < right and not s[right].isalnum():
right -= 1
# Check if both the characters are same...
# If it is not equal then the string is not a valid palindrome, hence return false...
if s[left].lower() != s[right].lower():
return False
# If same, then continue to next iteration and move both pointers to point to next alphanumeric character till left < right...
left, right = left + 1, right - 1
# After loop finishes, the string is said to be palindrome, hence return true...
return True | valid-palindrome | Very Easy || 100% || Fully Explained (Java, C++, Python, JS, Python3) | PratikSen07 | 13 | 2,300 | valid palindrome | 125 | 0.437 | Easy | 1,370 |
https://leetcode.com/problems/valid-palindrome/discuss/2438656/Very-Easy-oror-100-oror-Fully-Explained-(Java-C%2B%2B-Python-JS-Python3) | class Solution:
def isPalindrome(self, s: str) -> bool:
# Initialize two pointer variables, left and right and point them with the two ends of the input string...
left, right = 0, len(s) - 1
# Traverse all elements through the loop...
while left < right:
# Move the left pointer to right so it points to a alphanumeric character...
while left < right and not s[left].isalnum():
left += 1
# Similarly move right pointer to left so it also points to a alphanumeric character...
while left < right and not s[right].isalnum():
right -= 1
# Check if both the characters are same...
# If it is not equal then the string is not a valid palindrome, hence return false...
if s[left].lower() != s[right].lower():
return False
# If same, then continue to next iteration and move both pointers to point to next alphanumeric character till left < right...
left, right = left + 1, right - 1
# After loop finishes, the string is said to be palindrome, hence return true...
return True | valid-palindrome | Very Easy || 100% || Fully Explained (Java, C++, Python, JS, Python3) | PratikSen07 | 13 | 2,300 | valid palindrome | 125 | 0.437 | Easy | 1,371 |
https://leetcode.com/problems/valid-palindrome/discuss/2661691/PYTHON-3-Simple-or-isnumeric()-or-isalpha()-or-Easy-to-Understand | class Solution:
def isPalindrome(self, s: str) -> bool:
a = ""
for x in [*s]:
if x.isalpha(): a += x.lower()
if x.isnumeric(): a += x
return a == a[::-1] | valid-palindrome | [PYTHON 3] Simple | isnumeric() | isalpha() | Easy to Understand | omkarxpatel | 7 | 1,900 | valid palindrome | 125 | 0.437 | Easy | 1,372 |
https://leetcode.com/problems/valid-palindrome/discuss/2097709/PYTHON-oror-94-TIME-oror-86-MEMORY-oror-EASY | class Solution:
def isPalindrome(self, s: str) -> bool:
i,j=0,len(s)-1
s=s.lower()
a={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}
while (i<=j):
while i<=j and s[i] not in a:
i+=1
while j>=i and s[j] not in a:
j-=1
if i<=j and s[i]!=s[j]:
return False
i+=1
j-=1
return True | valid-palindrome | โ๏ธPYTHON || โ๏ธ94% TIME || 86% MEMORY || EASY | karan_8082 | 6 | 541 | valid palindrome | 125 | 0.437 | Easy | 1,373 |
https://leetcode.com/problems/valid-palindrome/discuss/2089935/Valid-Palindrome-in-Python-solution-92-faster | class Solution:
def isPalindrome(self, s: str) -> bool:
k = ''
for i in s:
if i.isalpha() or i.isdigit():
k += i.lower()
return k == k[::-1] | valid-palindrome | Valid Palindrome in Python solution 92 faster | Murod_Turaev | 6 | 403 | valid palindrome | 125 | 0.437 | Easy | 1,374 |
https://leetcode.com/problems/valid-palindrome/discuss/1447745/2-LINE-CODE-or-PYTHON-or-FASTER-THAN-95.88or-PLEASE-UPVOTE | class Solution:
def isPalindrome(self, s: str) -> bool:
s = ''.join([char.casefold() for char in s if char.isalnum()])
return s == s[::-1] | valid-palindrome | 2 LINE CODE | PYTHON | FASTER THAN 95.88%| PLEASE UPVOTE ๐ | nisargndoshi | 6 | 679 | valid palindrome | 125 | 0.437 | Easy | 1,375 |
https://leetcode.com/problems/valid-palindrome/discuss/998883/Python3-faster-than-90-Easy-to-understand | class Solution:
def isPalindrome(self, s: str) -> bool:
s1 = ''
for i in s:
if i.isalnum():
s1+=i.lower()
return s1[::-1] == s1 | valid-palindrome | Python3 faster than 90% Easy to understand | rotikapdamakan | 5 | 260 | valid palindrome | 125 | 0.437 | Easy | 1,376 |
https://leetcode.com/problems/valid-palindrome/discuss/2546948/2-Python-solutions-(2-pointers-solution-%2B-simple-2-lines-solution) | class Solution:
def isPalindrome(self, s: str) -> bool:
ptr1, ptr2 = 0, len(s)-1
while ptr1 < ptr2:
while ptr1 < ptr2 and not s[ptr1].isalnum():
ptr1 += 1
while ptr1 < ptr2 and not s[ptr2].isalnum():
ptr2 -= 1
if s[ptr1].lower() != s[ptr2].lower():
return False
ptr1 += 1
ptr2 -= 1
return True | valid-palindrome | ๐ 2 Python solutions (2 pointers solution + simple 2 lines solution) | croatoan | 3 | 280 | valid palindrome | 125 | 0.437 | Easy | 1,377 |
https://leetcode.com/problems/valid-palindrome/discuss/2546948/2-Python-solutions-(2-pointers-solution-%2B-simple-2-lines-solution) | class Solution:
def isPalindrome(self, s: str) -> bool:
filter = ''.join([i.lower() for i in s if i.isalnum()])
return filter == filter[::-1] | valid-palindrome | ๐ 2 Python solutions (2 pointers solution + simple 2 lines solution) | croatoan | 3 | 280 | valid palindrome | 125 | 0.437 | Easy | 1,378 |
https://leetcode.com/problems/valid-palindrome/discuss/1619720/Python3-Time-O(n)-or-Space-O(1)-or-2-pointers-in-place | class Solution:
def isPalindrome(self, s: str) -> bool:
l, r = 0, len(s) - 1
while l < r:
if s[l].isalnum() and s[r].isalnum():
if s[l].lower() != s[r].lower():
return False
l += 1
r -= 1
else:
if not s[l].isalnum():
l += 1
if not s[r].isalnum():
r -= 1
return True | valid-palindrome | [Python3] Time O(n) | Space O(1) | 2 pointers in-place | PatrickOweijane | 3 | 351 | valid palindrome | 125 | 0.437 | Easy | 1,379 |
https://leetcode.com/problems/valid-palindrome/discuss/1395136/Python-solution-in-2-lines | class Solution:
def isPalindrome(self, s: str) -> bool:
output = ''.join([char for char in s.lower() if char.isalpha() or char.isdigit()])
return output == output[::-1] | valid-palindrome | Python solution in 2 lines | bob23 | 3 | 297 | valid palindrome | 125 | 0.437 | Easy | 1,380 |
https://leetcode.com/problems/valid-palindrome/discuss/366729/Python-2-line | class Solution:
def isPalindrome(self, s: str) -> bool:
s = ''.join(l for l in s.casefold() if l.isalnum())
return s == s[::-1] | valid-palindrome | Python 2 line | amchoukir | 3 | 520 | valid palindrome | 125 | 0.437 | Easy | 1,381 |
https://leetcode.com/problems/valid-palindrome/discuss/2822176/PYTHON-isalpha()-or-isnumeric()-or-Simple | class Solution:
def isPalindrome(self, s: str) -> bool:
a = ""
for x in [*s]:
if x.isalpha(): a += x.lower()
if x.isnumeric(): a += x
return a == a[::-1] | valid-palindrome | [PYTHON] isalpha() | isnumeric() | Simple | omkarxpatel | 2 | 31 | valid palindrome | 125 | 0.437 | Easy | 1,382 |
https://leetcode.com/problems/valid-palindrome/discuss/2773675/Clean-python-code-O(n) | class Solution:
def isPalindrome(self, s: str) -> bool:
left, right = 0, len(s)-1
while right > left:
if not s[right].isalnum():
right -= 1
continue
if not s[left].isalnum():
left += 1
continue
if s[left].lower() != s[right].lower():
return False
right -= 1
left += 1
return True | valid-palindrome | Clean python code O(n) | really_cool_person | 2 | 844 | valid palindrome | 125 | 0.437 | Easy | 1,383 |
https://leetcode.com/problems/valid-palindrome/discuss/2430462/Python-Super-Simple-Cake-Walk-Solution | class Solution:
def isPalindrome(self, s: str) -> bool:
s = ''.join(c for c in s if c.isalnum()) #isalnum() checks whether character is alphanumeric or not
s = s.lower() # converts the string to lowercase
return s == s[::-1] # checks whether reverse of string is equal to string | valid-palindrome | ๐๐ฒ Python Super Simple Cake Walk Solution ๐ฒ๐ | sHadowSparK | 2 | 107 | valid palindrome | 125 | 0.437 | Easy | 1,384 |
https://leetcode.com/problems/valid-palindrome/discuss/1982004/Simple-Python-Solution-or-Faster-than-92 | class Solution:
def isPalindrome(self, s: str) -> bool:
res = ""
for c in s:
if c.isalnum():
res += c.lower()
print(res)
return res == res[::-1] | valid-palindrome | Simple Python Solution | Faster than 92% | nikhitamore | 2 | 277 | valid palindrome | 125 | 0.437 | Easy | 1,385 |
https://leetcode.com/problems/valid-palindrome/discuss/1860184/PYTHON3-or-Fastest-solution | class Solution:
def isPalindrome(self, s: str) -> bool:
s=s.lower()
alpha="abcdefghijklmnopqrstuvwxyz0123456789"
a=""
for i in s:
if i in alpha:
a+=i
return a[:]==a[::-1] | valid-palindrome | PYTHON3 | Fastest solution | Anilchouhan181 | 2 | 169 | valid palindrome | 125 | 0.437 | Easy | 1,386 |
https://leetcode.com/problems/valid-palindrome/discuss/1796466/Best-Python-Solution | class Solution:
def isPalindrome(self, s: str) -> bool:
a = ''
for i in s.lower():
if i.isalnum():
a += i
return a==a[::-1] | valid-palindrome | Best Python Solution | himanshu11sgh | 2 | 163 | valid palindrome | 125 | 0.437 | Easy | 1,387 |
https://leetcode.com/problems/valid-palindrome/discuss/1722965/Python-not-the-Fastest-but-98.88-less-memory | class Solution:
def isPalindrome(self, s: str) -> bool:
#var to hold new string
stringcheck = ''
#iterate through the letters
for letter in s:
if letter.isalnum() == True:
stringcheck=stringcheck+letter
return(stringcheck.lower() == stringcheck[::-1].lower()) | valid-palindrome | Python not the Fastest but 98.88% less memory | ovidaure | 2 | 281 | valid palindrome | 125 | 0.437 | Easy | 1,388 |
https://leetcode.com/problems/valid-palindrome/discuss/1623764/Python-solution-beats-98.59-on-run-time | class Solution:
def isPalindrome(self, s: str) -> bool:
s = ''.join(filter(str.isalnum, s))
s = s.lower()
return s == s[::-1] | valid-palindrome | Python solution beats 98.59% on run-time | sajid36 | 2 | 174 | valid palindrome | 125 | 0.437 | Easy | 1,389 |
https://leetcode.com/problems/valid-palindrome/discuss/1534623/Python-96%2B%2B-Faster-Solution-36ms | class Solution:
def isPalindrome(self, s: str) -> bool:
p = ""
for i in s.lower():
if i.isalnum():
p += i
else:
return p == p[::-1] | valid-palindrome | Python 96%++ Faster Solution-- 36ms | aaffriya | 2 | 314 | valid palindrome | 125 | 0.437 | Easy | 1,390 |
https://leetcode.com/problems/valid-palindrome/discuss/1331510/Python-easy-to-understand-short-solution | class Solution:
def isPalindrome(self, s: str) -> bool:
res = "".join(i.lower() for i in s if i.isalpha() or i.isnumeric())
return res == res[::-1] | valid-palindrome | Python easy-to-understand short solution | zedginidze | 2 | 218 | valid palindrome | 125 | 0.437 | Easy | 1,391 |
https://leetcode.com/problems/valid-palindrome/discuss/1311722/Python3-or-Faster-than-98.51-or-Using-alnum-and-lower | class Solution:
def isPalindrome(self, s: str) -> bool:
s = s.lower()
s = ''.join([x for x in s if x.isalnum()])
return s==s[::-1] | valid-palindrome | Python3 | Faster than 98.51% | Using alnum and lower | nishikantsinha | 2 | 127 | valid palindrome | 125 | 0.437 | Easy | 1,392 |
https://leetcode.com/problems/valid-palindrome/discuss/1122654/Python-solution-beats-99.9 | class Solution:
def isPalindrome(self, s: str) -> bool:
s = "".join( filter(str.isalnum, s.upper()) )
return (0,1)[s == s[::-1]] | valid-palindrome | Python solution beats 99.9% | malleswari1593 | 2 | 270 | valid palindrome | 125 | 0.437 | Easy | 1,393 |
https://leetcode.com/problems/valid-palindrome/discuss/503932/Python-2-pointers | class Solution:
def isPalindrome(self, s: str) -> bool:
p1 = 0
p2 = len(s)-1
while p1 < p2:
while p1 < p2 and not s[p1].isalnum():
p1 += 1
while p1 < p2 and not s[p2].isalnum():
p2 -= 1
if p1 < p2:
if s[p1].lower() == s[p2].lower():
p1 += 1
p2 -= 1
else: return False
return True | valid-palindrome | Python - 2 pointers | krion77 | 2 | 220 | valid palindrome | 125 | 0.437 | Easy | 1,394 |
https://leetcode.com/problems/valid-palindrome/discuss/2247140/Python3-Super-Easy-Solution-or-Efficient | class Solution:
def isPalindrome(self, s: str) -> bool:
s_out = ''
for char in s:
if char.isalnum():
s_out += char.lower()
return s_out == s_out[::-1] | valid-palindrome | โ
Python3 - Super Easy Solution | Efficient | thesauravs | 1 | 87 | valid palindrome | 125 | 0.437 | Easy | 1,395 |
https://leetcode.com/problems/valid-palindrome/discuss/2087958/Python3-O(N)-oror-O(N)-and-O(N)-oror-O(1)-solution | class Solution:
def isPalindrome(self, string: str) -> bool:
# return self.isPalindromeByList(string)
return self.isPalindromeOptimal(string)
# O(n) || O(1); worse: runtime: O(n^2)
# 106ms 11.29%
def isPalindromeOptimal(self, string):
if not string:
return True
left, right = 0, len(string) - 1
while left < right:
while left < right and not self.isAlphaNum(string[left]):
left += 1
while right > left and not self.isAlphaNum(string[right]):
right -= 1
if string[left].lower() != string[right].lower():
return False
left, right = left + 1, right - 1
return True
def isAlphaNum(self, char):
return ((ord('A') <= ord(char) <= ord('Z')) or
(ord('a') <= ord(char) <= ord('z')) or
(ord('0') <= ord(char) <= ord('9')))
# O(n) || O(n)
# 56ms 70.35%
def isPalindromeByList(self, string):
if not string:
return True
newStringList = list()
for char in string:
if char.isalnum():
newStringList.append(char.lower())
left, right = 0, len(newStringList) - 1
while left < right:
if newStringList[left] != newStringList[right]:
return False
left += 1
right -= 1
return True | valid-palindrome | Python3 O(N) || O(N) and O(N) || O(1) solution | arshergon | 1 | 120 | valid palindrome | 125 | 0.437 | Easy | 1,396 |
https://leetcode.com/problems/valid-palindrome/discuss/2047838/Python3-simple-solution-with-very-few-lines-of-code! | class Solution:
def isPalindrome(self, s: str) -> bool:
s1 = []
for key in s:
if key.isalpha() or key.isdigit():
s1.append(key.lower())
return s1 == s1[::-1] | valid-palindrome | Python3 simple solution with very few lines of code! | ji3010 | 1 | 203 | valid palindrome | 125 | 0.437 | Easy | 1,397 |
https://leetcode.com/problems/valid-palindrome/discuss/1762054/Python-solution | class Solution:
def isPalindrome(self, s: str) -> bool:
str1 = ""
str2 = ""
for i in s.lower():
if i.isalnum():
str1 = i + str1
if i.isalpha() or i.isdigit():
str2 += i
if str1 == str2:
return True
else:
return False | valid-palindrome | Python solution | payalsasmal | 1 | 92 | valid palindrome | 125 | 0.437 | Easy | 1,398 |
https://leetcode.com/problems/valid-palindrome/discuss/1762054/Python-solution | class Solution:
def alphanumeric(self, st):
if ((ord(st)>=48 and ord(st)<=57) or (ord(st) >= 65 and ord(st) <= 90) or (ord(st) >=97 and ord(st) <= 122)):
return True
return False
def isPalindrome(self, s: str) -> bool:
str1 = ""
str2 = ""
for i in s.lower():
if self.alphanumeric(i):
str1 = i + str1
if self.alphanumeric(i):
str2 += i
if str1 == str2:
return True
else:
return False | valid-palindrome | Python solution | payalsasmal | 1 | 92 | valid palindrome | 125 | 0.437 | Easy | 1,399 |
Subsets and Splits