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/power-of-two/discuss/2837128/python-oror-simple-solution-oror-1-liner-(hamming-weight) | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
# not negative and hamming weight is 1
return (n > 0) and (bin(n).count("1") == 1) | power-of-two | python || simple solution || 1-liner (hamming weight) | wduf | 0 | 1 | power of two | 231 | 0.457 | Easy | 4,300 |
https://leetcode.com/problems/power-of-two/discuss/2829613/Python-Solution | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n == 0:
return False
if n == 1:
return True
while n != 1:
if n % 2 != 0:
return False
n = n / 2
return True | power-of-two | Python Solution | Antoine703 | 0 | 1 | power of two | 231 | 0.457 | Easy | 4,301 |
https://leetcode.com/problems/power-of-two/discuss/2808012/Python-95-Solution | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n == 0:
return False
while n != 1:
n = n/2
if n%2 != 0 and n !=1:
return False
return True | power-of-two | Python 95% Solution | Jashan6 | 0 | 4 | power of two | 231 | 0.457 | Easy | 4,302 |
https://leetcode.com/problems/power-of-two/discuss/2806622/Python-one-liner-100(Simple-solution) | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n != 0 and (n & (n-1)) == 0 | power-of-two | Python one liner 100%(Simple solution) | farruhzokirov00 | 0 | 4 | power of two | 231 | 0.457 | Easy | 4,303 |
https://leetcode.com/problems/power-of-two/discuss/2785281/without-using-loop-in-O(1) | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n <= 0: return False
if n == 536870912: return True
return math.floor(math.log(n,2)) == math.ceil(math.log(n,2)) | power-of-two | without using loop in O(1) | sanskar_ | 0 | 6 | power of two | 231 | 0.457 | Easy | 4,304 |
https://leetcode.com/problems/power-of-two/discuss/2782029/Works-for-all-power-of-234-problems | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n==0:
return False
while n%2==0:
n/=2
if n==1:
return True
return False | power-of-two | Works for all, power of 2,3,4 problems | MayuD | 0 | 2 | power of two | 231 | 0.457 | Easy | 4,305 |
https://leetcode.com/problems/power-of-two/discuss/2775719/using-shifting | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
a=1
while(a<n):
a<<=1
return a==n | power-of-two | using shifting | droj | 0 | 4 | power of two | 231 | 0.457 | Easy | 4,306 |
https://leetcode.com/problems/power-of-two/discuss/2746604/Python3-Solution | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if not n or n < 0:
return False
while n > 1:
if n % 2 == 1:
return False
n = n//2
return True | power-of-two | Python3 Solution | paul1202 | 0 | 3 | power of two | 231 | 0.457 | Easy | 4,307 |
https://leetcode.com/problems/power-of-two/discuss/2739347/Simple-Python3-Solution | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n == 0:
return False
while n != 1:
if n%2 != 0:
return False
n = n // 2
return True | power-of-two | Simple Python3 Solution | dnvavinash | 0 | 4 | power of two | 231 | 0.457 | Easy | 4,308 |
https://leetcode.com/problems/power-of-two/discuss/2737786/easy-approach-using-python | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
while n%2==0 and n>1:
n=n/2
return True if n==1 else False | power-of-two | easy approach using python | sindhu_300 | 0 | 9 | power of two | 231 | 0.457 | Easy | 4,309 |
https://leetcode.com/problems/power-of-two/discuss/2735214/Simple-solution-in-Python. | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and (1 << int(math.log2(n))) == n | power-of-two | Simple solution in Python. | ahmedsamara | 0 | 9 | power of two | 231 | 0.457 | Easy | 4,310 |
https://leetcode.com/problems/power-of-two/discuss/2682896/python-simple-soln | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n==0:
return False
else:
if(n&n-1==0):
return True
else :
return False | power-of-two | python simple soln | AMBER_FATIMA | 0 | 2 | power of two | 231 | 0.457 | Easy | 4,311 |
https://leetcode.com/problems/power-of-two/discuss/2682147/Python-Solution | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n==1:
return True
if n==0:
return False
while n != 1:
if n%2 == 0:
n = n /2
else:
return False
return True | power-of-two | Python Solution | Sheeza | 0 | 3 | power of two | 231 | 0.457 | Easy | 4,312 |
https://leetcode.com/problems/power-of-two/discuss/2669924/Python-1-Liner | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return "{0:b}".format(n).strip('0') == '1' | power-of-two | Python 1-Liner | mephiticfire | 0 | 7 | power of two | 231 | 0.457 | Easy | 4,313 |
https://leetcode.com/problems/power-of-two/discuss/2667218/Python-solution-using-recursion | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n == 0:
return False
if n == 1 or n == 2:
return True
return self.isPowerOfTwo(n/2) | power-of-two | Python solution using recursion | MPoinelli | 0 | 7 | power of two | 231 | 0.457 | Easy | 4,314 |
https://leetcode.com/problems/power-of-two/discuss/2654420/Pyhton3-easy-solution | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
# integer maximum range is 2**30 so , here range is 0 to 31.
for i in range(0,31):
if n == 2**i :
return True
return False | power-of-two | Pyhton3 easy solution | 24Neha | 0 | 24 | power of two | 231 | 0.457 | Easy | 4,315 |
https://leetcode.com/problems/power-of-two/discuss/2614079/Python-Solution-Time-ComplexityO(n)-Interview-Approach | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n<=0:
return False
while n>1:
if n%2!=0: return False
n//=2
return True | power-of-two | [Python Solution] Time Complexity=O(n) - Interview Approach | utsa_gupta | 0 | 17 | power of two | 231 | 0.457 | Easy | 4,316 |
https://leetcode.com/problems/power-of-two/discuss/2559567/Python-(Simple-Solution-and-Beginner-Friendly) | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
while n>1:
n = n/2
return n == 1 | power-of-two | Python (Simple Solution and Beginner-Friendly) | vishvavariya | 0 | 77 | power of two | 231 | 0.457 | Easy | 4,317 |
https://leetcode.com/problems/power-of-two/discuss/2513792/Python-99-Faster-Solution | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n < 0:
return False
n = bin(n)[2:]
count = 0
for i in range(len(n)):
if n[i] == '1':
count += 1
if count == 1:
return True
else:
return False | power-of-two | [Python] 99% Faster Solution | jiarow | 0 | 84 | power of two | 231 | 0.457 | Easy | 4,318 |
https://leetcode.com/problems/power-of-two/discuss/2491522/C%2B%2BPythonJava-Best-Optimized-Solutions-greater-O(1)-and-O(logN)-Solution | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n==0:
return False
while n!=1:
if n%2!=0:
return False
n/=2
return True
# Time Complexity = O(N)
# Space Complexity = O(1) | power-of-two | C++/Python/Java Best Optimized Solutions -> O(1) and O(logN) Solution | arpit3043 | 0 | 33 | power of two | 231 | 0.457 | Easy | 4,319 |
https://leetcode.com/problems/power-of-two/discuss/2406331/pythonoror-easy-ororbeginnerororone-linerororrecursionoror-o(1)-oror-90Faster | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if (n)==1:
return True
if n<1:
return False
return self.isPowerOfTwo(n/2) | power-of-two | python|| easy ||beginner||one-liner||recursion|| o(1) || 90%Faster | shikhar_srivastava391 | 0 | 121 | power of two | 231 | 0.457 | Easy | 4,320 |
https://leetcode.com/problems/power-of-two/discuss/2406331/pythonoror-easy-ororbeginnerororone-linerororrecursionoror-o(1)-oror-90Faster | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n>0 and n&(n-1)==0:
return True | power-of-two | python|| easy ||beginner||one-liner||recursion|| o(1) || 90%Faster | shikhar_srivastava391 | 0 | 121 | power of two | 231 | 0.457 | Easy | 4,321 |
https://leetcode.com/problems/power-of-two/discuss/2392469/Python-Bit-manipulation-%2B-Explanation | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n == 0:
return False
return (n & -n) == n | power-of-two | Python [Bit manipulation] + Explanation | Yauhenish | 0 | 23 | power of two | 231 | 0.457 | Easy | 4,322 |
https://leetcode.com/problems/power-of-two/discuss/2365708/Python-solution-or-Simple-and-Easy-to-Understand-or-36-ms-or-90-faster | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
x = 0
y = pow(2, x)
while y < n:
x+=1
y = pow(2, x)
if (n - pow(2,x)) == 0:
return True
else:
return False | power-of-two | Python solution | Simple and Easy to Understand | 36 ms | 90% faster | harishmanjunatheswaran | 0 | 49 | power of two | 231 | 0.457 | Easy | 4,323 |
https://leetcode.com/problems/power-of-two/discuss/2361436/Python3-solution-with-Detailed-Explanation | class Solution:
def isPowerOfTwo(self, x: int) -> bool:
# TC = O(1); SC = O(1)
# a power of 2 has only kth bit set in its binary representation
# and ( power of 2 ) - 1 -> has all bits set except the kth bit
# so taking bitwise of these two numbers would always give 0
return (x!=0) and (x & (x-1)) == 0
# Example 1:
# if x = 0 ans = False
# if x = 1 ans = True and 1 & 0 == 0 -> True so True and True = True
# 00000
# & 00001
# ---------
# 00000
# ---------
# Example 2:
# if x = 16 , then x - 1 = 15; so x & x-1 == 0 will check:
# 16 = 10000
# 15 = & 01111
# --------------------
# 00000
# -------------------- | power-of-two | Python3 solution with Detailed Explanation | jinwooo | 0 | 15 | power of two | 231 | 0.457 | Easy | 4,324 |
https://leetcode.com/problems/power-of-two/discuss/2333671/Runtime%3A-33-ms-faster-than-93.38-of-Python3 | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n == 1: return True
count = 1
while(count<n):
count = count * 2
return count == n | power-of-two | Runtime: 33 ms, faster than 93.38% of Python3 | amit0693 | 0 | 28 | power of two | 231 | 0.457 | Easy | 4,325 |
https://leetcode.com/problems/power-of-two/discuss/2255862/Memory-Usage-Less-Than-95.30 | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
while n>=1:
if n==1:
return True
if n%2!=0:
return False
n=n//2
return False | power-of-two | Memory Usage Less Than 95.30% | jayeshvarma | 0 | 27 | power of two | 231 | 0.457 | Easy | 4,326 |
https://leetcode.com/problems/power-of-two/discuss/2255785/Python-3-using-Recursion | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n == 1:
return True
elif n > 1 and n - int(n) == 0: # Check is a whole number
return self.isPowerOfTwo(n / 2)
return False | power-of-two | Python 3 using Recursion | kdoyle | 0 | 50 | power of two | 231 | 0.457 | Easy | 4,327 |
https://leetcode.com/problems/power-of-two/discuss/2128872/Easy-Python-Solution-94.57-in-Time-95.27-in-Space | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
for m in range(32):
if 2**m == n:
return True
return False | power-of-two | Easy Python Solution, 94.57% in Time, 95.27% in Space | tylerpruitt | 0 | 131 | power of two | 231 | 0.457 | Easy | 4,328 |
https://leetcode.com/problems/power-of-two/discuss/2055230/Simple-Math-Python-Solution-or-85-Faster-or-Memory-less-than-60 | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n <= 0:
return False
else:
new = math.log2(n)
return new//1==new/1 | power-of-two | Simple Math Python Solution | 85% Faster | Memory less than 60% | eerie997 | 0 | 54 | power of two | 231 | 0.457 | Easy | 4,329 |
https://leetcode.com/problems/power-of-two/discuss/2050879/Using-bitwise-operator | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n == 0:
return False
return not n & n - 1 | power-of-two | Using bitwise operator | andrewnerdimo | 0 | 47 | power of two | 231 | 0.457 | Easy | 4,330 |
https://leetcode.com/problems/power-of-two/discuss/2019538/Python3-Solution-Recursion-and-Bit-Manipulation-2-solutions | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n == 1:
return True
elif n % 2 != 0 or n <= 0:
return False
else:
return self.isPowerOfTwo(n // 2) | power-of-two | Python3 Solution, Recursion and Bit Manipulation, 2 solutions | AprDev2011 | 0 | 28 | power of two | 231 | 0.457 | Easy | 4,331 |
https://leetcode.com/problems/power-of-two/discuss/2019538/Python3-Solution-Recursion-and-Bit-Manipulation-2-solutions | class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n <= 0:
return False
return n & (n-1) == 0 | power-of-two | Python3 Solution, Recursion and Bit Manipulation, 2 solutions | AprDev2011 | 0 | 28 | power of two | 231 | 0.457 | Easy | 4,332 |
https://leetcode.com/problems/number-of-digit-one/discuss/1655517/Python3-O(9)-Straight-Math-Solution | class Solution:
def countDigitOne(self, n: int) -> int:
#O(logn) mathematical solution
#intervals of new 1s: 0-9, 10-99, 100-999, 1000,9999...
#each interval yields 1,10,100,etc. new '1's respectively
#first and foremost, we want to check how many of each interval repeats
#conditions for FULL yield when curr%upper bound+1: 1 <=, 19 <=, 199 <=...
#conditions for PARTIAL yielf when curr%upper bound+1: None, 10 <= < 19, 100 <= < 199, 1000 <= < 1999 ...
ans = 0
for i in range(len(str(n))):
curr = 10**(i+1)
hi,lo = int('1'+'9'*i), int('1'+'0'*i)
ans += (n//curr) * 10**i
if (pot:=n%curr) >= hi: ans += 10**i
elif lo <= pot < hi:
ans += pot - lo + 1
return ans | number-of-digit-one | Python3 O(9) Straight Math Solution | terrysu64 | 1 | 341 | number of digit one | 233 | 0.342 | Hard | 4,333 |
https://leetcode.com/problems/number-of-digit-one/discuss/1565034/python-O(log10(n)) | class Solution:
def countDigitOne(self, n: int) -> int:
res, cur = 0, 1
while cur <= n:
res += n // (cur * 10) * cur + min(max(n % (cur * 10) - cur + 1, 0), cur)
cur *= 10
return res | number-of-digit-one | python O(log10(n)) | dereky4 | 1 | 325 | number of digit one | 233 | 0.342 | Hard | 4,334 |
https://leetcode.com/problems/number-of-digit-one/discuss/753348/Python3-two-approaches | class Solution:
def countDigitOne(self, n: int) -> int:
return sum(str(i).count("1") for i in range(1, n+1)) | number-of-digit-one | [Python3] two approaches | ye15 | 1 | 191 | number of digit one | 233 | 0.342 | Hard | 4,335 |
https://leetcode.com/problems/number-of-digit-one/discuss/753348/Python3-two-approaches | class Solution:
def countDigitOne(self, n: int) -> int:
if n < 0: return 0 #edge case
ans = d = tr = 0
m = 1 # magnitude
while n:
tr += d*m//10 #trailing digit
n, d = divmod(n, 10) #leading & current digit
ans += n * m
if d == 1: ans += tr + 1
elif d > 1: ans += m
m *= 10
return ans | number-of-digit-one | [Python3] two approaches | ye15 | 1 | 191 | number of digit one | 233 | 0.342 | Hard | 4,336 |
https://leetcode.com/problems/number-of-digit-one/discuss/753348/Python3-two-approaches | class Solution:
def countDigitOne(self, n: int) -> int:
if n < 0: return 0 #edge case
#number of 1's in n where 0 <= n <= x*10**i
fn = lambda k, i: k*i*10**(i-1) + (k==1) + (k>1)*10**i
ans = val = i = 0
while n:
n, x = divmod(n, 10)
ans += fn(x, i) + (x==1)*val
val += x*10**i
i += 1
return int(ans) | number-of-digit-one | [Python3] two approaches | ye15 | 1 | 191 | number of digit one | 233 | 0.342 | Hard | 4,337 |
https://leetcode.com/problems/number-of-digit-one/discuss/506131/Python3-two-simple-solutions | class Solution:
def countDigitOne(self, n: int) -> int:
if n==0: return 0
res,m=0,1
while m<=n:
a,b=n//m,n%m
if a%10>1: res+=(a//10+1)*m
elif a%10==1: res+=(a//10)*m+b+1
elif a%10==0: res+=(a//10)*m
m*=10
return res
def countDigitOne1(self, n: int) -> int:
if n==0: return 0
res,count="",0
for i in range(1,n+1):
res+=str(i)
for char in res:
if char=="1": count+=1
return count | number-of-digit-one | Python3 two simple solutions | jb07 | 1 | 151 | number of digit one | 233 | 0.342 | Hard | 4,338 |
https://leetcode.com/problems/number-of-digit-one/discuss/2179625/Python-mathematical-approach-digit-by-digit | class Solution:
def countDigitOne(self, n: int) -> int:
num = str(n)[::-1]
count = 0
for i in range(len(num)-1, -1, -1):
pv = 10**i # placevalue
# mulitplicity of current digit (how many times it will be repeated)
mul = n//(pv*10)
rem = n % pv # remainder of current place value
count += mul * pv # count for number of times 1 occurs in this place when the current digit is considered to be less than 1
# if the current digit is greater than 1 then additional number of 1's are added to the count (equivalent to the place value)
if num[i] > '1':
count += pv
# if the current digit is equal to 1 then additional number of 1's are added to the count (equivalent to the number modded by the current place value)
if num[i] == '1':
count += rem + 1
return count | number-of-digit-one | Python mathematical approach digit by digit | ComicCoder023 | 0 | 176 | number of digit one | 233 | 0.342 | Hard | 4,339 |
https://leetcode.com/problems/number-of-digit-one/discuss/1604219/Python-Easy-Solution-or-With-Explanation | class Solution:
def countDigitOne(self, n: int) -> int:
# No. of 1s at one's Position (n/10) + (n%10!=0)
# No. of 1s at ten's Position (n/100)*10 + min(max(n%100 - 10 +1,0),10)
# No. of 1s at Hundread's Dosition (n/1000)*100 + min(max(n%1000 - 100 +1,0),100)
res = 0
cur = 1
while cur <= n:
res += ((n//(cur*10))*cur)+min(max(n % (cur*10)-cur+1, 0), cur)
cur *= 10
return res | number-of-digit-one | Python Easy Solution | With Explanation ✔ | leet_satyam | 0 | 505 | number of digit one | 233 | 0.342 | Hard | 4,340 |
https://leetcode.com/problems/number-of-digit-one/discuss/1291619/East-to-understand.-From-recursive-to-straight-forward-from-a-noob-user-O(log-n)-no-extra-memory | class Solution:
@lru_cache()
def countDigitOne(self, n: int) -> int:
#print(n)
if n == 0:
return 0
elif 1 < n <= 9:
return 1
l = len(str(n))
if n // 10 ** (l - 1) > 1:
return self.countDigitOne(n % (10 ** (l - 1))) + \
(self.countDigitOne(10 ** (l - 1)-1)) * (n // (10 ** (l - 1)) - 2) + \
(10 ** (l - 1) + self.countDigitOne(10 ** (l - 1)-1)) + \
self.countDigitOne(10 ** (l - 1)-1)
else:
return self.countDigitOne(n % (10 ** (l - 1))) + n % (10 ** (l - 1)) + 1+ \
self.countDigitOne(10 ** (l - 1)-1) | number-of-digit-one | East to understand. From recursive to straight-forward from a noob user, O(log n), no extra memory | 1970633640 | 0 | 349 | number of digit one | 233 | 0.342 | Hard | 4,341 |
https://leetcode.com/problems/number-of-digit-one/discuss/1291619/East-to-understand.-From-recursive-to-straight-forward-from-a-noob-user-O(log-n)-no-extra-memory | class Solution:
def countDigitOne(self, n: int) -> int:
tens = 1
fnum = 1 if n % 10 > 0 else 0
fnines = 0
num = n
num = num // 10
while num:
fnines = fnines * 10 + tens
tens = tens * 10
c = num % 10
if c == 1:
fnum = fnum + n % tens + 1 + fnines
elif c > 1:
fnum = fnum + c * fnines + tens
num = num // 10
return fnum | number-of-digit-one | East to understand. From recursive to straight-forward from a noob user, O(log n), no extra memory | 1970633640 | 0 | 349 | number of digit one | 233 | 0.342 | Hard | 4,342 |
https://leetcode.com/problems/number-of-digit-one/discuss/637821/Python3-16-ms-14-MB-beats-100 | class Solution:
def countDigitOne(self, n: int) -> int:
if n < 1: return 0
# i = 0
p = 1 # 10 ** i
c = 0 # count of 1s less than 10 ** i
result = 0
for char in str(n)[::-1]:
d = int(char)
# if d == 0: pass
if d == 1:
result += c + n%(p) + 1
elif d > 1:
result += p + d*c
c += p + (c<<3)+c # c = p + 8*c + c
p = (p<<3)+p+p # p *= 10
# i += 1
return result | number-of-digit-one | Python3 16 ms, 14 MB - beats 100% | augustuslogsdon | 0 | 409 | number of digit one | 233 | 0.342 | Hard | 4,343 |
https://leetcode.com/problems/palindrome-linked-list/discuss/2466200/Python-O(N)O(1) | class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
def reverse(node):
prev = None
while node:
next_node = node.next
node.next = prev
prev, node = node, next_node
return prev
slow = head
fast = head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
n1 = head
n2 = reverse(slow.next)
while n2:
if n1.val != n2.val:
return False
n1 = n1.next
n2 = n2.next
return True | palindrome-linked-list | Python, O(N)/O(1) | blue_sky5 | 7 | 839 | palindrome linked list | 234 | 0.496 | Easy | 4,344 |
https://leetcode.com/problems/palindrome-linked-list/discuss/1151395/Python-3-or-Easy-Solution | class Solution:
def isPalindrome(self, head: ListNode) -> bool:
#vList = valueList
vList = []
#Converting to list
while head != None:
if head.val == 0:
vList.append(0)
else:
vList.append(head.val)
head = head.next
#nList = newList which will be reverse of vList
nList = vList[::-1]
#Checking for Palindrome!
if nList == vList:
return True
else:
return False | palindrome-linked-list | Python 3 | Easy Solution | iamvatsalpatel | 6 | 531 | palindrome linked list | 234 | 0.496 | Easy | 4,345 |
https://leetcode.com/problems/palindrome-linked-list/discuss/2245119/Python-Reverse-the-Middle-of-the-Linked-List-Time-O(N)-or-Space-O(1)-Explained | class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
slow = head
fast = head
# We use slow and fast pointer algorithm to get the middle of the linked list
while fast and fast.next:
slow = slow.next
fast = fast.next.next
secondHalfEnd = self.reverse(slow)
pointer1 = head
pointer2 = secondHalfEnd
validPalindrome = True
while pointer1 and pointer2:
if pointer1.val != pointer2.val:
validPalindrome = False
break
pointer1 = pointer1.next
pointer2 = pointer2.next
self.reverse(secondHalfEnd) # Reverse the second half of the Linked List back to normal
return validPalindrome
def reverse(self, head):
prev = None
current = head
while current:
temp = current.next
current.next = prev
prev = current
current = temp
return prev | palindrome-linked-list | [Python] Reverse the Middle of the Linked List - Time O(N) | Space O(1) Explained | Symbolistic | 5 | 308 | palindrome linked list | 234 | 0.496 | Easy | 4,346 |
https://leetcode.com/problems/palindrome-linked-list/discuss/1326533/Python-or-O(n)-Time-or-O(1)-Space-or-~95-or-With-Comments | class Solution:
def isPalindrome(self, head: ListNode) -> bool:
prev = None
fast = head
slow = head
# Reverse half the list while trying to find the end
while fast and fast.next:
fast = fast.next.next
next_node = slow.next
slow.next = prev
prev = slow
slow = next_node
# left side
left = prev
# right side
if fast:
'''
if fast is not None, then the length of the list is odd
and we can ignore the middle value
'''
right = slow.next
else:
right = slow
# Just need to traverse each side and check if the values equal or not.
while left is not None and right is not None:
if left.val != right.val:
return False
left = left.next
right = right.next
return True | palindrome-linked-list | Python | O(n) Time | O(1) Space | ~95% | With Comments | peatear-anthony | 4 | 503 | palindrome linked list | 234 | 0.496 | Easy | 4,347 |
https://leetcode.com/problems/palindrome-linked-list/discuss/382762/Python-solutions | class Solution:
def isPalindromeRec(self, head, node):
if not node:
return (head, True)
cur, is_palindrome = self.isPalindromeRec(head, node.next)
if not is_palindrome:
return (None, False)
if cur.val != node.val:
return (None, False)
return (cur.next, True)
def isPalindrome(self, head: ListNode) -> bool:
return self.isPalindromeRec(head, head)[1] | palindrome-linked-list | Python solutions | amchoukir | 4 | 1,400 | palindrome linked list | 234 | 0.496 | Easy | 4,348 |
https://leetcode.com/problems/palindrome-linked-list/discuss/382762/Python-solutions | class Solution:
def isPalindrome(self, head: ListNode) -> bool:
stack = []
node = head
while node:
stack.append(node.val)
node = node.next
node = head
while node:
if stack[-1] != node.val:
return False
stack.pop()
node = node.next
return True | palindrome-linked-list | Python solutions | amchoukir | 4 | 1,400 | palindrome linked list | 234 | 0.496 | Easy | 4,349 |
https://leetcode.com/problems/palindrome-linked-list/discuss/382762/Python-solutions | class Solution:
def reverseList(self, head):
prev = None
cur = head
while cur:
next = cur.next
cur.next = prev
prev = cur
cur = next
return prev
def isSame(self, node1, node2):
while node1 and node2:
if node1.val != node2.val:
return False
node1 = node1.next
node2 = node2.next
return True
def isPalindrome(self, head: ListNode) -> bool:
if not head or not head.next:
return True
slow = head
fast = head.next
len_list = 2
while fast and fast.next:
slow = slow.next
fast = fast.next.next
len_list += 2
if not fast:
len_list -= 1
tail_first_half = slow
head_second_half = slow.next
slow.next = None # Cutting the list in two
head_first_half = self.reverseList(head)
node1 = head_first_half
node2 = head_second_half
result = self.isSame(node1, node2) if len_list & 1 == 0 else self.isSame(node1.next, node2)
self.reverseList(head_first_half)
tail_first_half.next = head_second_half # Puting back the list together
return result | palindrome-linked-list | Python solutions | amchoukir | 4 | 1,400 | palindrome linked list | 234 | 0.496 | Easy | 4,350 |
https://leetcode.com/problems/palindrome-linked-list/discuss/382762/Python-solutions | class Solution:
def isPalindrome(self, head: ListNode) -> bool:
rev = None
slow = fast = head
while fast and fast.next:
fast = fast.next.next
rev, rev.next, slow = slow, rev, slow.next
if fast:
slow = slow.next
while rev and rev.val == slow.val:
rev = rev.next
slow = slow.next
return not rev | palindrome-linked-list | Python solutions | amchoukir | 4 | 1,400 | palindrome linked list | 234 | 0.496 | Easy | 4,351 |
https://leetcode.com/problems/palindrome-linked-list/discuss/382762/Python-solutions | class Solution:
def isPalindrome(self, head: ListNode) -> bool:
rev = None
fast = head
while fast and fast.next:
fast = fast.next.next
rev, rev.next, head = head, rev, head.next
tail = head.next if fast else head
result = True
while rev:
result = result and rev.val == tail.val
head, head.next, rev = rev, head, rev.next
tail = tail.next
return result | palindrome-linked-list | Python solutions | amchoukir | 4 | 1,400 | palindrome linked list | 234 | 0.496 | Easy | 4,352 |
https://leetcode.com/problems/palindrome-linked-list/discuss/1318032/Clean-Code-Simple-Beginners-Solution-O(N)-time-and-space | class Solution:
def isPalindrome(self, head: ListNode) -> bool:
stack = []
# stores the first half
n = 0
cur = head
while cur:
cur = cur.next
n += 1
cur = head
for x in range(n//2):
stack.append(cur.val)
cur = cur.next
if n % 2: cur = cur.next
while cur:
if stack[-1] != cur.val: return False
stack.pop()
cur = cur.next
return True | palindrome-linked-list | Clean Code - Simple Beginners Solution O(N) time and space | yozaam | 3 | 283 | palindrome linked list | 234 | 0.496 | Easy | 4,353 |
https://leetcode.com/problems/palindrome-linked-list/discuss/1048461/Most-simple-solution-Python | class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if head is None:
return True
tmp = []
while head != None:
tmp.append(head.val)
head = head.next
return tmp == tmp[::-1] | palindrome-linked-list | Most simple solution Python | NicolasIbagon | 3 | 426 | palindrome linked list | 234 | 0.496 | Easy | 4,354 |
https://leetcode.com/problems/palindrome-linked-list/discuss/536240/O(1)-space-easy-Python-3-with-comments | class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if not head or not head.next:
return True
# find the middle of the list
currentSlow = currentFast = head
while currentFast:
currentSlow = currentSlow.next
if currentFast.next:
currentFast = currentFast.next.next
else:
break
# reverse second part of the list
previous = currentSlow
current = currentSlow.next
previous.next = None
while current:
nextNode = current.next
current.next = previous
previous = current
current = nextNode
# compare the front and back of the list
currentReverse = previous
currentForward = head
while currentReverse and currentForward:
if currentForward.val != currentReverse.val:
return False
currentReverse = currentReverse.next
currentForward = currentForward.next
return True | palindrome-linked-list | O(1) space, easy Python 3 with comments | kstanski | 3 | 617 | palindrome linked list | 234 | 0.496 | Easy | 4,355 |
https://leetcode.com/problems/palindrome-linked-list/discuss/2817187/The-simplest | class Solution:
def isPalindrome(self, head: ListNode) -> bool:
source = []
while head is not None:
source.append(head.val)
head = head.next
return source == source[::-1] | palindrome-linked-list | The simplest | pkozhem | 2 | 195 | palindrome linked list | 234 | 0.496 | Easy | 4,356 |
https://leetcode.com/problems/palindrome-linked-list/discuss/1840924/code-explans-itself-python-5-liner | class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
lst = []
while head:
lst.append(head.val)
head = head.next
#turns the head to a list
return lst == lst[::-1] | palindrome-linked-list | code explans itself python 5 liner | ggeeoorrggee | 2 | 183 | palindrome linked list | 234 | 0.496 | Easy | 4,357 |
https://leetcode.com/problems/palindrome-linked-list/discuss/1793728/PYTHON-VERY-EASY-SOLUTION | class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
slow = head
# 1. Append all of the value/data in the list
res = []
while slow:
res.append(slow.val)
slow = slow.next
# 2. Compare the default list with reverse version of that lists. If they are the same return "True" else return "False"
if res == res[::-1]:
return True
else:
return False | palindrome-linked-list | PYTHON VERY EASY SOLUTION | JS177117P | 2 | 77 | palindrome linked list | 234 | 0.496 | Easy | 4,358 |
https://leetcode.com/problems/palindrome-linked-list/discuss/1214103/Python3-or-O(1)-Space | class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if not head:
return
slow_ptr = head
fast_ptr = head
prev = None
while(fast_ptr and fast_ptr.next):
slow_ptr = slow_ptr.next
fast_ptr = fast_ptr.next.next
curr = slow_ptr
while(curr):
tmp = curr.next
curr.next = prev
prev = curr
curr = tmp
tmp_head = head
while(tmp_head and tmp_head!=slow_ptr and prev):
if tmp_head.val != prev.val:
return False
tmp_head = tmp_head.next
prev = prev.next
return True | palindrome-linked-list | Python3 | O(1) Space | jhaanimesh1996 | 2 | 325 | palindrome linked list | 234 | 0.496 | Easy | 4,359 |
https://leetcode.com/problems/palindrome-linked-list/discuss/468337/Python-3-(five-lines)-(beats-~99) | class Solution:
def isPalindrome(self, H: ListNode) -> bool:
A = []
while H != None: H, _ = H.next, A.append(H.val)
for i in range(len(A)//2):
if A[i] != A[-(i+1)]: return False
return True
- Junaid Mansuri
- Chicago, IL | palindrome-linked-list | Python 3 (five lines) (beats ~99%) | junaidmansuri | 2 | 761 | palindrome linked list | 234 | 0.496 | Easy | 4,360 |
https://leetcode.com/problems/palindrome-linked-list/discuss/2468853/Python-oror-O(1)-space-oror-detailed-explanation | class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
temp = []
cur = head
while cur:
temp.append(cur.val)
cur = cur.next
if temp == temp[::-1]:
return True
return False | palindrome-linked-list | Python || O(1) space || detailed explanation ✅ | wilspi | 1 | 45 | palindrome linked list | 234 | 0.496 | Easy | 4,361 |
https://leetcode.com/problems/palindrome-linked-list/discuss/2468853/Python-oror-O(1)-space-oror-detailed-explanation | class Solution:
def reverse(self, head):
cur = head
pre = None
while cur:
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
return pre
def getLen(self, head):
list_len = 0
cur = head
while cur:
list_len += 1
cur = cur.next
return list_len
def isPalindrome(self, head: Optional[ListNode]) -> bool:
list_len = self.getLen(head)
if list_len == 1:
return True
cur, i = head, 1
while i < (list_len // 2):
cur = cur.next
i += 1
second_head = cur.next
cur.next = None
first_head = self.reverse(head)
cur1 = first_head
cur2 = second_head if list_len % 2 == 0 else second_head.next
while cur1 and cur2:
if cur1.val != cur2.val:
return False
cur1, cur2 = cur1.next, cur2.next
return True | palindrome-linked-list | Python || O(1) space || detailed explanation ✅ | wilspi | 1 | 45 | palindrome linked list | 234 | 0.496 | Easy | 4,362 |
https://leetcode.com/problems/palindrome-linked-list/discuss/2466983/Use-a-List-!-oror-Python | class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
#list to store the values.
l = []
while head:
l.append(head.val)
head = head.next
#return the result of checking current obtained list with its reverse
return l==l[::-1] | palindrome-linked-list | Use a List ! || Python | haminearyan | 1 | 28 | palindrome linked list | 234 | 0.496 | Easy | 4,363 |
https://leetcode.com/problems/palindrome-linked-list/discuss/2431012/Clean-Efficient-Python3-or-Without-Cheating | class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
if not head or not head.next:
return True
cur, n = head, 0
while cur:
n += 1
cur = cur.next
last, cur = None, head
for _ in range(n // 2 + n % 2): # reverse first half pointers
mid = cur
cur = cur.next
mid.next = last
last = mid
left, right = last, cur
if n % 2:
left = left.next
while left and left.val == right.val: # try to go outwards on both sides, comparing values
left = left.next
right = right.next
return left is None | palindrome-linked-list | Clean, Efficient Python3 | Without Cheating | ryangrayson | 1 | 116 | palindrome linked list | 234 | 0.496 | Easy | 4,364 |
https://leetcode.com/problems/palindrome-linked-list/discuss/2428091/Help-me-out!!-Python!! | class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
list=[]
flag = 0
while head.val:
list.append(head.val)
head = head.next
for i in range(int(len(list)/2)):
if list[i] != list[-1 - i]:
flag = 1
if flag != 0:
return False
else:
return True | palindrome-linked-list | Help me out!! Python!! | sHadowSparK | 1 | 39 | palindrome linked list | 234 | 0.496 | Easy | 4,365 |
https://leetcode.com/problems/palindrome-linked-list/discuss/2428091/Help-me-out!!-Python!! | class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
list=[]
flag = 0
while head.next:
list.append(head.val)
head = head.next
list.append(head.val)
for i in range(int(len(list)/2)):
if list[i] != list[-1 - i]:
flag = 1
if flag != 0:
return False
else:
return True | palindrome-linked-list | Help me out!! Python!! | sHadowSparK | 1 | 39 | palindrome linked list | 234 | 0.496 | Easy | 4,366 |
https://leetcode.com/problems/palindrome-linked-list/discuss/2331575/Beginner-python-solution | class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
a = ''
while head != None:
a += str(head.val)
head = head.next
if a == a[::-1]:
return True
else:
return False | palindrome-linked-list | Beginner python solution | EbrahimMG | 1 | 132 | palindrome linked list | 234 | 0.496 | Easy | 4,367 |
https://leetcode.com/problems/palindrome-linked-list/discuss/1918940/Python-or-Explanation-or-Start-Mid-End-or-Doubly-Linked-List-or-Reverse | class Solution:
def isPalindrome(self, head):
start = mid = end = head
while end and end.next:
mid = mid.next
end.next.prev = end
if end.next.next: end.next.next.prev=end.next
end = end.next.next if end.next.next else end.next
while start != mid and end != mid:
if start.val != end.val: return False
start = start.next
end = end.prev
return start.val == end.val | palindrome-linked-list | Python | Explanation | Start, Mid, End | Doubly-Linked List | Reverse | domthedeveloper | 1 | 132 | palindrome linked list | 234 | 0.496 | Easy | 4,368 |
https://leetcode.com/problems/palindrome-linked-list/discuss/1918940/Python-or-Explanation-or-Start-Mid-End-or-Doubly-Linked-List-or-Reverse | class Solution:
def isPalindrome(self, head):
start = mid = end = head
while end and end.next:
mid = mid.next
end = end.next.next if end.next.next else end.next
mid_original = prev = mid
while mid:
next = mid.next
mid.next = prev
prev = mid
mid = next
mid, end = mid_original, prev
while start != mid and end != mid:
if start.val != end.val: return False
start = start.next
end = end.next
return start.val == end.val | palindrome-linked-list | Python | Explanation | Start, Mid, End | Doubly-Linked List | Reverse | domthedeveloper | 1 | 132 | palindrome linked list | 234 | 0.496 | Easy | 4,369 |
https://leetcode.com/problems/palindrome-linked-list/discuss/1907721/Python-Short-Recursive-solution | class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
self.left = ListNode(-1,head)
def isPal(head):
if not head: return True
right = isPal(head.next)
self.left = self.left.next
return right and self.left.val == head.val
return isPal(head) | palindrome-linked-list | ✅ Python Short Recursive solution | dhananjay79 | 1 | 206 | palindrome linked list | 234 | 0.496 | Easy | 4,370 |
https://leetcode.com/problems/palindrome-linked-list/discuss/1890784/Python3-87.98-or-Mid-Reverse-and-Merge-LinkedList-O(1)-Space-or-Clear-Implementation | class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
def mid(n):
s = f = n
while f.next and f.next.next:
s = s.next
f = f.next.next
return s
def rev(n):
prev = None
while n:
tmp = n.next
n.next = prev
prev = n
n = tmp
return prev
def display(n):
l = []
while n:
l.append(n.val)
n = n.next
print(l)
end = mid(head)
tail = rev(end.next)
cur = head
# display(cur)
# display(tail)
while cur and tail:
if cur.val != tail.val:
return False
if cur == end:
break
cur = cur.next
tail = tail.next
return True | palindrome-linked-list | Python3 87.98% | Mid, Reverse, and Merge LinkedList O(1) Space | Clear Implementation | doneowth | 1 | 107 | palindrome linked list | 234 | 0.496 | Easy | 4,371 |
https://leetcode.com/problems/palindrome-linked-list/discuss/1744982/Python3-or-Two-Approaches | class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
vals=[]
itr=head
n=0
while itr:
vals.append(itr.val)
itr=itr.next
n+=1
for i in range(0,n//2):
if vals[i]!=vals[n-1-i]:
return False
return True | palindrome-linked-list | Python3 | Two Approaches | user9015Y | 1 | 101 | palindrome linked list | 234 | 0.496 | Easy | 4,372 |
https://leetcode.com/problems/palindrome-linked-list/discuss/1744982/Python3-or-Two-Approaches | class Solution:
def reverse(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
prev=None
curr=head
while curr:
temp=curr.next
curr.next=prev
prev=curr
curr=temp
return prev
def isPalindrome(self, head: Optional[ListNode]) -> bool:
if not head or not head.next:
return True
slow=fast=head
while fast and fast.next:
slow=slow.next
fast=fast.next.next
slow=self.reverse(slow)
itr=head
while slow:
if itr.val!=slow.val:
return False
itr=itr.next
slow=slow.next
return True | palindrome-linked-list | Python3 | Two Approaches | user9015Y | 1 | 101 | palindrome linked list | 234 | 0.496 | Easy | 4,373 |
https://leetcode.com/problems/palindrome-linked-list/discuss/1387106/Python3-99-O(1)-Space-O(n)-time.-One-Pass-Slow-Pointer-Fast-Pointer | class Solution:
def isPalindrome(self, head: ListNode) -> bool:
def reverse(node):
prev = None
curr = node
while curr:
tmp = curr.next
curr.next = prev
prev = curr
curr = tmp
return prev
def areEqual(node1, node2):
if not (node1 and node2):
return True
while node1 and node2:
if node1.val != node2.val:
return False
node1 = node1.next
node2 = node2.next
return not (node1 or node2)
prev = None
slow = fast = head
while fast and fast.next:
prev = slow
slow = slow.next
fast = fast.next.next
if fast:
slow = slow.next
# Severe connection
if prev:
prev.next = None
head = reverse(head)
return areEqual(head, slow) | palindrome-linked-list | [Python3] 99% O(1) Space O(n) time. One Pass Slow Pointer Fast Pointer | whitehatbuds | 1 | 383 | palindrome linked list | 234 | 0.496 | Easy | 4,374 |
https://leetcode.com/problems/palindrome-linked-list/discuss/2837572/python-oror-simple-solution-oror-o(1)-space | class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
slow = fast = head # slow (middle), fast node
i = 0 # counter for slow
# get middle node in linkedlist
while fast.next:
fast = fast.next
if (i % 2) == 1:
slow = slow.next
i += 1
# reverse second half
prev, iter = None, slow.next
while iter:
next = iter.next
iter.next = prev
prev = iter
iter = next
# connect halfs and set slow to start of second half
slow.next = prev
slow = slow.next
# see if first half matches second half
while slow and (head.val == slow.val):
head = head.next
slow = slow.next
# if slow reaches end, it is a palindrome
return not slow | palindrome-linked-list | python || simple solution || o(1) space | wduf | 0 | 3 | palindrome linked list | 234 | 0.496 | Easy | 4,375 |
https://leetcode.com/problems/palindrome-linked-list/discuss/2833672/O(1)-Space-solution-with-exactly-O(1N)-worst-case-speed-(at-most-exactly-1N-scan)-Python | class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
slow_node = head
fast_node = slow_node
prev_node = None
while fast_node is not None:
if fast_node.next is None:
# list is odd length (don't add another node to reversed 1st half list - the next node is the odd mid-point)
fast_node = fast_node.next
slow_node = slow_node.next
else:
# list is even length (add another node to reversed 1st half list)
fast_node = fast_node.next.next
temp_node = slow_node
slow_node = slow_node.next
temp_node.next = prev_node
prev_node = temp_node
# At this point prev_node points to the head of reversed 1st half of list and slow_node points to head of remaining half of list
while slow_node is not None:
if slow_node.val != prev_node.val:
return False
slow_node = slow_node.next
prev_node = prev_node.next
return True | palindrome-linked-list | O(1) Space solution with exactly O(1N) worst case speed (at most exactly 1N scan) [Python] | user1923xl | 0 | 2 | palindrome linked list | 234 | 0.496 | Easy | 4,376 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/1394823/Explained-Easy-Iterative-Python-Solution | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
while True:
if root.val > p.val and root.val > q.val:
root = root.left
elif root.val < p.val and root.val < q.val:
root = root.right
else:
return root | lowest-common-ancestor-of-a-binary-search-tree | Explained Easy Iterative Python Solution | sevdariklejdi | 55 | 2,000 | lowest common ancestor of a binary search tree | 235 | 0.604 | Medium | 4,377 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/2504620/Very-Easy-oror-100-oror-Fully-Explained-oror-C%2B%2B-Java-Python-JS-C-Python3-oror-Iterative-and-Recursive | class Solution(object):
def lowestCommonAncestor(self, root, p, q):
if root:
# If the value of p node and the q node is greater than the value of root node...
if root.val > p.val and root.val > q.val:
return self.lowestCommonAncestor(root.left, p, q)
# If the value of p node and the q node is less than the value of root node...
elif root.val < p.val and root.val < q.val:
return self.lowestCommonAncestor(root.right, p, q)
else:
return root | lowest-common-ancestor-of-a-binary-search-tree | Very Easy || 100% || Fully Explained || C++, Java, Python, JS, C, Python3 || Iterative & Recursive | PratikSen07 | 7 | 500 | lowest common ancestor of a binary search tree | 235 | 0.604 | Medium | 4,378 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/2185308/Python3-simple-recursive-solution | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if p is None or q is None:
return None
if root == p or root == q:
return root
if (root.left == p and root.right ==q) or (root.right == p and root.left == q):
return root
if p.val < root.val and q.val < root.val:
return self.lowestCommonAncestor(root.left, p, q)
elif p.val > root.val and q.val > root.val:
return self.lowestCommonAncestor(root.right, p, q)
return root | lowest-common-ancestor-of-a-binary-search-tree | 📌 Python3 simple recursive solution | Dark_wolf_jss | 7 | 74 | lowest common ancestor of a binary search tree | 235 | 0.604 | Medium | 4,379 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/2704717/Python-Easy-Way-To-Find-Lowest-Common-Ancestor-of-a-Binary-Search-Tree-or-96-Faster | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
curr = root
while curr:
if p.val>curr.val and q.val>curr.val:
curr = curr.right
elif p.val<curr.val and q.val<curr.val:
curr = curr.left
else:
return curr | lowest-common-ancestor-of-a-binary-search-tree | ✔️ Python Easy Way To Find Lowest Common Ancestor of a Binary Search Tree | 96% Faster 🔥 | pniraj657 | 6 | 408 | lowest common ancestor of a binary search tree | 235 | 0.604 | Medium | 4,380 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/2234898/Python-solution-with-explanation | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
def helper(root):
if not root:
return None
else:
if(p.val>root.val and q.val>root.val):
return helper(root.right)
if(p.val<root.val and q.val<root.val):
return helper(root.left)
else:
return root
return helper(root) | lowest-common-ancestor-of-a-binary-search-tree | Python solution with explanation | palashbajpai214 | 3 | 145 | lowest common ancestor of a binary search tree | 235 | 0.604 | Medium | 4,381 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/2414480/Python-Elegant-and-Short-or-O(n)-time-or-DFS | class Solution:
"""
Time: O(n)
Memory: O(n)
"""
def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
if p.val < q.val:
return self._find_lca(root, p, q)
else:
return self._find_lca(root, q, p)
@classmethod
def _find_lca(cls, tree: TreeNode, lower: TreeNode, higher: TreeNode) -> TreeNode:
if tree.val == lower.val or tree.val == higher.val:
return tree
if lower.val < tree.val < higher.val:
return tree
if higher.val < tree.val:
return cls._find_lca(tree.left, lower, higher)
else:
return cls._find_lca(tree.right, lower, higher) | lowest-common-ancestor-of-a-binary-search-tree | Python Elegant & Short | O(n) time | DFS | Kyrylo-Ktl | 2 | 49 | lowest common ancestor of a binary search tree | 235 | 0.604 | Medium | 4,382 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/2253691/Python-Iterative-Solution-Explained-Time-O(N)-or-Space-O(1) | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
current = root
while current:
if current.val > p.val and current.val > q.val:
current = current.left
elif current.val < p.val and current.val < q.val:
current = current.right
else:
return current
return -1 | lowest-common-ancestor-of-a-binary-search-tree | [Python] Iterative Solution Explained - Time O(N) | Space O(1) | Symbolistic | 2 | 102 | lowest common ancestor of a binary search tree | 235 | 0.604 | Medium | 4,383 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/1782697/Python3-solution-short-and-easy | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if p.val<root.val and q.val<root.val:
return self.lowestCommonAncestor(root.left,p,q)
if p.val>root.val and q.val>root.val:
return self.lowestCommonAncestor(root.right,p,q)
return root | lowest-common-ancestor-of-a-binary-search-tree | Python3 solution short and easy | Karna61814 | 2 | 93 | lowest common ancestor of a binary search tree | 235 | 0.604 | Medium | 4,384 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/1593528/Python-3-easy-recursive-solution | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
# if root is in between p and q
if (p.val <= root.val <= q.val) or (q.val <= root.val <= p.val):
return root
# if p and q are to the left of root
if root.val > p.val:
return self.lowestCommonAncestor(root.left, p, q)
# if p and q are the right of root
return self.lowestCommonAncestor(root.right, p, q) | lowest-common-ancestor-of-a-binary-search-tree | Python 3 easy recursive solution | dereky4 | 2 | 309 | lowest common ancestor of a binary search tree | 235 | 0.604 | Medium | 4,385 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/2413700/Use-nature-of-Binary-Search-Tree | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
p_val, q_val = p.val, q.val
while root:
val = root.val
if val > max(p_val, q_val):
root = root.left
elif val < min(p_val, q_val):
root = root.right
else:
return root | lowest-common-ancestor-of-a-binary-search-tree | Use nature of Binary Search Tree | 996-YYDS | 1 | 24 | lowest common ancestor of a binary search tree | 235 | 0.604 | Medium | 4,386 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/2262110/Python-3lines-with-O(1) | class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
node = root
while node:
if node.val<p.val and node.val<q.val:
node = node.right
elif node.val>p.val and node.val>q.val:
node = node.left
else:
return node | lowest-common-ancestor-of-a-binary-search-tree | Python 3lines with O(1) | Abhi_009 | 1 | 108 | lowest common ancestor of a binary search tree | 235 | 0.604 | Medium | 4,387 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/1773620/Very-easy-solution-using-Js-%2B-Python3 | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
cur = root
while cur :
if p.val < cur.val and q.val < cur.val :
cur = cur.left
elif p.val > cur.val and q.val > cur.val :
cur = cur.right
else :
return cur | lowest-common-ancestor-of-a-binary-search-tree | Very easy solution using - Js + Python3 | shakilbabu | 1 | 106 | lowest common ancestor of a binary search tree | 235 | 0.604 | Medium | 4,388 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/1515659/Python3-simple-solution | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode'):
while True:
if p.val > root.val and q.val > root.val:
root = root.right
elif p.val < root.val and q.val < root.val:
root = root.left
else:
return root | lowest-common-ancestor-of-a-binary-search-tree | Python3 simple solution | EklavyaJoshi | 1 | 81 | lowest common ancestor of a binary search tree | 235 | 0.604 | Medium | 4,389 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/1354851/Easy-Fast-Iterative-Python-Solution-(Faster-than-98) | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode'):
while True:
if p.val > root.val and q.val > root.val:
root = root.right
elif p.val < root.val and q.val < root.val:
root = root.left
else:
return root | lowest-common-ancestor-of-a-binary-search-tree | Easy, Fast Iterative Python Solution (Faster than 98%) | the_sky_high | 1 | 97 | lowest common ancestor of a binary search tree | 235 | 0.604 | Medium | 4,390 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/2732281/striver-approach-5-liner | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root: return None
curr = root.val
if curr < p.val and curr < q.val: return self.lowestCommonAncestor(root.right, p, q)
if curr > p.val and curr > q.val: return self.lowestCommonAncestor(root.left, p, q)
return root | lowest-common-ancestor-of-a-binary-search-tree | striver approach 5 liner | hacktheirlives | 0 | 3 | lowest common ancestor of a binary search tree | 235 | 0.604 | Medium | 4,391 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/2721691/D-Clean-Python-Solution | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if p.val > q.val:
p, q = q, p # making sure that q will be the upper limit
def helper(root):
if root == None:
return None
if p.val <= root.val <= q.val: # return first root that falls into this range because that will be LCA.
return root
if root.val < p.val:
return helper(root.right)
if root.val > q.val:
return helper(root.left)
return helper(root) | lowest-common-ancestor-of-a-binary-search-tree | ;D Clean Python Solution | user1813H | 0 | 5 | lowest common ancestor of a binary search tree | 235 | 0.604 | Medium | 4,392 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/2589657/Python-Two-Iterative-Solutionsoror-O(N)-O(1)-oror-Beats-91-Time-Complexity-96-Space | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
curr = root
while True:
if curr.val < q.val and curr.val < p.val:
curr = curr.right
elif curr.val > q.val and curr.val > p.val:
curr = curr.left
else:
return curr | lowest-common-ancestor-of-a-binary-search-tree | Python Two Iterative Solutions|| O(N) O(1) || Beats 91% Time Complexity 96% Space | ChristianK | 0 | 46 | lowest common ancestor of a binary search tree | 235 | 0.604 | Medium | 4,393 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/2553666/python-short-solution-dfs | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
d,d2,stk={},{},[[root,[]]]
while stk:
temp=stk.pop()
d2[temp[0].val]=temp[0]
d[temp[0].val]=[*temp[1],temp[0].val]
if temp[0].left:
stk.append([temp[0].left,temp[1]+[temp[0].val]])
if temp[0].right:
stk.append([temp[0].right,temp[1]+[temp[0].val]])
r=min(len(d[p.val])-1,len(d[q.val])-1)
for i in range(r,-1,-1):
if d[q.val][i]==d[p.val][i]:
return d2[d[p.val][i]] | lowest-common-ancestor-of-a-binary-search-tree | python short solution dfs | benon | 0 | 48 | lowest common ancestor of a binary search tree | 235 | 0.604 | Medium | 4,394 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/2517464/Python-Easiest | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
curr = root
while curr:
if p.val > curr.val and q.val > curr.val:
curr = curr.right
elif p.val < curr.val and q.val < curr.val:
curr = curr.left
else:
return curr | lowest-common-ancestor-of-a-binary-search-tree | Python Easiest ✅ | Khacker | 0 | 32 | lowest common ancestor of a binary search tree | 235 | 0.604 | Medium | 4,395 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/2414680/Python-or-Easy-solution | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
answer = None
def traverse(node):
nonlocal answer
if node is None:
return
if q.val <= node.val <= p.val or p.val <= node.val <= q.val:
answer = node
return
if node.val <= p.val and node.val <= q.val:
traverse(node.right)
elif node.val >= p.val and node.val >= q.val:
traverse(node.left)
traverse(root)
return answer | lowest-common-ancestor-of-a-binary-search-tree | Python | Easy solution | pivovar3al | 0 | 9 | lowest common ancestor of a binary search tree | 235 | 0.604 | Medium | 4,396 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/2413533/Python-while-loop | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if p.val > q.val:
p, q = q, p
while True:
if root.val < p.val:
root = root.right
elif root.val > q.val:
root = root.left
else:
return root | lowest-common-ancestor-of-a-binary-search-tree | Python, while loop | blue_sky5 | 0 | 8 | lowest common ancestor of a binary search tree | 235 | 0.604 | Medium | 4,397 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/2413515/Python-3-Easy-Solution-with-Time-Complexity%3A-O(logn)-Space-Complexity%3A-O(1) | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
cur =root
while cur:
if p.val > cur.val and q.val>cur.val:
cur=cur.right
elif p.val<cur.val and q.val<cur.val:
cur=cur.left
else:
return cur | lowest-common-ancestor-of-a-binary-search-tree | Python 3 Easy Solution with Time Complexity: O(logn) Space Complexity: O(1) | WhiteBeardPirate | 0 | 2 | lowest common ancestor of a binary search tree | 235 | 0.604 | Medium | 4,398 |
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2539410/python3-simple-Solution | class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root==None or root.val==p.val or root.val==q.val:
return root
left=self.lowestCommonAncestor(root.left,p,q)
right=self.lowestCommonAncestor(root.right,p,q)
if left!=None and right!=None:
return root
elif left!=None:
return left
else:
return right | lowest-common-ancestor-of-a-binary-tree | python3 simple Solution | pranjalmishra334 | 4 | 251 | lowest common ancestor of a binary tree | 236 | 0.581 | Medium | 4,399 |
Subsets and Splits