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-three/discuss/1869568/Python-Clean-and-Simple!-Multiple-Solutions | class Solution:
def isPowerOfThree(self, n):
return n > 0 and 3**19 % n == 0 | power-of-three | Python - Clean and Simple! Multiple Solutions | domthedeveloper | 2 | 210 | power of three | 326 | 0.453 | Easy | 5,600 |
https://leetcode.com/problems/power-of-three/discuss/1869568/Python-Clean-and-Simple!-Multiple-Solutions | class Solution:
def isPowerOfThree(self, n):
return n > 0 and 3**int(log(2**31-1,3)) % n == 0 | power-of-three | Python - Clean and Simple! Multiple Solutions | domthedeveloper | 2 | 210 | power of three | 326 | 0.453 | Easy | 5,601 |
https://leetcode.com/problems/power-of-three/discuss/1189408/Two-Python-Solutions.-O(log(n))-and-O(1) | class Solution:
def isPowerOfThree(self, n: int) -> bool:
while n>1:
if n%3 == 0:
n /= 3
else:
break
if n == 1:
return True
return False | power-of-three | Two Python Solutions. O(log(n)) and O(1) | fast_typer | 2 | 468 | power of three | 326 | 0.453 | Easy | 5,602 |
https://leetcode.com/problems/power-of-three/discuss/794980/Simple-python-solution | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n==0:
return False
if n==3 or n==1:
return True
i=3
while(i<n):
i=i*3
if i==n:
return True
else:
return False | power-of-three | Simple python solution | karygauss03 | 2 | 341 | power of three | 326 | 0.453 | Easy | 5,603 |
https://leetcode.com/problems/power-of-three/discuss/2643081/python | class Solution:
def isPowerOfThree(self, n: int) -> bool:
def helper(i):
if i < 1:
return False
if i == 1:
return True
if i % 3 != 0:
return False
return helper(i//3)
return helper(n) | power-of-three | python | zoey513 | 1 | 20 | power of three | 326 | 0.453 | Easy | 5,604 |
https://leetcode.com/problems/power-of-three/discuss/2494837/C%2B%2BJavaPython-Easy-O(LogN)-Solution-with-optimized-solution | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n<=0:
return False
while n!=1:
if n%3!=0:
return False
n=n/3
return True | power-of-three | C++/Java/Python Easy O(LogN) Solution with optimized solution | arpit3043 | 1 | 178 | power of three | 326 | 0.453 | Easy | 5,605 |
https://leetcode.com/problems/power-of-three/discuss/2471435/Python-Simple-Python-Solution | class Solution:
def isPowerOfThree(self, n: int) -> bool:
for i in range(n+1):
if 3**i==n:
return True
if 3**i>n:
return False
return False | power-of-three | [ Python ] β
β
Simple Python Solution π₯³βπ | ASHOK_KUMAR_MEGHVANSHI | 1 | 108 | power of three | 326 | 0.453 | Easy | 5,606 |
https://leetcode.com/problems/power-of-three/discuss/2471435/Python-Simple-Python-Solution | class Solution:
def isPowerOfThree(self, n: int) -> bool:
power = 0
number = 3
while True:
num = number**power
if num == n:
return True
if num > n:
return False
else:
power = power + 1
return False | power-of-three | [ Python ] β
β
Simple Python Solution π₯³βπ | ASHOK_KUMAR_MEGHVANSHI | 1 | 108 | power of three | 326 | 0.453 | Easy | 5,607 |
https://leetcode.com/problems/power-of-three/discuss/2471024/python3-or-easy-or-one-liner | class Solution:
def isPowerOfThree(self, n: int) -> bool:
return False if n<=0 or n>1162261467 else 1162261467%n==0 | power-of-three | python3 | easy | one liner | H-R-S | 1 | 61 | power of three | 326 | 0.453 | Easy | 5,608 |
https://leetcode.com/problems/power-of-three/discuss/2279966/Recursion | class Solution:
def isPowerOfThree(self, n: int) -> bool:
def powerofthree(n , x):
if(3**x == n):
return True
if(3**x > n):
return False
return powerofthree(n , x+1)
return powerofthree(n , 0) | power-of-three | Recursion | shingnapure_shilpa17 | 1 | 38 | power of three | 326 | 0.453 | Easy | 5,609 |
https://leetcode.com/problems/power-of-three/discuss/1869734/Python-easy-solution | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n < 1:return False
while (n%3 == 0):
n/= 3
return n==1 | power-of-three | Python easy solution | tansam | 1 | 167 | power of three | 326 | 0.453 | Easy | 5,610 |
https://leetcode.com/problems/power-of-three/discuss/1338819/Simple-Python-Solution-for-%22Power-of-Three%22 | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if (n == 0):
return False
while (n != 1):
if (n % 3 != 0):
return False
n = n // 3
return True | power-of-three | Simple Python Solution for "Power of Three" | sakshikhandare2527 | 1 | 387 | power of three | 326 | 0.453 | Easy | 5,611 |
https://leetcode.com/problems/power-of-three/discuss/826570/Python-O(log(logn))-solution | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n <= 0:
return False
while n % 3 == 0:
sr = sqrt(n)
if (sr - int(sr)) == 0:
n = sr
else:
n = n / 3
return n == 1 | power-of-three | Python O(log(logn)) solution | abodhare | 1 | 155 | power of three | 326 | 0.453 | Easy | 5,612 |
https://leetcode.com/problems/power-of-three/discuss/2843869/python-oror-simple-solution-oror-3-lines | class Solution:
def isPowerOfThree(self, n: int) -> bool:
# n not 0 and n is a multiple of 3
while n and not n % 3:
n /= 3
return n == 1 | power-of-three | python || simple solution || 3 lines | wduf | 0 | 1 | power of three | 326 | 0.453 | Easy | 5,613 |
https://leetcode.com/problems/power-of-three/discuss/2829341/Python-simple-and-easy-understanding-solution | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n is 0:
return False
while True:
if n == 1:
return True
if n % 3 != 0:
return False
n //= 3 | power-of-three | Python simple and easy-understanding solution | yutoun | 0 | 2 | power of three | 326 | 0.453 | Easy | 5,614 |
https://leetcode.com/problems/power-of-three/discuss/2791079/pythonic-way-math-solution | class Solution:
def isPowerOfThree(self, n: int) -> bool:
while n > 2:
if n % 3 >0:
return False
n = n/3
return n ==1 | power-of-three | pythonic way math solution | radhikapadia31 | 0 | 1 | power of three | 326 | 0.453 | Easy | 5,615 |
https://leetcode.com/problems/power-of-three/discuss/2755491/easy-solution!!!! | class Solution:
def isPowerOfThree(self, n: int) -> bool:
while n % 3 == 0 and n != 0:
n /= 3
if n == 1: return True
return False | power-of-three | easy solution!!!! | sanjeevpathak | 0 | 3 | power of three | 326 | 0.453 | Easy | 5,616 |
https://leetcode.com/problems/power-of-three/discuss/2738758/Simple-Python3-Solution | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n == 0:
return False
while(n != 1):
if (n%3 != 0):
return False
n = n // 3
return True | power-of-three | Simple Python3 Solution | dnvavinash | 0 | 7 | power of three | 326 | 0.453 | Easy | 5,617 |
https://leetcode.com/problems/power-of-three/discuss/2737595/No-Loops!-No-Recursion!-Absolutely-do-not-run-this-in-production! | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n <= 0:
return False
e = 0.000000000001
x = log(n, 3)
return abs(x - round(x)) < e | power-of-three | No Loops! No Recursion! Absolutely do not run this in production! | ThatTallProgrammer | 0 | 7 | power of three | 326 | 0.453 | Easy | 5,618 |
https://leetcode.com/problems/power-of-three/discuss/2729591/easy-way | class Solution:
def isPowerOfThree(self, n: int) -> bool:
while n%3==0 and n!=0:
n /= 3
if n==1:
return True
else:
return False | power-of-three | easy way | sindhu_300 | 0 | 6 | power of three | 326 | 0.453 | Easy | 5,619 |
https://leetcode.com/problems/power-of-three/discuss/2716074/Fast-and-Easy-Solution | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n <= 0:
return False
if n == 1:
return True
curr = 1
while curr < n:
curr = curr * 3
if curr == n:
return True
return False | power-of-three | Fast and Easy Solution | user6770yv | 0 | 6 | power of three | 326 | 0.453 | Easy | 5,620 |
https://leetcode.com/problems/power-of-three/discuss/2682169/Python-Solution | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n==1:
return True
if n==0:
return False
while n != 1:
if n%3 == 0:
n = n /3
else:
return False
return True | power-of-three | Python Solution | Sheeza | 0 | 2 | power of three | 326 | 0.453 | Easy | 5,621 |
https://leetcode.com/problems/power-of-three/discuss/2662387/easy-python-solution-or-Recursion | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n == 0: return False
if n == 1: return True
if n % 3 == 0:
return self.isPowerOfThree(n/3)
return False | power-of-three | easy python solution | Recursion | codeSheep_01 | 0 | 20 | power of three | 326 | 0.453 | Easy | 5,622 |
https://leetcode.com/problems/power-of-three/discuss/2614099/Python-Solution-Interview-Approach | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n<=0:
return False
while n>1:
if n%3!=0: return False
n//=3
return True | power-of-three | [Python Solution] Interview Approach | utsa_gupta | 0 | 44 | power of three | 326 | 0.453 | Easy | 5,623 |
https://leetcode.com/problems/power-of-three/discuss/2608024/Python3-Time%3A-112-ms-(73.28)-Space%3A-13.8-MB-(96.07) | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n == 1:
return True
if n <= 0:
return False
num = math.log(n, 3)
return num.is_integer() or round(num - int(num), 9) == 1 | power-of-three | Python3 Time: 112 ms (73.28%), Space: 13.8 MB (96.07%) | hnhtran | 0 | 10 | power of three | 326 | 0.453 | Easy | 5,624 |
https://leetcode.com/problems/power-of-three/discuss/2475508/Python-(Simple-and-Beginner-Friendly) | class Solution:
def isPowerOfThree(self, n: int) -> bool:
for i in range(0, 32):
if 3**i == n:
return True
return False | power-of-three | Python (Simple and Beginner-Friendly) | vishvavariya | 0 | 17 | power of three | 326 | 0.453 | Easy | 5,625 |
https://leetcode.com/problems/power-of-three/discuss/2474146/Python-Solution-or-Easy-Approach | class Solution:
def isPowerOfThree(self, n: int) -> bool:
while (n % 3 == 0 or n == 1) and n != 0:
if n == 1:
return True
n = n // 3
return False | power-of-three | Python Solution | Easy Approach | cyber_kazakh | 0 | 28 | power of three | 326 | 0.453 | Easy | 5,626 |
https://leetcode.com/problems/power-of-three/discuss/2472654/recursion-%2B-iterative-%3A-very-simple-four-lines-of-python-code | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if(n == 1): return True
if(n <= 0): return False
if(n%3): return False
return self.isPowerOfThree(n/3)
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if(n == 1): return True
if(n <= 0): return False
while(n):
if(n%3 !=0):
return False
return True | power-of-three | recursion + iterative : very simple four lines of python code | rajitkumarchauhan99 | 0 | 14 | power of three | 326 | 0.453 | Easy | 5,627 |
https://leetcode.com/problems/power-of-three/discuss/2472482/Python3-or-90-faster-or-recursion-or-assert | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n in (1, 3):
return True
else:
if n % 3 == 0 and n != 0:
return self.isPowerOfThree(n / 3)
else:
return False
# test1, test2, test3 = 27, 0, 9
# test4, test5, test6 = -27, 1, -3
# assert Solution().isPowerOfThree(test1) == True
# assert Solution().isPowerOfThree(test2) == False
# assert Solution().isPowerOfThree(test3) == True
# assert Solution().isPowerOfThree(test4) == False
# assert Solution().isPowerOfThree(test5) == True
# assert Solution().isPowerOfThree(test6) == False | power-of-three | Python3 | 90% faster | recursion | assert | Sergei_Gusev | 0 | 5 | power of three | 326 | 0.453 | Easy | 5,628 |
https://leetcode.com/problems/power-of-three/discuss/2471838/Simple-iterative-solution-neat-and-clean!! | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n == 0:
return False
while n != 1:
if n%3 != 0:
return False
n = n / 3
return True | power-of-three | Simple iterative solution neat and clean!! | __Asrar | 0 | 13 | power of three | 326 | 0.453 | Easy | 5,629 |
https://leetcode.com/problems/power-of-three/discuss/2471830/Python3-Solution-with-using-loop | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n <= 0:
return False
while n % 3 == 0:
n //= 3
return n == 1 | power-of-three | [Python3] Solution with using loop | maosipov11 | 0 | 5 | power of three | 326 | 0.453 | Easy | 5,630 |
https://leetcode.com/problems/power-of-three/discuss/2471442/Python-3-Solution-94ms-(85) | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if(n == 0) :
return False
num = n
while num != 1:
num = num / 3
intnum = math.floor(num)
if(num != intnum):
return
if(num == 1):
return True;
else :
return False | power-of-three | Python 3 Solution 94ms (85%) | tanmay656565 | 0 | 5 | power of three | 326 | 0.453 | Easy | 5,631 |
https://leetcode.com/problems/power-of-three/discuss/2471353/Python-Recursion-O(logn)-time-O(logn)-space. | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n == 1:
return True
if n < 1:
return False
return self.isPowerOfThree(n/3) | power-of-three | Python Recursion, O(logn) time, O(logn) space. | OsamaRakanAlMraikhat | 0 | 9 | power of three | 326 | 0.453 | Easy | 5,632 |
https://leetcode.com/problems/power-of-three/discuss/2470884/Python-Simple-and-Easy-Solution | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n < 1:
return False
while n % 3 == 0:
n /= 3
return n == 1 | power-of-three | Python - Simple and Easy Solution | dayaniravi123 | 0 | 17 | power of three | 326 | 0.453 | Easy | 5,633 |
https://leetcode.com/problems/power-of-three/discuss/2333687/Runtime%3A-84-ms-faster-than-92.07-of-Python3 | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n == 1: return True
count = 1
while(count<n):
count = count * 3
return count == n | power-of-three | Runtime: 84 ms, faster than 92.07% of Python3 | amit0693 | 0 | 84 | power of three | 326 | 0.453 | Easy | 5,634 |
https://leetcode.com/problems/power-of-three/discuss/1949561/Easy-Python-Solution | class Solution:
def isPowerOfThree(self, n: int) -> bool:
while n >= 3:
if n % 3 != 0:
return False
n = n / 3
return n == 1 | power-of-three | Easy Python Solution | westkosing | 0 | 216 | power of three | 326 | 0.453 | Easy | 5,635 |
https://leetcode.com/problems/power-of-three/discuss/1760324/Python-Recursion-Easy | class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 0:
return False
if n == 1:
return True
else:
if n %3==0:
k = n/3
return self.isPowerOfThree(k)
return False | power-of-three | Python Recursion Easy | junaidoxford59 | 0 | 103 | power of three | 326 | 0.453 | Easy | 5,636 |
https://leetcode.com/problems/power-of-three/discuss/1754914/Beginners-Pytho-Solution | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n<1:
return False
for i in range(0,n):
print(3**i)
if 3**i > n:
return False
if 3**i==n:
return True | power-of-three | Beginners Pytho Solution | sangam92 | 0 | 65 | power of three | 326 | 0.453 | Easy | 5,637 |
https://leetcode.com/problems/power-of-three/discuss/1638420/Python-Easy-Solution-or-Two-Approaches | class Solution:
def isPowerOfThree(self, n: int) -> bool:
# Time - O(n)
if n == 0:
return False
if n == 3 or n == 1:
return True
i = 3
while i < n:
i *= 3
return i == n
# Time - O(1)
# (3**19): Highest Power of 3!
return n > 0 and (3**19) % n == 0 | power-of-three | Python Easy Solution | Two Approaches β | leet_satyam | 0 | 228 | power of three | 326 | 0.453 | Easy | 5,638 |
https://leetcode.com/problems/power-of-three/discuss/1554711/Python3-Solution-or-1-line-answer | class Solution:
def isPowerOfThree(self, n: int) -> bool:
return n > 0 and 1162261467 % n == 0 | power-of-three | Python3 Solution | 1 line answer | satyam2001 | 0 | 192 | power of three | 326 | 0.453 | Easy | 5,639 |
https://leetcode.com/problems/power-of-three/discuss/1554711/Python3-Solution-or-1-line-answer | class Solution:
def isPowerOfThree(self, n: int) -> bool:
return n == 1 or n != 0 and n%3 == 0 and self.isPowerOfThree(n//3) | power-of-three | Python3 Solution | 1 line answer | satyam2001 | 0 | 192 | power of three | 326 | 0.453 | Easy | 5,640 |
https://leetcode.com/problems/power-of-three/discuss/1316979/Easy-Solution_python3-(faster-than-98) | class Solution:
def isPowerOfThree(self, n: int) -> bool:
# Dealing special case: 1.
if n == 1:
return True
# If n is an odd, it is not a number that is power of three.
# Also, eliminating those number did not have any factor of 3.
elif n % 2 == 0 or n % 3 != 0:
return False
else:
return power_of_three(n)
def power_of_three(n):
# Base Case
if n == 3:
return True
# If n is not devided by 3, it's not a power of three number.
elif n % 3:
return False
elif n < 3:
return False
# Recursive
else:
return power_of_three(n / 3) | power-of-three | Easy Solution_python3 (faster than 98%) | An_222 | 0 | 216 | power of three | 326 | 0.453 | Easy | 5,641 |
https://leetcode.com/problems/power-of-three/discuss/1245157/Python3-simple-solution-%22one-liner%22-using-math.log()-and-math.isclose() | class Solution:
def isPowerOfThree(self, n: int) -> bool:
return n > 0 and math.isclose(round(math.log(n, 3)), math.log(n, 3), rel_tol = 0.000000000000001) | power-of-three | Python3 simple solution "one-liner" using math.log() and math.isclose() | EklavyaJoshi | 0 | 112 | power of three | 326 | 0.453 | Easy | 5,642 |
https://leetcode.com/problems/count-of-range-sum/discuss/1195369/Python3-4-solutions | class Solution:
def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:
prefix = [0]
for x in nums: prefix.append(prefix[-1] + x)
def fn(lo, hi):
"""Return count of range sum between prefix[lo:hi]."""
if lo+1 >= hi: return 0
mid = lo + hi >> 1
ans = fn(lo, mid) + fn(mid, hi)
k = kk = mid
for i in range(lo, mid):
while k < hi and prefix[k] - prefix[i] < lower: k += 1
while kk < hi and prefix[kk] - prefix[i] <= upper: kk += 1
ans += kk - k
prefix[lo:hi] = sorted(prefix[lo:hi])
return ans
return fn(0, len(prefix)) | count-of-range-sum | [Python3] 4 solutions | ye15 | 8 | 459 | count of range sum | 327 | 0.361 | Hard | 5,643 |
https://leetcode.com/problems/count-of-range-sum/discuss/1195369/Python3-4-solutions | class Solution:
def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:
ans = prefix = 0
seen = [0]
for x in nums:
prefix += x
lo = bisect_left(seen, prefix - upper)
hi = bisect_left(seen, prefix - lower + 1)
ans += hi - lo
insort(seen, prefix)
return ans | count-of-range-sum | [Python3] 4 solutions | ye15 | 8 | 459 | count of range sum | 327 | 0.361 | Hard | 5,644 |
https://leetcode.com/problems/count-of-range-sum/discuss/2815466/Would-an-interviewer-accept-this | class Solution:
def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:
from sortedcontainers import SortedList
l = SortedList()
l.add(0)
total = 0
count = 0
for v in nums:
total += v
count += (l.bisect_right(total - lower) - l.bisect_left(total - upper))
l.add(total)
return count | count-of-range-sum | Would an interviewer accept this? | ariboi27 | 0 | 4 | count of range sum | 327 | 0.361 | Hard | 5,645 |
https://leetcode.com/problems/count-of-range-sum/discuss/2663449/O(n-logn)-in-Python-faster-than-more-than-80-easy-to-understand | class Solution:
def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:
# First get the cumulative list
# takes O(n)
accumulated = nums.copy()
for i in range(0, len(nums)):
if i != 0:
accumulated[i] = nums[i] + accumulated[i-1]
# sort the cumulative list
# we do this because it's easy for later operations
# takes O(n logn)
new_acc = sorted(accumulated)
result = 0
num = 0
# takes O(n)
for i in range(0, len(nums)):
# get how many subarrays are within the bound
# inside the loop, takes O(logn)
l = bisect_left(new_acc, lower)
r = bisect_right(new_acc, upper)
diff = r - l
result += diff
lower += nums[num]
upper += nums[num]
poped = bisect_left(new_acc, accumulated[num])
new_acc.pop(poped)
num += 1
# overall, takes O(n logn)
return result | count-of-range-sum | O(n logn) in Python faster than more than 80%, easy to understand | IamYoung | 0 | 23 | count of range sum | 327 | 0.361 | Hard | 5,646 |
https://leetcode.com/problems/count-of-range-sum/discuss/1407246/simple-python-solution-with-divide-and-conquer-approach | class Solution:
def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:
def find(l,r):
if l > r:
return 0
m = (l+r)//2
left = [0]
s = 0
for i in range(m-1,l-1,-1):
s += nums[i]
left.append(s)
right = [0]
s = 0
for i in range(m+1,r+1):
s += nums[i]
right.append(s)
right.sort()
ans = 0
for i in left:
ans += (bisect.bisect_right(right,upper-i-nums[m]) - bisect.bisect_left(right,lower-i-nums[m]))
return ans + find(l,m-1)+find(m+1,r)
return find(0, len(nums)-1) | count-of-range-sum | simple python solution with divide and conquer approach | sukhesai | 0 | 178 | count of range sum | 327 | 0.361 | Hard | 5,647 |
https://leetcode.com/problems/odd-even-linked-list/discuss/2458296/easy-approach-using-two-pointer-in-python-With-Comments-TC-%3A-O(N)-SC-%3A-O(1) | class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if(head is None or head.next is None):
return head
# assign odd = head(starting node of ODD)
# assign even = head.next(starting node of EVEN)
odd , even = head , head.next
Even = even # keep starting point of Even Node so later we will connect with Odd Node
while(odd.next and even.next):
odd.next = odd.next.next # Connect odd.next to odd Node
even.next = even.next.next # Connect even,next to Even Node
odd = odd.next # move odd
even = even.next # move even
odd.next = Even # now connect odd.next to starting point to Even list
return head | odd-even-linked-list | easy approach using two pointer in python With Comments [TC : O(N) SC : O(1)] | rajitkumarchauhan99 | 4 | 156 | odd even linked list | 328 | 0.603 | Medium | 5,648 |
https://leetcode.com/problems/odd-even-linked-list/discuss/1607890/Easiest-Approach-oror-Well-Coded-oror-92-faster | class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head is None or head.next is None:
return head
e,o = head,head.next
odd_head = o
while o!=None and o.next!=None:
e.next = o.next
e = e.next
o.next = e.next
o = o.next
e.next = odd_head
return head | odd-even-linked-list | ππ Easiest Approach || Well-Coded || 92% faster π | abhi9Rai | 2 | 162 | odd even linked list | 328 | 0.603 | Medium | 5,649 |
https://leetcode.com/problems/odd-even-linked-list/discuss/1151220/Simple-Python-3-Solution | class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
odd = ListNode()
even = ListNode()
p1 = odd
p2 = even
t = head
i = 1
while t:
if i % 2 != 0:
p1.next = t
p1 = p1.next
else:
p2.next = t
p2 = p2.next
i += 1
t = t.next
p2.next = None
p1.next = even.next
return odd.next | odd-even-linked-list | Simple Python 3 Solution | imbhuvnesh | 2 | 149 | odd even linked list | 328 | 0.603 | Medium | 5,650 |
https://leetcode.com/problems/odd-even-linked-list/discuss/1608696/Python3-CLEAN-CODE-0(n)-Explained | class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
headOdd, headEven = head, head.next
tailOdd, tailEven = headOdd, headEven
i = 3
cur = headEven.next
while cur:
if i%2:
tailOdd.next = cur
tailOdd = cur
else:
tailEven.next = cur
tailEven = cur
cur = cur.next
i += 1
tailEven.next = None # prevent cycle
tailOdd.next = headEven
return headOdd | odd-even-linked-list | βοΈ [Python3] CLEAN CODE, 0(n), Explained | artod | 1 | 58 | odd even linked list | 328 | 0.603 | Medium | 5,651 |
https://leetcode.com/problems/odd-even-linked-list/discuss/1448349/Python3-solution | class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return head
temp2 = head
c = 1
while temp2.next:
temp2 = temp2.next
c += 1
i = 0
previous = head
temp1 = head
while i < c:
if i % 2 != 0:
temp2.next = ListNode(temp1.val)
temp2 = temp2.next
previous.next = previous.next.next
previous = previous.next
temp1 = temp1.next
i += 1
return head | odd-even-linked-list | Python3 solution | EklavyaJoshi | 1 | 56 | odd even linked list | 328 | 0.603 | Medium | 5,652 |
https://leetcode.com/problems/odd-even-linked-list/discuss/1411973/fastest-solution-and-yet-quite-simple-both-in-c%2B%2B-and-python-with-and-without-counter | class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if not head:
return None
odd = head
evenHead = even = head.next
while even and even.next:
odd.next = even.next
odd = odd.next
even.next = odd.next
even = even.next
odd.next = evenHead
return head | odd-even-linked-list | fastest solution and yet quite simple both in c++ and python , with and without counter | sagarhparmar12345 | 1 | 97 | odd even linked list | 328 | 0.603 | Medium | 5,653 |
https://leetcode.com/problems/odd-even-linked-list/discuss/1411973/fastest-solution-and-yet-quite-simple-both-in-c%2B%2B-and-python-with-and-without-counter | class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if (not head or not head.next or not head.next.next):
return head
ans=head
pointer_start=head
pointer_tail=head.next
head=head.next.next
count=2
while head:
if count%2==0:
pointer_tail.next=head.next
head.next=pointer_start.next
pointer_start.next=head
pointer_start=head
head=pointer_tail
else:
pointer_tail=pointer_tail.next
count+=1
head=head.next
return ans | odd-even-linked-list | fastest solution and yet quite simple both in c++ and python , with and without counter | sagarhparmar12345 | 1 | 97 | odd even linked list | 328 | 0.603 | Medium | 5,654 |
https://leetcode.com/problems/odd-even-linked-list/discuss/341726/Python-3-solution-(linking-alternate-node) | class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if not head:return None
even=head.next
i=head
j=even
while i.next and j.next:
i.next=j.next
i=i.next
j.next=i.next
j=j.next
i.next=even
return head | odd-even-linked-list | Python 3 solution (linking alternate node) | ketan35 | 1 | 321 | odd even linked list | 328 | 0.603 | Medium | 5,655 |
https://leetcode.com/problems/odd-even-linked-list/discuss/2768795/python-solution | class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
even = None
pre = None
cur = head
if not head:
return None
nxt = head.next
index = 0
while cur:
if index == 1:
even = cur
nxt = cur.next
if nxt == None:
if index % 2 == 0:
cur.next = even
else:
pre.next = even
else:
cur.next = nxt.next
pre = cur
cur = nxt
index += 1
return head | odd-even-linked-list | python solution | maomao1010 | 0 | 1 | odd even linked list | 328 | 0.603 | Medium | 5,656 |
https://leetcode.com/problems/odd-even-linked-list/discuss/2757908/Python-O(1)-space | class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head is None or head.next is None:
return head
lastOdd = head
lastEven = head.next
while lastEven is not None and lastEven.next is not None:
nextOdd = lastEven.next
nextEven = nextOdd.next
firstEven = lastOdd.next
lastOdd.next = nextOdd
nextOdd.next = firstEven
lastEven.next = nextEven
lastOdd = nextOdd
lastEven = nextEven
return head | odd-even-linked-list | Python O(1) space | jamaxack | 0 | 2 | odd even linked list | 328 | 0.603 | Medium | 5,657 |
https://leetcode.com/problems/odd-even-linked-list/discuss/2626446/python3-constant-space-and-linear-time | class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return None
odd=head
even=head.next
while head.next:
temp=head.next
head.next=head.next.next
head=temp
odd_root=odd
while odd.next:
odd=odd.next
odd.next=even
return odd_root | odd-even-linked-list | python3 constant space and linear time | benon | 0 | 12 | odd even linked list | 328 | 0.603 | Medium | 5,658 |
https://leetcode.com/problems/odd-even-linked-list/discuss/2524322/Python-Nice-Clean-Easy-to-Understand | class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head: return
odd = head
even = head.next
evenHead = even
while even and even.next:
odd.next = odd.next.next
even.next = even.next.next
odd = odd.next
even = even.next
odd.next = evenHead
return head | odd-even-linked-list | Python Nice Clean Easy to Understand | soumyadexter7 | 0 | 58 | odd even linked list | 328 | 0.603 | Medium | 5,659 |
https://leetcode.com/problems/odd-even-linked-list/discuss/2397872/Python-or-Two-pointers-or-90-faster-or-Easy-to-unserstand | class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
slow, fast = head, head.next
while fast and fast.next:
temp = fast.next
fast.next = temp.next # (1)
temp.next = slow.next # (2)
slow.next = temp # (3)
slow = slow.next
fast = fast.next
return head | odd-even-linked-list | Python | Two pointers | 90% faster | Easy to unserstand | pcdean2000 | 0 | 39 | odd even linked list | 328 | 0.603 | Medium | 5,660 |
https://leetcode.com/problems/odd-even-linked-list/discuss/1983984/Python-oror-Intuitive-Solution-(Iterative) | class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
odd, even, curr= ListNode(0), ListNode(0), head
rootEven, rootOdd, idx = even, odd, 1
while curr:
if idx%2:
odd.next = curr
odd = odd.next
else:
even.next = curr
even = even.next
idx += 1
curr = curr.next
rootOdd, rootEven = rootOdd.next, rootEven.next
even.next, odd.next = None, rootEven
return rootOdd | odd-even-linked-list | Python || Intuitive Solution (Iterative) | morpheusdurden | 0 | 56 | odd even linked list | 328 | 0.603 | Medium | 5,661 |
https://leetcode.com/problems/odd-even-linked-list/discuss/1946076/Python3-Simple-Faster-than-92 | class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return head
else:
odd = head
even = odd.next
ehead = even
while even and even.next:
odd.next = odd.next.next
even.next = even.next.next
odd = odd.next
even = even.next
odd.next = ehead
return head | odd-even-linked-list | [Python3] Simple, Faster than 92% | natscripts | 0 | 46 | odd even linked list | 328 | 0.603 | Medium | 5,662 |
https://leetcode.com/problems/odd-even-linked-list/discuss/1607690/Compact-(5-Lines)-Python3-Solution | class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
current, i= [seven:=ListNode(), sodd:=ListNode()], 0
while head:
current[i].next, current[i], head, i = head, head, head.next, i^1
current[0].next, current[1].next= sodd.next, None
return seven.next | odd-even-linked-list | Compact (5 Lines) Python3 Solution | pknoe3lh | 0 | 11 | odd even linked list | 328 | 0.603 | Medium | 5,663 |
https://leetcode.com/problems/odd-even-linked-list/discuss/1607663/One-pass-96-speed | class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if head and head.next and head.next.next:
head_even = head.next
odd = head
even = head_even
while even and even.next:
odd.next = even.next
odd = odd.next
even.next = odd.next
even = even.next
odd.next = head_even
return head | odd-even-linked-list | One pass, 96% speed | EvgenySH | 0 | 40 | odd even linked list | 328 | 0.603 | Medium | 5,664 |
https://leetcode.com/problems/odd-even-linked-list/discuss/1607367/Python3-O(n)-time-O(1)-space-solution | class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if head == None or head.next == None:
return head
odd_begin = head
even_begin = head.next
while head.next != None and head.next.next != None:
tmp = head.next
head.next = head.next.next
tmp.next = head.next.next
head = head.next
head.next = even_begin
return odd_begin | odd-even-linked-list | [Python3] O(n) time, O(1) space solution | maosipov11 | 0 | 12 | odd even linked list | 328 | 0.603 | Medium | 5,665 |
https://leetcode.com/problems/odd-even-linked-list/discuss/1113173/Python-or-easy-to-understand | class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if not head:
return None
odd = head
even = head.next
evenhead = even
while even and even.next:
odd.next = even.next
odd = odd.next
even.next = odd.next
even = even.next
odd.next = evenhead
return head | odd-even-linked-list | Python | easy to understand | timotheeechalamet | 0 | 132 | odd even linked list | 328 | 0.603 | Medium | 5,666 |
https://leetcode.com/problems/odd-even-linked-list/discuss/1080552/python-beats-95-simple-code-2-pointer | class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if head==None or head.next==None:
return head
odd = head
even = head.next
x = even.next
while x:
temp = x
even.next = x.next
even = even.next
temp.next = odd.next
odd.next = temp
odd = odd.next
x= even.next if even else None
return head | odd-even-linked-list | python beats 95% simple code 2 pointer | abhishekm2106 | 0 | 255 | odd even linked list | 328 | 0.603 | Medium | 5,667 |
https://leetcode.com/problems/odd-even-linked-list/discuss/1056305/Python-solution-(32ms) | class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if not head: return head
p1 = head
p2 = p1.next
t = p2
while p1.next and p2.next:
p1.next = p2.next
p1 = p1.next
p2.next = p1.next
p2 = p2.next
p1.next = t
return head | odd-even-linked-list | Python solution (32ms) | kysr007 | 0 | 61 | odd even linked list | 328 | 0.603 | Medium | 5,668 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2052380/Python-DFS-with-Memoization-Beats-~90 | class Solution:
def longestIncreasingPath(self, grid: List[List[int]]) -> int:
m,n=len(grid),len(grid[0])
directions = [0, 1, 0, -1, 0] # four directions
@lru_cache(maxsize=None) # using python cache lib for memoization
def dfs(r,c):
ans=1
# iterating through all 4 directions
for i in range(4):
new_row,new_col=r+directions[i], c+directions[i+1] # calculating the new cell
# check if new cell is within the grid bounds and is an increasing sequence
if 0<=new_row<m and 0<=new_col<n and grid[new_row][new_col]>grid[r][c]:
ans = max(ans, dfs(new_row, new_col) + 1 ) # finding the max length of valid path from the current cell
return ans
return max(dfs(r,c) for r in range(m) for c in range(n)) | longest-increasing-path-in-a-matrix | Python DFS with Memoization Beats ~90% | constantine786 | 4 | 580 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,669 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2165003/Python-Solution-using-Memoization | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
row = len(matrix); col = len(matrix[0])
res = 0
memo = {}
directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]
def helper(i, j):
if (i,j) in memo: return memo[(i,j)]
path = 1
for move in directions:
r = i + move[0]
c = j + move[1]
if (0<=r<row and 0<=c<col and
matrix[r][c] != '#' and matrix[r][c] > matrix[i][j]):
tmp = matrix[i][j]
matrix[i][j] = '#'
path = max(path, helper(r, c) + 1)
matrix[i][j] = tmp
memo[(i,j)] = path
return memo[(i,j)]
for i in range(row):
for j in range(col):
res = max(res, helper(i, j))
return res
# Time: O(N^3)
# Space: O(N^2) | longest-increasing-path-in-a-matrix | [Python] Solution using Memoization | samirpaul1 | 3 | 108 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,670 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/1158379/Python3-top-down-dp | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
m, n = len(matrix), len(matrix[0]) # dimensions
@cache
def fn(i, j):
"""Return max increasing path starting from (i, j)."""
ans = 1
for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):
if 0 <= ii < m and 0 <= jj < n and matrix[i][j] < matrix[ii][jj]:
ans = max(ans, 1 + fn(ii, jj))
return ans
return max(fn(i, j) for i in range(m) for j in range(n)) | longest-increasing-path-in-a-matrix | [Python3] top-down dp | ye15 | 3 | 134 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,671 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/1158379/Python3-top-down-dp | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
m, n = len(matrix), len(matrix[0])
indeg = [[0]*n for _ in range(m)]
for i in range(m):
for j in range(n):
for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):
if 0 <= ii < m and 0 <= jj < n and matrix[i][j] < matrix[ii][jj]:
indeg[ii][jj] += 1
queue = deque([(i, j) for i in range(m) for j in range(n) if indeg[i][j] == 0])
ans = 0
while queue:
for _ in range(len(queue)):
i, j = queue.popleft()
for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):
if 0 <= ii < m and 0 <= jj < n and matrix[i][j] < matrix[ii][jj]:
indeg[ii][jj] -= 1
if indeg[ii][jj] == 0: queue.append((ii, jj))
ans += 1
return ans | longest-increasing-path-in-a-matrix | [Python3] top-down dp | ye15 | 3 | 134 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,672 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/1103556/Python-memoized-DFS | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
M, N = len(matrix), len(matrix[0])
MOVES = [(1,0), (0,1), (-1,0), (0,-1)]
@functools.cache
def dfs(i, j):
path_length = 0
for di, dj in MOVES:
ni, nj = i+di, j+dj
if 0<=ni<M and 0<=nj<N and matrix[ni][nj] > matrix[i][j]:
path_length = max(path_length, dfs(ni, nj))
return 1 + path_length
res = 0
for i in range(M):
for j in range(N):
res = max(res, dfs(i, j))
return res | longest-increasing-path-in-a-matrix | Python memoized DFS | mjgallag | 3 | 374 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,673 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/1716994/Easy-to-understand-Python-DP-memo-solution | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
def isValid(r,c):
return 0<=r<len(matrix) and 0<=c<len(matrix[0])
directions=[(1,0),(0,1),(-1,0),(0,-1)]
max_path=1
dp= [ [0 for _ in range(len(matrix[0]))] for __ in range(len(matrix))]
def helper(r,c):
if dp[r][c]:
return dp[r][c]
res=dp[r][c]
for nr,nc in directions:
nr,nc=r+nr,c+nc
if isValid(nr,nc) and matrix[nr][nc]>matrix[r][c]:
res=max( helper(nr,nc) + 1 , res )
dp[r][c]=res
return dp[r][c]
for r in range(len(matrix)):
for c in range(len(matrix[0])):
max_path=max(helper(r,c)+1,max_path)
return max_path | longest-increasing-path-in-a-matrix | Easy to understand Python π DP memo solution | InjySarhan | 2 | 148 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,674 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/1424541/Python-Clean | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
def dfs(row, col):
if (row, col) in visited: return visited[(row, col)]
length = 1
path.add((row, col))
for r, c in [(row-1, col), (row, col-1), (row, col+1), (row+1, col)]:
if r in range(M) and c in range(N) and matrix[r][c] < matrix[row][col] and (r, c) not in path:
length = max(dfs(r, c)+1, length)
path.remove((row, col))
visited[(row, col)] = length
return length
M, N = len(matrix), len(matrix[0])
path, visited = set(), {}
max_len = 1
for row in range(M):
for col in range(N):
max_len = max(dfs(row, col), max_len)
return max_len | longest-increasing-path-in-a-matrix | [Python] Clean | soma28 | 2 | 134 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,675 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2394648/python-DFS%2BDP | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
m = len(matrix)
n = len(matrix[0])
dp = [[0]*n for _ in range(m)]
ans = 1
for i in range(m):
for j in range(n):
ans = max(ans, self.longestFrom(matrix, i,j, dp))
return ans
def longestFrom(self, matrix, i,j, dp):
if dp[i][j] >0:
return dp[i][j]
ans = 1
if i-1>=0 and matrix[i-1][j]>matrix[i][j]:
ans = max(self.longestFrom(matrix, i-1,j, dp)+1,ans)
if i+1<len(matrix) and matrix[i+1][j]>matrix[i][j]:
ans = max(ans,self.longestFrom(matrix, i+1,j, dp)+1)
if j-1>=0 and matrix[i][j-1]>matrix[i][j]:
ans = max(ans,self.longestFrom(matrix, i,j-1, dp)+1)
if j+1<len(matrix[0]) and matrix[i][j+1]>matrix[i][j]:
ans = max(ans,self.longestFrom(matrix, i,j+1, dp)+1)
dp[i][j] = ans
return ans | longest-increasing-path-in-a-matrix | python DFS+DP | li87o | 1 | 76 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,676 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2348003/Python-BFS-solution-with-hashmap | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
height = len(matrix)
width = len(matrix[0])
max_length = 1
starting_point = (0,0)
directions = ((0, 1), (1, 0), (0,-1), (-1, 0))
visited_hash_map = defaultdict(lambda: 0)
queue = [ (starting_point, 0) ]
while queue:
(row, col), length = queue.pop(0)
max_length = max(max_length, length)
for dy, dx in directions:
_row, _col = row + dy, col + dx
if 0 <= _row < height and 0 <= _col < width:
new_length = 1
if matrix[row][col] > matrix[_row][_col]:
new_length += length
state = ( (_row, _col), new_length )
if visited_hash_map[(_row, _col)] < new_length:
visited_hash_map[(_row, _col)] = new_length
queue.append(state)
return max_length | longest-increasing-path-in-a-matrix | Python BFS solution with hashmap | complete_noob | 1 | 48 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,677 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2225145/python-solution-dfs-%2B-memoization-dp | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
# build the graph
graph = {}
dp = {}
m = len(matrix)
n = len(matrix[0])
for row in range(m):
for col in range(n):
# check four side if there is a bigger neighbour
graph[(row,col)] = set()
curr_element = matrix[row][col]
# check left side
if col > 0 and matrix[row][col-1] > curr_element:
graph[(row,col)].add((row, col - 1))
# check right side
if col < n - 1 and matrix[row][col+1] > curr_element:
graph[(row, col)].add((row, col + 1))
# check up side
if row > 0 and matrix[row-1][col] > curr_element:
graph[(row, col)].add((row-1, col))
# check down side
if row < m-1 and matrix[row+1][col] > curr_element:
graph[(row, col)].add((row+1, col))
# dfs
def dfs(row, col):
# check out of bound
if row < 0 or row > m or col < 0 or col > n:
return 0
# check if on dp
if (row,col) in dp:
return dp[(row, col)]
curr_max_length = 1
for neighbour in graph[(row,col)]:
neighbour_row, neighbour_col = neighbour
curr_max_length = max(dfs(neighbour_row, neighbour_col) + 1, curr_max_length)
dp[(row,col)] = curr_max_length
return curr_max_length
maximum = 0
for row in range(m):
for col in range(n):
curr_max = dfs(row, col)
maximum = max(maximum, curr_max)
return maximum | longest-increasing-path-in-a-matrix | python solution, dfs + memoization dp | bmusuko | 1 | 59 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,678 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2074276/Python-Very-Easy-Sort-and-Compare | class Solution:
def longestIncreasingPath(self, matrix):
M, N = len(matrix), len(matrix[0])
increase_order = sorted((matrix[i][j], i, j) for i in range(M) for j in range(N))
len_mat, max_len = [[1] * N for _ in range(M)], 0
for val, i, j in increase_order:
for ii, jj in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
if 0 <= ii < M and 0 <= jj < N and val > matrix[ii][jj]:
len_mat[i][j] = max(len_mat[i][j], len_mat[ii][jj] + 1)
max_len = max(max_len, len_mat[i][j])
return max_len | longest-increasing-path-in-a-matrix | Python Very Easy Sort and Compare | steve-jokes | 1 | 56 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,679 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2053105/python-java-DFS-(small-and-easy-to-understand) | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
Y = len(matrix) - 1
X = len(matrix[0]) - 1
def DFS(y, x):
if visited[y][x] != 0 : return visited[y][x]
val = 0
if y != 0 and matrix[y][x] < matrix[y-1][x]: val = max(val, DFS( y-1, x) )
if y != Y and matrix[y][x] < matrix[y+1][x]: val = max(val, DFS( y+1, x) )
if x != 0 and matrix[y][x] < matrix[y][x-1]: val = max(val, DFS( y, x-1) )
if x != X and matrix[y][x] < matrix[y][x+1]: val = max(val, DFS( y, x+1) )
visited[y][x] = val + 1
return val + 1
answer, limY, limX = 1, Y + 1, X + 1
visited = list()
for i in range(limY) : visited.append([0]*limX)
for i in range(limY):
for j in range(limX):
if visited[i][j] == 0: answer = max(answer, DFS(i, j))
return answer | longest-increasing-path-in-a-matrix | python, java - DFS (small & easy to understand) | ZX007java | 1 | 39 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,680 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/1599605/Py3Py-Simple-solution-using-memoized-dfs-w-comments | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
# Init
max_depth = 0
rows = len(matrix)
cols = len(matrix[0])
# Helper function to check if the node
# is within boundaries of the matrix
def inLimits(node):
r,c = node
return (0 <= r < rows) and (0 <= c < cols)
# Helper function to generate neighbours
# of a node
def neighbours(node):
r,c = node
return [(r-1,c), (r+1,c), (r,c-1), (r,c+1)]
# Helper function to check if the path from
# a node to its neighbours is increasing
def isIncreasing(x,y):
return matrix[y[0]][y[1]] > matrix[x[0]][x[1]]
# Memoized dfs
@cache
def dfs(node):
curr_depth = 1
for nei in neighbours(node):
if inLimits(nei) and isIncreasing(node, nei):
curr_depth = max(curr_depth, 1 + dfs(nei))
return curr_depth
# Run dfs for all nodes and calculate max depth
for i in range(rows):
for j in range(cols):
max_depth = max(max_depth, dfs((i,j)))
return max_depth # return max depth | longest-increasing-path-in-a-matrix | [Py3/Py] Simple solution using memoized dfs w/ comments | ssshukla26 | 1 | 130 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,681 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/1219778/python3-O(mn)-DFS-%2B-DP-solution | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
dp = [[0] * len(matrix[0]) for _ in range(len(matrix))]
def dfs(i, j):
longestnum = 1
dp[i][j] = -1
for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
x, y = i + dx, j + dy
if x < 0 or x > len(matrix) - 1 or y < 0 or y > len(matrix[0]) - 1:
continue
if dp[x][y] == -1 or matrix[x][y] <= matrix[i][j]:
continue
if dp[x][y] == 0:
dp[x][y] = dfs(x, y)
longestnum = max(longestnum, 1 + dp[x][y])
dp[i][j] = longestnum
return dp[i][j]
maxval = 0
for mi in range(len(matrix)):
for mj in range(len(matrix[0])):
if dp[mi][mj] == 0:
maxval = max(maxval, dfs(mi, mj))
return maxval | longest-increasing-path-in-a-matrix | python3 O(mn) DFS + DP solution | savikx | 1 | 84 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,682 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2842740/Python-3-easy-10-line-Sol.-faster-then-93-clean-code | class Solution(object):
def longestIncreasingPath(self, matrix):
li=[(0,1),(0,-1),(1,0),(-1,0)]
dp=[[0]*len(matrix[0]) for a in range(len(matrix))]
def helper(i,j):
if dp[i][j]==0:
dp[i][j]=1
for a,b in li:
if 0<=i+a<len(matrix) and 0<=j+b<len(matrix[0]):
if matrix[i+a][j+b]>matrix[i][j]:
dp[i][j] = max(dp[i][j],helper(i+a,j+b)+1)
return dp[i][j]
return max(helper(i,j) for i in range (len(matrix)) for j in range(len(matrix[0]))) | longest-increasing-path-in-a-matrix | Python 3 easy 10 line Sol. faster then 93% clean code | pranjalmishra334 | 0 | 3 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,683 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2798241/Clean-Backtracking-Solution-in-Python | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
m, n = len(matrix), len(matrix[0])
@cache
def backtrack(r, c):
mxPath = 0
for nxt_r, nxt_c in (
(r + 1, c),
(r - 1, c),
(r, c + 1),
(r, c - 1)
):
if 0 <= nxt_r < m and 0 <= nxt_c < n:
if matrix[nxt_r][nxt_c] > matrix[r][c]:
mxPath = max(mxPath, backtrack(nxt_r, nxt_c))
return mxPath + 1
return max(
[backtrack(row, col) for row in range(m) for col in range(n)]
) | longest-increasing-path-in-a-matrix | Clean Backtracking Solution in Python | ananth360 | 0 | 2 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,684 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2747325/Python3-DP-faster-than-98.87 | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
memo = [[-1] * len(matrix[0]) for _ in range(len(matrix))]
pathLengths = []
for i in range(len(matrix)):
for j in range(len(matrix[0])):
pathLengths.append(self.helper(j, i, matrix, memo))
return max(pathLengths)
def helper(self, x, y, matrix, memo):
if memo[y][x] == -1:
possiblePathLengths = []
# can move left
if x > 0 and matrix[y][x - 1] > matrix[y][x]:
if memo[y][x - 1] == -1:
memo[y][x - 1] = self.helper(x - 1, y, matrix, memo)
possiblePathLengths.append(memo[y][x - 1])
# can move right
if x < len(matrix[0]) - 1 and matrix[y][x + 1] > matrix[y][x]:
if memo[y][x + 1] == -1:
memo[y][x + 1] = self.helper(x + 1, y, matrix, memo)
possiblePathLengths.append(memo[y][x + 1])
# can move up
if y > 0 and matrix[y - 1][x] > matrix[y][x]:
if memo[y - 1][x] == -1:
memo[y - 1][x] = self.helper(x, y - 1, matrix, memo)
possiblePathLengths.append(memo[y - 1][x])
# can move down
if y < len(matrix) - 1 and matrix[y + 1][x] > matrix[y][x]:
if memo[y + 1][x] == -1:
memo[y + 1][x] = self.helper(x, y + 1, matrix, memo)
possiblePathLengths.append(memo[y + 1][x])
memo[y][x] = 1 if len(possiblePathLengths) == 0 else 1 + max(possiblePathLengths)
return memo[y][x] | longest-increasing-path-in-a-matrix | Python3 DP , faster than 98.87% | ch33tcode | 0 | 14 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,685 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2740701/2D-DP-(DFS-with-memoization) | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
ROWS, COLS = len(matrix), len(matrix[0])
dp = {} # (i, j) -> LIP
def dfs(i, j, prev_val):
if i < 0 or i == ROWS or j < 0 or j == COLS or matrix[i][j] <= prev_val:
return 0
if (i, j) in dp:
return dp[(i, j)]
res = 1
res = max(res, 1+dfs(i+1, j, matrix[i][j]))
res = max(res, 1+dfs(i-1, j, matrix[i][j]))
res = max(res, 1+dfs(i, j+1, matrix[i][j]))
res = max(res, 1+dfs(i, j-1, matrix[i][j]))
dp[(i, j)] = res
return res
res = 0
for r in range(ROWS):
for c in range(COLS):
res = max(res, dfs(r, c, -1))
return res | longest-increasing-path-in-a-matrix | 2D DP (DFS with memoization) | jonathanbrophy47 | 0 | 11 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,686 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2705932/Straight-forward-solution-Easy-to-understand-DFS | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
n, m = len(matrix), len(matrix[0])
lip = [[-1] * m for _ in range(n)]
def dfs(i, j, prev_val) -> int:
if i < 0 or i == n or j < 0 or j == m:
return 0
if matrix[i][j] <= prev_val:
return 0
if lip[i][j] != -1:
return lip[i][j]
lip[i][j] = 1 + max(dfs(i - 1, j, matrix[i][j]) ,
dfs(i + 1, j, matrix[i][j]),
dfs(i, j - 1, matrix[i][j]),
dfs(i, j + 1, matrix[i][j])
)
return lip[i][j]
for i in range(n):
for j in range(m):
dfs(i, j, -1)
return max(map(max, lip)) | longest-increasing-path-in-a-matrix | Straight forward solution - Easy to understand DFS | slob1 | 0 | 6 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,687 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2690799/Python-(Faster-than-97)-or-DFS-%2B-DP-O(N*M)-Solution | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
rows, cols = len(matrix), len(matrix[0])
longestPath = 1
dp = [[0] * cols for _ in range(rows)]
def dfs(r, c, prev):
if r < 0 or c < 0 or r >= rows or c >= cols or matrix[r][c] <= prev:
return 0
if dp[r][c] != 0:
return dp[r][c]
pathLength = 1
pathLength = max(pathLength, 1 + dfs(r + 1, c, matrix[r][c]), 1 + dfs(r - 1, c, matrix[r][c]),
1 + dfs(r, c + 1, matrix[r][c]), 1 + dfs(r, c - 1, matrix[r][c]))
dp[r][c] = pathLength
return pathLength
for r in range(rows):
for c in range(cols):
longestPath = max(longestPath, dfs(r, c, -1))
return longestPath | longest-increasing-path-in-a-matrix | Python (Faster than 97%) | DFS + DP O(N*M) Solution | KevinJM17 | 0 | 11 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,688 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2690649/very-simple-solution-oror-dfs-oror-python-oror-98-faster | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
row=len(matrix)
col=len(matrix[0])
dp=[[-1 for i in range(col)]for i in range(row)]
def safe(r,c):
if 0<=r<row and 0<=c<col:
return True
return False
def dfs(r,c):
if dp[r][c]!=-1:
return dp[r][c]
dp[r][c]=1
if safe(r+1,c) and matrix[r+1][c]>matrix[r][c]:
dp[r][c]=max(dp[r][c],1+dfs(r+1,c))
if safe(r-1,c) and matrix[r-1][c]>matrix[r][c]:
dp[r][c]=max(dp[r][c],1+dfs(r-1,c))
if safe(r,c+1) and matrix[r][c+1]>matrix[r][c]:
dp[r][c]=max(dp[r][c],1+dfs(r,c+1))
if safe(r,c-1) and matrix[r][c-1]>matrix[r][c]:
dp[r][c]=max(dp[r][c],1+dfs(r,c-1))
return dp[r][c]
res=1
for i in range(row):
for j in range(col):
res=max(res,dfs(i,j))
return res | longest-increasing-path-in-a-matrix | very simple solution || dfs || python || 98% faster | aryan3012 | 0 | 5 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,689 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2607644/Python3-Elegant-Solution | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
if not matrix:
return 0
pathLen = 1
useStack = set()
for i in range(len(matrix)):
for j in range(len(matrix[0])):
maxCnt = 0
maxCnt += 1 if (i+1 == len(matrix)) or (matrix[i+1][j] <= matrix[i][j]) else 0
maxCnt += 1 if (i == 0) or (matrix[i-1][j] <= matrix[i][j]) else 0
maxCnt += 1 if (j+1 == len(matrix[0])) or (matrix[i][j+1] <= matrix[i][j]) else 0
maxCnt += 1 if (j == 0) or (matrix[i][j-1] <= matrix[i][j]) else 0
if maxCnt == 4:
useStack.add((i, j))
saveStack = set()
for point in useStack:
if point[0]+1 != len(matrix) and matrix[point[0]][point[1]] > matrix[point[0]+1][point[1]]:
saveStack.add((point[0]+1, point[1]))
if point[1]+1 != len(matrix[0]) and matrix[point[0]][point[1]] > matrix[point[0]][point[1]+1]:
saveStack.add((point[0], point[1]+1))
if point[0] != 0 and matrix[point[0]][point[1]] > matrix[point[0]-1][point[1]]:
saveStack.add((point[0]-1, point[1]))
if point[1] != 0 and matrix[point[0]][point[1]] > matrix[point[0]][point[1]-1]:
saveStack.add((point[0], point[1]-1))
while saveStack:
useStack.clear()
useStack, saveStack = saveStack, useStack
for point in useStack:
if point[0]+1 != len(matrix) and matrix[point[0]][point[1]] > matrix[point[0]+1][point[1]]:
saveStack.add((point[0]+1, point[1]))
if point[1]+1 != len(matrix[0]) and matrix[point[0]][point[1]] > matrix[point[0]][point[1]+1]:
saveStack.add((point[0], point[1]+1))
if point[0] != 0 and matrix[point[0]][point[1]] > matrix[point[0]-1][point[1]]:
saveStack.add((point[0]-1, point[1]))
if point[1] != 0 and matrix[point[0]][point[1]] > matrix[point[0]][point[1]-1]:
saveStack.add((point[0], point[1]-1))
pathLen += 1
return pathLen | longest-increasing-path-in-a-matrix | Python3 Elegant Solution | PlayingChess | 0 | 16 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,690 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2509956/Python3-solution%3A-faster-than-most-submissions | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
ROWS, COLS = len(matrix), len(matrix[0])
dp = {}
def dfs(r, c, prevVal):
if (r < 0 or r == ROWS or
c < 0 or c == COLS or
matrix[r][c] <= prevVal):
return 0
if (r, c) in dp:
return dp[(r, c)]
res = 1
res = max(res, 1 + dfs(r + 1, c, matrix[r][c]))
res = max(res, 1 + dfs(r - 1, c, matrix[r][c]))
res = max(res, 1 + dfs(r, c + 1, matrix[r][c]))
res = max(res, 1 + dfs(r, c - 1, matrix[r][c]))
dp[(r, c)] = res
return res
for r in range(ROWS):
for c in range(COLS):
dfs(r, c, -1)
return max(dp.values()) | longest-increasing-path-in-a-matrix | βοΈ Python3 solution: faster than most submissions | UpperNoot | 0 | 69 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,691 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2429051/Python3-or-DFS-%2B-Memoization | class Solution:
def longestIncreasingPath(self, A: List[List[int]]) -> int:
m,n=len(A),len(A[0])
ans=0
@lru_cache(None)
def dfs(row,col):
vis.add((row,col))
up,down,left,right=0,0,0,0
if row+1<m and A[row+1][col]>A[row][col] and (row+1,col) not in vis:
down=1+dfs(row+1,col)
if row-1>=0 and A[row-1][col]>A[row][col] and (row-1,col) not in vis:
up=1+dfs(row-1,col)
if col+1<n and A[row][col+1]>A[row][col] and (row,col+1) not in vis:
right=1+dfs(row,col+1)
if col-1>=0 and A[row][col-1]>A[row][col] and (row,col-1) not in vis:
left=1+dfs(row,col-1)
vis.remove((row,col))
return max(1,up,down,left,right)
for i in range(m):
for j in range(n):
vis=set()
ans=max(ans,dfs(i,j))
return ans | longest-increasing-path-in-a-matrix | [Python3] | DFS + Memoization | swapnilsingh421 | 0 | 96 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,692 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2375485/python-O(N*M)-Solution | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
ROWS, COLS = len(matrix), len(matrix[0])
dp = {}
def dfs(r, c, prevVal):
if (r < 0 or r == ROWS or
c < 0 or c == COLS or
matrix[r][c] <= prevVal):
return 0
if (r, c) in dp:
return dp[(r, c)]
res = 1
res = max(res, 1 + dfs(r + 1, c, matrix[r][c]))
res = max(res, 1 + dfs(r - 1, c, matrix[r][c]))
res = max(res, 1 + dfs(r, c + 1, matrix[r][c]))
res = max(res, 1 + dfs(r, c - 1, matrix[r][c]))
dp[(r, c)] = res
return res
for r in range(ROWS):
for c in range(COLS):
dfs(r, c, -1)
return max(dp.values()) | longest-increasing-path-in-a-matrix | python O(N*M) Solution | soumyadexter7 | 0 | 91 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,693 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2328978/Memoization-technique-with-Depth-first-search | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
# we will look for every occurence of each cell and will use memoization technique to reuse the longest path for every cell if present in dp. Dynamic programming
row, col = len(matrix), len(matrix[0])
dp = {}
def dfs(r, c, prev):
if r<0 or c<0 or r == row or c ==col or matrix[r][c]<=prev:
return 0
if (r,c) in dp:
return dp[(r,c)]
res = 1
res = max(res, dfs(r+1, c, matrix[r][c])+1)
res = max(res, dfs(r, c+1, matrix[r][c])+1)
res = max(res, dfs(r-1, c, matrix[r][c])+1)
res = max(res, dfs(r, c-1, matrix[r][c])+1)
dp[(r,c)] = res
return res
for i in range(row):
for j in range(col):
dfs(i,j,-1)
return max(dp.values()) | longest-increasing-path-in-a-matrix | Memoization technique with Depth first search | yashchandani98 | 0 | 36 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,694 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2273970/Python-3-Simple-DP | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
m, n = len(matrix), len(matrix[0])
cache = {}
def search(cm, cn):
if (cm, cn) in cache:
return cache[(cm, cn)]
max_depth = 0
for bm, bn in [(-1, 0), (0, -1), (1, 0), (0, 1)]:
tm, tn = cm + bm, cn + bn
if tm < 0 or tm >= m or tn < 0 or tn >= n:
continue
if matrix[tm][tn] <= matrix[cm][cn]:
continue
k = search(tm, tn)
if k > max_depth:
max_depth = k
cache[(cm, cn)] = max_depth + 1
return max_depth + 1
global_max = 0
for i in range(m):
for j in range(n):
global_max = max(search(i, j), global_max)
return global_max | longest-increasing-path-in-a-matrix | Python 3 Simple DP | leng-yue | 0 | 28 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,695 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2205746/DFS-%2B-Memoization | class Solution:
def inBound(self, x, y, matrix):
m, n = len(matrix), len(matrix[0])
return 0 <= x < m and 0 <= y < n
def longestPath(self, x, y, matrix, dpMatrix):
directions = [[-1, 0], [0, -1], [1, 0], [0, 1]]
if not self.inBound(x, y, matrix):
return 0
if dpMatrix[x][y] > 0:
return dpMatrix[x][y]
currentMax = 1
for direction in directions:
xNew = x + direction[0]
yNew = y + direction[1]
if self.inBound(xNew, yNew, matrix) and matrix[xNew][yNew] > matrix[x][y]:
currentMax = max(currentMax, 1 + self.longestPath(xNew, yNew, matrix, dpMatrix))
dpMatrix[x][y] = currentMax
return currentMax
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
longestPath = 0
m, n = len(matrix), len(matrix[0])
dpMatrix = [[0]*n for i in range(m)]
for i in range(m):
for j in range(n):
longestPath = max(longestPath, self.longestPath(i, j, matrix, dpMatrix))
return longestPath | longest-increasing-path-in-a-matrix | DFS + Memoization | Vaibhav7860 | 0 | 130 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,696 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2122654/Python3-or-Memoization-or-93 | class Solution:
def longestIncreasingPath(self, matrix: list[list[int]]) -> int:
memo = [[None]*len(matrix[0]) for _ in range(len(matrix))]
def findMaxPath(r, c, matrix, visited):
maxm = 1
if memo[r][c] is not None:
return memo[r][c]
if (r,c) in visited:
return 0
if r > 0 and matrix[r][c] < matrix[r-1][c]:
maxm = max(findMaxPath(r-1, c, matrix, visited+[(r,c)])+1, maxm)
if r < len(matrix)-1 and matrix[r][c] < matrix[r+1][c]:
maxm = max(findMaxPath(r+1, c, matrix, visited+[(r,c)])+1, maxm)
if c > 0 and matrix[r][c] < matrix[r][c-1]:
maxm = max(findMaxPath(r, c-1, matrix, visited+[(r,c)])+1, maxm)
if c < len(matrix[0])-1 and matrix[r][c] < matrix[r][c+1]:
maxm = max(findMaxPath(r, c+1, matrix, visited+[(r,c)])+1, maxm)
memo[r][c]=maxm
return maxm
maxm=0
for i in range(len(matrix)):
for j in range(len(matrix[i])):
maxm=max(findMaxPath(i, j, matrix, []),maxm)
return maxm | longest-increasing-path-in-a-matrix | Python3 | Memoization | 93% | ComicCoder023 | 0 | 71 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,697 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2056518/Python3-Solution-with-using-dfs-and-dp | class Solution:
def traversal(self, matrix, dp, i, j, prev_val):
if i < 0 or i >= len(matrix) or j < 0 or j >= len(matrix[0]) or prev_val >= matrix[i][j]:
return 0
if dp[i][j] != 0:
return dp[i][j]
up_len = self.traversal(matrix, dp, i + 1, j, matrix[i][j])
right_len = self.traversal(matrix, dp, i, j + 1, matrix[i][j])
down_len = self.traversal(matrix, dp, i - 1, j, matrix[i][j])
left_len = self.traversal(matrix, dp, i, j - 1, matrix[i][j])
dp[i][j] = max(up_len, right_len, down_len, left_len) + 1
return dp[i][j]
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
res = -1
dp = [[0 for _ in range(len(matrix[0]))] for _ in range(len(matrix))]
for i in range(len(matrix)):
for j in range(len(matrix[i])):
res = max(res, self.traversal(matrix, dp, i, j, -1))
return res | longest-increasing-path-in-a-matrix | [Python3] Solution with using dfs and dp | maosipov11 | 0 | 12 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,698 |
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2055172/Python-Simple-and-Easy-Solution-oror-DFS-Solution | class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
rows, cols = len(matrix), len(matrix[0])
dp = {}
def dfs(r, c, prevVal):
if (r < 0 or r == rows or c < 0 or c == cols
or matrix[r][c] <= prevVal):
return 0
if (r, c) in dp:
return dp[(r,c)]
res = 1
res = max(res, 1 + dfs(r + 1, c, matrix[r][c]))
res = max(res, 1 + dfs(r - 1, c, matrix[r][c]))
res = max(res, 1 + dfs(r, c + 1, matrix[r][c]))
res = max(res, 1 + dfs(r, c - 1, matrix[r][c]))
dp[(r, c)] = res
return res
for r in range(rows):
for c in range(cols):
dfs(r, c, -1)
return max(dp.values()) | longest-increasing-path-in-a-matrix | Python - Simple and Easy Solution || DFS Solution | dayaniravi123 | 0 | 8 | longest increasing path in a matrix | 329 | 0.522 | Hard | 5,699 |
Subsets and Splits