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/n-th-tribonacci-number/discuss/2547199/EASY-PYTHON3-SOLUTION
class Solution: def tribonacci(self, n: int) -> int: if n == 0: return 0 # this is our base cases x1, x2, x3 = 0, 1, 1 # we end at n+1 because we need to include the "n" itself for i in range(3, n+1): # this is just a short cut instead of using temp variables to do the swapping x3 ,x1, x2 = (x1 + x2 + x3), x2, x3 return x3
n-th-tribonacci-number
🔥 EASY PYTHON3 SOLUTION 🔥
rajukommula
0
24
n th tribonacci number
1,137
0.633
Easy
17,700
https://leetcode.com/problems/n-th-tribonacci-number/discuss/2395407/python3-or-Memoization
class Solution: def tribonacci(self, n: int) -> int: cache = {0: 0, 1: 1, 2: 1} return self.recurse(n, cache) def recurse(self, n, cache): if n in cache: return cache[n] if n not in cache: cache[n] = self.recurse(n-3, cache) + self.recurse(n-2, cache) + self.recurse(n-1, cache) return cache[n]
n-th-tribonacci-number
python3 | Memoization
Gilbert770
0
18
n th tribonacci number
1,137
0.633
Easy
17,701
https://leetcode.com/problems/n-th-tribonacci-number/discuss/2258750/4-line-of-Code-orororor-Python-Simple-Python-Solution-ororororor-100-Optimal-Solution
class Solution: def tribonacci(self, n: int) -> int: a = [0, 1, 1] for i in range(3,n+1): a.append(sum(a[i-3:i])) return a[n]
n-th-tribonacci-number
4 line of Code |||| [ Python ] ✅ Simple Python Solution ✅✅ ||||| ✅100% Optimal Solution
vaibhav0077
0
43
n th tribonacci number
1,137
0.633
Easy
17,702
https://leetcode.com/problems/n-th-tribonacci-number/discuss/2232018/Fast-and-easy-solution
class Solution: def tribonacci(self, n: int) -> int: nums = [0,1,1] nums1,nums2,nums3,new = 0,1,1,0 for i in range(n): new = nums1 + nums2 + nums3 nums1 = nums2 nums2 = nums3 nums3 = new nums.append(new) return nums[n]
n-th-tribonacci-number
Fast and easy solution
kollee001
0
32
n th tribonacci number
1,137
0.633
Easy
17,703
https://leetcode.com/problems/n-th-tribonacci-number/discuss/2169538/Python-runtime-51.86-memory-58.81
class Solution: def tribonacci(self, n: int) -> int: d = {0:0, 1:1, 2:1} return self.recur(n, d) def recur(self, n, d): if n >= 3: d[n] = self.recur(n-1, d) + d[n-2] + d[n-3] return d[n] return d[n]
n-th-tribonacci-number
Python, runtime 51.86%, memory 58.81%
tsai00150
0
54
n th tribonacci number
1,137
0.633
Easy
17,704
https://leetcode.com/problems/n-th-tribonacci-number/discuss/2169538/Python-runtime-51.86-memory-58.81
class Solution: def tribonacci(self, n: int) -> int: d = {0:0, 1:1, 2:1} if n <= 2: return d[n] for i in range(3, n+1): d[i] = d[i-1] + d[i-2] + d[i-3] return d[n]
n-th-tribonacci-number
Python, runtime 51.86%, memory 58.81%
tsai00150
0
54
n th tribonacci number
1,137
0.633
Easy
17,705
https://leetcode.com/problems/n-th-tribonacci-number/discuss/2157435/Python-N-th-Tribonacci-Number-(Easy-way)
class Solution: def tribonacci(self, n: int) -> int: a, b, c = 0, 1, 1 # T_3 = 0 + 1 + 1 = 2 # T_4 = 1 + 1 + 2 = 4 # T-5 = 1 + 2 + 4 = 7 if n == 0: return 0 for i in range(n - 2): a, b, c = b, c, a + b + c return c
n-th-tribonacci-number
[Python] N-th Tribonacci Number (Easy way)
YangJenHao
0
26
n th tribonacci number
1,137
0.633
Easy
17,706
https://leetcode.com/problems/n-th-tribonacci-number/discuss/2118346/Python-simple-solution
class Solution: def tribonacci(self, n: int) -> int: arr = [0,1,1] for i in range(2,n): arr.append(sum(arr[-3:])) return arr[n]
n-th-tribonacci-number
Python simple solution
StikS32
0
75
n th tribonacci number
1,137
0.633
Easy
17,707
https://leetcode.com/problems/n-th-tribonacci-number/discuss/2070395/Python-space-optimization-O(1)-Space
class Solution: def tribonacci(self, n: int) -> int: if n == 0: return 0 elif n==1 or n == 2: return 1 a,b,c = 0,1,1 for i in range(3,n+1): a,b,c = b,c, a+b+c return c
n-th-tribonacci-number
Python space optimization O(1) Space
dc_devesh7
0
46
n th tribonacci number
1,137
0.633
Easy
17,708
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1941865/Python-Solution
class Solution: def tribonacci(self, n: int) -> int: arr = [0,1,1] if n <= 2: return arr[n] for i in range(3,n+1): arr.append(arr[i-1]+arr[i-2]+arr[i-3]) return arr[n]
n-th-tribonacci-number
Python Solution
MS1301
0
45
n th tribonacci number
1,137
0.633
Easy
17,709
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1925050/Python-Solution-using-Array
class Solution: def tribonacci(self, n: int) -> int: arr = [0, 1, 1] if n < 3: return arr[n] i = 3 while i <= n and i <= 37: arr.append(arr[i-1] + arr[i-2] + arr[i-3]) i += 1 return arr[-1]
n-th-tribonacci-number
Python Solution using Array
sayantanis23
0
15
n th tribonacci number
1,137
0.633
Easy
17,710
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1914203/Python-Multiple-Solutions-Clean-and-Simple!
class Solution: def tribonacci(self, n): return 0 if n==0 else 1 if n<3 else self.tribonacci(n-1)+self.tribonacci(n-2)+self.tribonacci(n-3)
n-th-tribonacci-number
Python - Multiple Solutions - Clean and Simple!
domthedeveloper
0
43
n th tribonacci number
1,137
0.633
Easy
17,711
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1914203/Python-Multiple-Solutions-Clean-and-Simple!
class Solution: @cache def tribonacci(self, n): return 0 if n==0 else 1 if n<3 else self.tribonacci(n-1)+self.tribonacci(n-2)+self.tribonacci(n-3)
n-th-tribonacci-number
Python - Multiple Solutions - Clean and Simple!
domthedeveloper
0
43
n th tribonacci number
1,137
0.633
Easy
17,712
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1914203/Python-Multiple-Solutions-Clean-and-Simple!
class Solution: def tribonacci(self, n): q = deque([0,1,1], maxlen=3) for i in range(n): q.append(q.popleft()+q[-1]+q[-2]) return q.popleft()
n-th-tribonacci-number
Python - Multiple Solutions - Clean and Simple!
domthedeveloper
0
43
n th tribonacci number
1,137
0.633
Easy
17,713
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1914203/Python-Multiple-Solutions-Clean-and-Simple!
class Solution: def tribonacci(self, n): a, b, c = 0, 1, 1 for i in range(n): a, b, c = b, c, a+b+c return a
n-th-tribonacci-number
Python - Multiple Solutions - Clean and Simple!
domthedeveloper
0
43
n th tribonacci number
1,137
0.633
Easy
17,714
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1914203/Python-Multiple-Solutions-Clean-and-Simple!
class Solution: def tribonacci(self, n): return reduce(lambda x,_:(x[1],x[2],x[0]+x[1]+x[2]), range(n), (0, 1, 1))[0]
n-th-tribonacci-number
Python - Multiple Solutions - Clean and Simple!
domthedeveloper
0
43
n th tribonacci number
1,137
0.633
Easy
17,715
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1896216/Python-easy-solution-for-beginners
class Solution: def tribonacci(self, n: int) -> int: if n == 0: return 0 elif n == 1 or n == 2: return 1 else: a = 0 b = 1 c = 1 for i in range(n-2): d = a + b + c a = b b = c c = d return d
n-th-tribonacci-number
Python easy solution for beginners
alishak1999
0
43
n th tribonacci number
1,137
0.633
Easy
17,716
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1832775/Python3-Dynamic-programming
class Solution: def tribonacci(self, n: int) -> int: if n <= 1: return n dp = [0] * (n + 1) dp[0] = 0 dp[1] = 1 dp[2] = 1 for i in range(3,n + 1): dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3] return dp[-1]
n-th-tribonacci-number
[Python3] Dynamic programming
zhanweiting
0
80
n th tribonacci number
1,137
0.633
Easy
17,717
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1804955/Python3-bottom-up-dp-solution.
class Solution: def BottomUp(self, n): if n == 0: return 0 elif n == 1: return 1 elif n == 2: return 1 first = 0 second = 1 third = 1 for i in range(3, n+1): current = first + second + third #self.dp[i] = current first = second second = third third = current return current def tribonacci(self, n: int) -> int: return(self.BottomUp(n))
n-th-tribonacci-number
Python3 bottom up dp solution.
sourav-saha
0
38
n th tribonacci number
1,137
0.633
Easy
17,718
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1804923/Python3-top-down-dp-solution-.
class Solution: dp = [-1]*38 def TopDown(self, n): #base case if n == 0: return 0 elif n == 1: return 1 elif n == 2: return 1 elif self.dp[n] == -1: self.dp[n] = self.TopDown(n-3) + self.TopDown(n-2) + self.TopDown(n-1) return self.dp[n] def tribonacci(self, n: int) -> int: return(self.TopDown(n))
n-th-tribonacci-number
Python3 top down dp solution .
sourav-saha
0
16
n th tribonacci number
1,137
0.633
Easy
17,719
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1789495/Python-or-Simple-Solution-or-Using-lru_cache
class Solution: @lru_cache(maxsize=None) def tribonacci(self, n: int) -> int: if n == 0: return 0 if n == 1 or n == 2: return 1 return self.tribonacci(n - 3) + self.tribonacci(n - 2) + self.tribonacci(n - 1)
n-th-tribonacci-number
[Python] | Simple Solution | Using lru_cache
tejeshreddy111
0
38
n th tribonacci number
1,137
0.633
Easy
17,720
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1771794/Simple-Python-Solution-or-Easy-To-Understand-or-O(n)-Time-or-O(1)-Space
class Solution: def tribonacci(self, n: int) -> int: a, b, c, i = 0, 1, 1, 3 if n in [0,1]: return n while(i<=n): temp = a + b + c a = b b = c c = temp i += 1 return (c)
n-th-tribonacci-number
✔Simple Python Solution | Easy To Understand | O(n) Time | O(1) Space
Coding_Tan3
0
62
n th tribonacci number
1,137
0.633
Easy
17,721
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1712266/Solution-with-DP-Top-Down-with-memoization
class Solution: def tribonacci(self, n: int) -> int: memo = {} memo[0] = 0 memo[1] = 1 memo[2] = 1 def dp(i): if i in memo: return memo[i] memo[i] = dp(i-1) + dp(i-2) + dp(i-3) return memo[i] dp(n) return memo[n]
n-th-tribonacci-number
Solution with DP - Top Down with memoization
alessiogatto
0
68
n th tribonacci number
1,137
0.633
Easy
17,722
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1584654/easy-Python-solution-linear-dp
class Solution: def tribonacci(self, n: int) -> int: f = [None]*38 f[0] = 0 f[1] = 1 f[2] = 1 for i in range(3,n+1): f[i] = f[i-1] + f[i-2] + f[i-3] return f[n]
n-th-tribonacci-number
easy Python solution- linear dp
pheraram
0
109
n th tribonacci number
1,137
0.633
Easy
17,723
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1561276/Python3-or-Easy-or-No-Recursive-or-Loop-Solution
class Solution: def tribonacci(self, n: int) -> int: fnum = 0 snum = 1 tnum = 1 for i in range(n): fnum,snum = snum,fnum+snum snum,tnum = tnum,snum+tnum return fnum
n-th-tribonacci-number
Python3 | Easy | No Recursive | Loop Solution
infinityhawk
0
50
n th tribonacci number
1,137
0.633
Easy
17,724
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1532980/Python3-Solution
class Solution: def tribonacci(self, n: int,dp={}) -> int: if n<=1: return n if n==2: return 1 if n not in dp: dp[n]=self.tribonacci(n-1, dp) + self.tribonacci(n-2, dp) + self.tribonacci(n-3, dp) return dp[n]
n-th-tribonacci-number
Python3 Solution
kirtipurohit025
0
51
n th tribonacci number
1,137
0.633
Easy
17,725
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1483290/Python3-DP-solution
class Solution: def tribonacci(self, n: int) -> int: dp = [0] * (n + 4) dp[0] = 0 dp[1] = 1 dp[2] = 1 for i in range(3, n + 1): dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3] return dp[n]
n-th-tribonacci-number
[Python3] DP solution
maosipov11
0
16
n th tribonacci number
1,137
0.633
Easy
17,726
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1483145/Without-using-Dynammic-Programming-with-Python3
class Solution: @cache def tribonacci(self, n: int) -> int: if n == 0 or n == 1: return n if n == 2: return 1 return self.tribonacci(n - 1) + self.tribonacci(n - 2) + self.tribonacci(n - 3)
n-th-tribonacci-number
Without using Dynammic Programming with Python3
guptaanshik1
0
10
n th tribonacci number
1,137
0.633
Easy
17,727
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1445608/Simple-Python-Solution
class Solution: def tribonacci(self, n: int) -> int: arr=[0,1,1] for i in range(3,n+1): arr.append(arr[i-1]+arr[i-2]+arr[i-3]) return arr[n]
n-th-tribonacci-number
Simple Python Solution
bazman
0
40
n th tribonacci number
1,137
0.633
Easy
17,728
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1436849/Python-Simple-DP-Faster-than-98.75
class Solution: def __init__(self): self.memo = [None] * 38 self.memo[0] = 0 self.memo[1] = 1 self.memo[2] = 1 def tribonacci(self, n: int) -> int: if self.memo[n] is not None: return self.memo[n] number = self.tribonacci(n - 1) + self.tribonacci(n - 2) + self.tribonacci(n - 3) self.memo[n] = number return number
n-th-tribonacci-number
Python Simple DP Faster than 98.75%
rizwanmustafa0000
0
92
n th tribonacci number
1,137
0.633
Easy
17,729
https://leetcode.com/problems/n-th-tribonacci-number/discuss/1419738/Python3-Iterative-No-Memory-Less-Than-90.54
class Solution: def tribonacci(self, n: int) -> int: if n < 3: if n == 0: return 0 if n == 1 or n == 2: return 1 t0, t1, t2 = 0, 1, 1 for i in range(3, n + 1): t = t0 + t1 + t2 t0 = t1 t1 = t2 t2 = t return t
n-th-tribonacci-number
Python3 Iterative No Memory [Less Than 90.54%]
Hejita
0
26
n th tribonacci number
1,137
0.633
Easy
17,730
https://leetcode.com/problems/alphabet-board-path/discuss/837601/Python-3-or-Straight-forward-solution-or-Explanations
class Solution: def __init__(self): board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"] self.d = {c:(i, j) for i, row in enumerate(board) for j, c in enumerate(row)} def alphabetBoardPath(self, target: str) -> str: ans, prev = '', (0, 0) for c in target: cur = self.d[c] delta_x, delta_y = cur[0]-prev[0], cur[1]-prev[1] h = 'R'*delta_y if delta_y > 0 else 'L'*(-delta_y) v = 'D'*delta_x if delta_x > 0 else 'U'*(-delta_x) ans += (h+v if cur == (5,0) else v+h) + '!' prev = cur return ans
alphabet-board-path
Python 3 | Straight forward solution | Explanations
idontknoooo
2
184
alphabet board path
1,138
0.523
Medium
17,731
https://leetcode.com/problems/alphabet-board-path/discuss/2516299/Python3-or-Map-characters-or-simulate-the-moves
class Solution: def alphabetBoardPath(self, target: str) -> str: # Map row and column for all characters board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"] map_row = {char: r for r, characters in enumerate(board) for c, char in enumerate(characters)} map_col = {char: c for r, characters in enumerate(board) for c, char in enumerate(characters)} res = [] r = c = 0 for char in target: target_r, target_c = map_row[char], map_col[char] if r != target_r or c != target_c: if r == 5 and c == 0: # special case: if at 'z', can only move up res.append('U') r -= 1 # Go to target column hori_move = abs(target_c - c) res.append('R' * hori_move if c < target_c else 'L' * hori_move) if c > target_c: hori_move *= -1 c += hori_move # Go to target row verti_move = abs(target_r - r) res.append('D' * verti_move if r < target_r else 'U' * verti_move) if r > target_r: verti_move *= -1 r += verti_move res.append('!') return ''.join(res)
alphabet-board-path
Python3 | Map characters | simulate the moves
Ploypaphat
0
21
alphabet board path
1,138
0.523
Medium
17,732
https://leetcode.com/problems/alphabet-board-path/discuss/2218323/PYTHON-SOL-or-LINEAR-TIME-or-VERY-EASY-or-EXPLAINED-WITH-PICTURE-or
class Solution: def alphabetBoardPath(self, target: str) -> str: def shortestPath(r,c,tr,tc): path = "" pr = r while r > tr: path += 'U' r -= 1 while r < tr: path += 'D' r += 1 if tr == 5 and pr != tr: path = path[:len(path) - 1] while c > tc: path += 'L' c -= 1 while c < tc: path += 'R' c += 1 if tr == 5 and pr != tr: path = path + 'D' return path table = ['abcde','fghij','klmno','pqrst','uvwxy','z'] r,c = 0,0 ans = "" for character in target: t_row = None for i,word in enumerate(table): if character in word: t_row = i break t_col = table[i].index(character) ans += shortestPath(r,c,t_row,t_col) + '!' r,c = t_row,t_col return ans
alphabet-board-path
PYTHON SOL | LINEAR TIME | VERY EASY | EXPLAINED WITH PICTURE |
reaper_27
0
35
alphabet board path
1,138
0.523
Medium
17,733
https://leetcode.com/problems/alphabet-board-path/discuss/1628963/Brute-force-with-my-notes
class Solution: def alphabetBoardPath(self, target: str) -> str: board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"] # greedy because starting from 0,0 no matter # the next letter the best move is always just going # directly to it in terms of distance between # prev - cur coords = {} pc = "a" for row in range(len(board)): for col in range(len(board[row])): # col = x, row = y coords[board[row][col]] = (row, col) moves = [] # how to account for z?? # you know its z and special if its row 5 # and col is != 0 for nc in target: # get diff which represents the amount to move # from the cur x,y coordinate cur = coords[pc] nxt = coords[nc] r_cur, c_cur = cur r_nxt, c_nxt = nxt r_diff = r_nxt - r_cur c_diff = c_nxt - c_cur # where char = z and then the column to move from # is not 0 then you need to go left then go down # otherwise if 0 you cna just follow normal if nc == "z" and c_cur != 0: # this is special z case, just go left to pin # to LHS then go down moves.append("L" * abs(c_diff)) moves.append("D" * abs(r_diff)) else: if r_diff > 0: moves.append("D" * r_diff) else: moves.append("U" * abs(r_diff)) if c_diff > 0: moves.append("R" * c_diff) else: moves.append("L" * abs(c_diff)) # mark and add char moves.append("!") # make new previous to current pc = nc return "".join(moves)
alphabet-board-path
Brute force with my notes
normalpersontryingtopayrent
0
33
alphabet board path
1,138
0.523
Medium
17,734
https://leetcode.com/problems/alphabet-board-path/discuss/1447483/Simple-Python-O(n)-hashmap-solution
class Solution: def alphabetBoardPath(self, target: str) -> str: # find mapping from letter to index board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"] letter2idx = {} for i in range(len(board)): for j in range(len(board[i])): letter2idx[board[i][j]] = (i, j) cur_i = cur_j = 0 ret = [] for letter in target: d_i = letter2idx[letter][0]-cur_i d_j = letter2idx[letter][1]-cur_j # always move left and up before right and down # so that we never go out of board at the row z is in if d_i < 0: ret.extend(['U']*(-d_i)) if d_j < 0: ret.extend(['L']*(-d_j)) if d_i > 0: ret.extend(['D']*d_i) if d_j > 0: ret.extend(['R']*d_j) ret.append('!') cur_i, cur_j = letter2idx[letter] return "".join(ret)
alphabet-board-path
Simple Python O(n) hashmap solution
Charlesl0129
0
131
alphabet board path
1,138
0.523
Medium
17,735
https://leetcode.com/problems/alphabet-board-path/discuss/1169851/99.79-Faster-Solution-Python3-(16ms).-Easy-Readable-Code
class Solution: def getPosition(self,alpha:str): ascii_code = ord(alpha)-ord('a') q = ascii_code//5 r = ascii_code%5 return [q,r] def getDirection(self,tx,ty,px,py): direction = '' if tx == 5 and ty >= 0: diff_x = 4-px diff_y = ty-py direction += 'D'*diff_x direction += 'L'*(-1*diff_y) direction += 'D' else: diff_x = tx-px diff_y = ty-py if diff_x>0: direction += 'D'*diff_x else: direction += 'U'*(-1*diff_x) if diff_y>0: direction += 'R'*diff_y else: direction += 'L'*(-1*diff_y) return direction return direction def alphabetBoardPath(self, target: str) -> str: position = [0,0] res = '' for char in target: target = self.getPosition(char) if target == position: res += '!' else: tx,ty = target[0],target[1] px,py = position[0],position[1] direct = self.getDirection(tx,ty,px,py) res += direct res += '!' position = target return res
alphabet-board-path
99.79% Faster Solution Python3 (16ms). Easy Readable Code
tgoel219
0
37
alphabet board path
1,138
0.523
Medium
17,736
https://leetcode.com/problems/alphabet-board-path/discuss/1168530/Python3-linear-sweep
class Solution: def alphabetBoardPath(self, target: str) -> str: ans = [] x = y = 0 for c in target: xx, yy = divmod(ord(c)-97, 5) if x > xx: ans.append((x-xx)*"U") if y > yy: ans.append((y-yy)*"L") if x < xx: ans.append((xx-x)*"D") if y < yy: ans.append((yy-y)*"R") ans.append("!") x, y = xx, yy return "".join(ans)
alphabet-board-path
[Python3] linear sweep
ye15
0
33
alphabet board path
1,138
0.523
Medium
17,737
https://leetcode.com/problems/alphabet-board-path/discuss/1069469/Python3-solution-faster-than-96.45-in-time-and-less-than-94.90-in-memory
class Solution: def alphabetBoardPath(self, target): hashTable = [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 0], [1, 1], [1, 2], [1, 3], [1, 4], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [3, 0], [3, 1], [3, 2], [3, 3], [3, 4], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [5, 0]] OFFSET, current = 97, 0 res = "" for t in target: v_move = hashTable[current][0] - hashTable[ord(t)-OFFSET][0] h_move = hashTable[current][1] - hashTable[ord(t)-OFFSET][1] while v_move != 0 or h_move != 0: #Go vertical direction while v_move != 0: if v_move < 0 and current < 21: res += 'D' v_move += 1 current += 5 elif v_move > 0: res += 'U' v_move -= 1 current -= 5 else: break #Go horizontal direction current -= h_move while h_move != 0: if h_move < 0: res += 'R' h_move += 1 else: res += 'L' h_move -= 1 res += '!' return res
alphabet-board-path
Python3 solution, faster than 96.45% in time and less than 94.90% in memory
danieltseng
0
51
alphabet board path
1,138
0.523
Medium
17,738
https://leetcode.com/problems/largest-1-bordered-square/discuss/1435087/Python-3-or-Prefix-sum-DP-O(N3)-or-Explanation
class Solution: def largest1BorderedSquare(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) dp = [[(0, 0)] * (n) for _ in range((m))] for i in range(m): # calculate prefix-sum as `hint` section suggested for j in range(n): if not grid[i][j]: continue dp[i][j] = (dp[i][j][0] + dp[i-1][j][0] + 1, dp[i][j][1] + dp[i][j-1][1] + 1) for win in range(min(m, n)-1, -1, -1): # for each window size for i in range(m-win): # for each x-axis for j in range(n-win): # for each y-axis if not grid[i][j]: continue # determine whether square of (i, j), (i+win, j+win) is 1-boarded x1, y1 = dp[i+win][j+win] # bottom-right corner x2, y2 = dp[i][j+win] # upper-right corner x3, y3 = dp[i+win][j] # bottom-left corner x4, y4 = dp[i][j] # upper-left corner if y1 - y3 == x1 - x2 == y2 - y4 == x3 - x4 == win: return (win+1) * (win+1) return 0
largest-1-bordered-square
Python 3 | Prefix-sum, DP, O(N^3) | Explanation
idontknoooo
2
347
largest 1 bordered square
1,139
0.501
Medium
17,739
https://leetcode.com/problems/largest-1-bordered-square/discuss/1187472/python-dp-faster-than-98%2B
class Solution: def largest1BorderedSquare(self, grid: List[List[int]]) -> int: width = len(grid[0]) height = len(grid) dp = [[(0, 0)] * width for x in range(height)] max_len = 0 for i in range(height): for j in range(width): if grid[i][j] == 0: dp[i][j] == (0, 0) else: if max_len == 0: max_len = 1 if i == 0 and j == 0: dp[i][j] = (1, 1) elif i == 0: dp[i][j] = (1, dp[i][j-1][1] + 1) elif j == 0: dp[i][j] = (dp[i-1][j][0] + 1, 1) else: dp[i][j] = (dp[i-1][j][0] + 1, dp[i][j-1][1] + 1) # height and width for k in range(max_len, min(dp[i][j])): # k+1 is side length of the square if dp[i-k][j][1] >= k + 1 and dp[i][j-k][0] >= k + 1: max_len = k+1 #print(dp) return max_len * max_len
largest-1-bordered-square
python, dp, faster than 98+%
dustlihy
2
292
largest 1 bordered square
1,139
0.501
Medium
17,740
https://leetcode.com/problems/largest-1-bordered-square/discuss/2218430/PYTHON-or-EXPLAINED-or-VERY-EASY-or-O(N*M*MAX(N*M))-or-SIMPLE-or
class Solution: def largest1BorderedSquare(self, grid: List[List[int]]) -> int: ans = 0 n,m = len(grid) , len(grid[0]) for sr in range(n): for sc in range(m): er,ec = sr,sc while True: if grid[sr][ec] == 0 or grid[er][sc] == 0: break flag = True for i in range(sr,er+1): if grid[i][ec] == 0: flag = False break if flag == True: for i in range(sc,ec+1): if grid[er][i] == 0: flag = False break if flag == True: size = (er - sr + 1) * (er - sr + 1) if size > ans: ans = size er += 1 ec += 1 if er == n or ec == m: break return ans
largest-1-bordered-square
PYTHON | EXPLAINED | VERY EASY | O(N*M*MAX(N*M)) | SIMPLE |
reaper_27
0
66
largest 1 bordered square
1,139
0.501
Medium
17,741
https://leetcode.com/problems/largest-1-bordered-square/discuss/1168617/Python3-horizontal-and-vertical-precipitation
class Solution: def largest1BorderedSquare(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) # dimensions hori = deepcopy(grid) vert = deepcopy(grid) for i in range(m): for j in range(n): if grid[i][j]: if j: hori[i][j] += hori[i][j-1] # horizontal precipitation if i: vert[i][j] += vert[i-1][j] # vertical precipitation ans = 0 for i in reversed(range(m)): for j in reversed(range(n)): val = min(hori[i][j], vert[i][j]) while val > ans: if vert[i][j-val+1] >= val and hori[i-val+1][j] >= val: ans = val val -= 1 return ans*ans
largest-1-bordered-square
[Python3] horizontal & vertical precipitation
ye15
0
84
largest 1 bordered square
1,139
0.501
Medium
17,742
https://leetcode.com/problems/stone-game-ii/discuss/793881/python-DP-Thought-process-explained
class Solution: def stoneGameII(self, piles: List[int]) -> int: suffix_sum = self._suffix_sum(piles) @lru_cache(None) def dfs(pile: int, M: int, turn: bool) -> Tuple[int, int]: # turn: true - alex, false - lee sum_alex, sum_lee = suffix_sum[pile], suffix_sum[pile] for next_pile in range(pile + 1, min(pile + 2 * M + 1, len(piles) + 1)): sum_alex_next, sum_lee_next = dfs( next_pile, max(M, next_pile - pile), not turn ) range_sum = suffix_sum[pile] - suffix_sum[next_pile] if turn: if sum_lee_next < sum_lee: sum_alex = sum_alex_next + range_sum sum_lee = sum_lee_next else: if sum_alex_next < sum_alex: sum_alex = sum_alex_next sum_lee = sum_lee_next + range_sum return sum_alex, sum_lee return dfs(0, 1, True)[0]
stone-game-ii
[python] DP Thought process explained
omgitspavel
36
1,900
stone game ii
1,140
0.649
Medium
17,743
https://leetcode.com/problems/stone-game-ii/discuss/793881/python-DP-Thought-process-explained
class Solution: def stoneGameII(self, piles: List[int]) -> int: suffix_sum = self._suffix_sum(piles) @lru_cache(None) def dfs(pile: int, M: int) -> int: sum_next_player = suffix_sum[pile] for next_pile in range(pile + 1, min(pile + 2 * M + 1, len(piles) + 1)): sum_next_player = min( sum_next_player, dfs(next_pile, max(M, next_pile - pile)) ) sum_player = suffix_sum[pile] - sum_next_player return sum_player return dfs(0, 1)
stone-game-ii
[python] DP Thought process explained
omgitspavel
36
1,900
stone game ii
1,140
0.649
Medium
17,744
https://leetcode.com/problems/stone-game-ii/discuss/793881/python-DP-Thought-process-explained
class Solution: def stoneGameII(self, piles: List[int]) -> int: suffix_sum = self._suffix_sum(piles) dp = [[0] * (len(piles) + 1) for _ in range(len(piles) + 1)] for pile in reversed(range(len(piles))): for M in reversed(range(len(piles))): sum_next_player = suffix_sum[pile] for next_pile in range(pile + 1, min(pile + 2 * M + 1, len(piles) + 1)): sum_next_player = min( sum_next_player, dp[next_pile][max(M, next_pile - pile)] ) sum_player = suffix_sum[pile] - sum_next_player dp[pile][M] = sum_player return dp[0][1]
stone-game-ii
[python] DP Thought process explained
omgitspavel
36
1,900
stone game ii
1,140
0.649
Medium
17,745
https://leetcode.com/problems/stone-game-ii/discuss/808305/Python-DP-memoization-with-explanation
class Solution: def stoneGameII(self, piles: List[int]) -> int: N = len(piles) self.dp = {} def recursiveStoneGame(start, M): if start >= N: return 0 # take all if possible if N - start <= 2*M: return sum(piles[start:]) # memoization if (start, M) in self.dp: return self.dp[(start, M)] my_score = 0 total_score = sum(piles[start:]) # the opponent can take [1, 2*M] stones for x in range(1, 2*M+1): # get opponent's score opponent_score = recursiveStoneGame(start+x, max(x, M)) # maintains max my_score my_score = max(my_score, total_score - opponent_score) self.dp[(start, M)] = my_score return my_score return recursiveStoneGame(0, 1)
stone-game-ii
[Python] DP memoization with explanation
xjiang2020
15
934
stone game ii
1,140
0.649
Medium
17,746
https://leetcode.com/problems/stone-game-ii/discuss/851536/beat-100-intuitive-code-with-explanation
class Solution: def stoneGameII(self, piles): # accumulated sum table of the rest of all stores reversely for quick check a = [*accumulate(piles[::-1])][::-1] # dp cache @lru_cache(None) def game(i, m): # i: current index, m: current maximal move # if player's move can arrive goal, get all rest stones if i + 2 * m >= len(piles): return a[i] # otherwise, # the rest of all stones must subtract rival's minimum # _minScore: rival's minimum _minScore = 2**31 - 1 # find which move can get maximum # x: how many moves for x in range(1, 2 * m + 1): # get rival's score score = game(i + x, x) if x > m else game(i + x, m) # update rival's new minimum if score < _minScore: _minScore = score # the rest of all stores of current position # subtract rival's minimum to get best result return a[i] - _minScore return game(0, 1)
stone-game-ii
beat 100%, intuitive code with explanation
MarcoChang
5
755
stone game ii
1,140
0.649
Medium
17,747
https://leetcode.com/problems/stone-game-ii/discuss/485246/RZ-Top-down-solution-from-top-voted-solution-and-corresponding-bottom-up-solution-in-Python
class Solution: def stoneGameII(self, piles: List[int]) -> int: if not piles: return 0 n = len(piles) postSum = [0] * n postSum[n - 1] = piles[n - 1] for i in range(n - 2, -1, -1): postSum[i] = postSum[i + 1] + piles[i] return self.helper(0, 1, postSum, {}) def helper(self, start, M, postSum, cache): if (start, M) in cache: return cache[(start, M)] n = len(postSum) if start >= n: return 0 if n - start <= 2 * M: return postSum[start] minNext = float('inf') for x in range(1, 2 * M + 1): minNext = min(minNext, self.helper(start + x, max(M, x), postSum, cache)) res = postSum[start] - minNext cache[(start, M)] = res return res
stone-game-ii
[RZ] Top down solution from top voted solution and corresponding bottom up solution in Python
theflyingemini
3
629
stone game ii
1,140
0.649
Medium
17,748
https://leetcode.com/problems/stone-game-ii/discuss/485246/RZ-Top-down-solution-from-top-voted-solution-and-corresponding-bottom-up-solution-in-Python
class Solution: def stoneGameII(self, piles: List[int]) -> int: if not piles: return 0 n = len(piles) postSum = [0] * n postSum[n - 1] = piles[n - 1] for i in range(n - 2, -1, -1): postSum[i] = postSum[i + 1] + piles[i] f = [[0 for _ in range(n)] for _ in range(n)] for i in range(n - 1, -1, -1): for m in range(1, n): if n - i <= 2 * m: f[i][m] = postSum[i] continue minNext = float('inf') for x in range(1, 2 * m + 1): minNext = min(minNext, f[i + x][max(m, x)]) f[i][m] = postSum[i] - minNext return f[0][1]
stone-game-ii
[RZ] Top down solution from top voted solution and corresponding bottom up solution in Python
theflyingemini
3
629
stone game ii
1,140
0.649
Medium
17,749
https://leetcode.com/problems/stone-game-ii/discuss/2223050/PYTHON-or-WELL-WRITTEN-or-COMMENT-%2B-EXPLANATION-or-DP-or-EASY-or
class Solution: def stoneGameII(self, piles: List[int]) -> int: n = len(piles) dp = {} def recursion(index,M): # if we reached to the end we cannot score any value if index == n: return 0 # we search if we have solved the same case earlier if (index,M) in dp: return dp[(index,M)] # total remaining score is the sum of array from index to the end total = sum(piles[index:]) # if we can take the complete array it is the best choice if index + 2*M >= n :return total # my_score is the score we are getting as the player who is playing my_score = 0 for x in range(index,index+2*M): # opponent score will be calculated by next recursion opponent_score = recursion(x+1,max(M,x-index+1)) # my_score is the remaining value of total - opponent_score my_score = max(my_score,total - opponent_score) # this is memoization part dp[(index,M)] = my_score # return the score return my_score return recursion(0,1)
stone-game-ii
PYTHON | WELL WRITTEN | COMMENT + EXPLANATION | DP | EASY |
reaper_27
1
126
stone game ii
1,140
0.649
Medium
17,750
https://leetcode.com/problems/stone-game-ii/discuss/1331567/Intuitive-DFS-DP-with-and-without-bool-flag-for-current-player-optimal-strategy-of-min-max
class Solution: def stoneGameII(self, piles: List[int]) -> int: @functools.cache def dp(l, m, i_am_alice): # lets return alice count if l == len(piles): return 0 left = [] taking_now = 0 for x in range(2*m): if l+x == len(piles): break if i_am_alice: taking_now += piles[l+x] taking_later = dp(l+x+1, max(m,x+1), not i_am_alice) left.append(taking_now + taking_later) if i_am_alice: # i want to maximize alice return max(left) else: # i am bob, want to minimize alice return min(left) return dp(0,1,True)
stone-game-ii
Intuitive DFS DP with & without bool flag for current player, optimal strategy of min max
yozaam
0
276
stone game ii
1,140
0.649
Medium
17,751
https://leetcode.com/problems/longest-common-subsequence/discuss/2331817/Python3-or-Java-or-C%2B%2B-or-DP-or-O(nm)-or-BottomUp-(Tabulation)
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: dp = [] # Fill the matrix for _ in range(len(text1)+1): row = [] for _ in range(len(text2)+1): row.append(0) dp.append(row) longest_length = 0 # Start looping throught the text1 and text2 for i in range(1, len(text1)+1): for j in range(1, len(text2)+1): # If characters match # fill the current cell by adding one to the diagonal value if text1[i-1] == text2[j-1]: dp[i][j] = dp[i-1][j-1] + 1 else: # If characters do not match # Fill the cell with max value of previous row and column dp[i][j] = max(dp[i-1][j], dp[i][j-1]) # Keep track of the MAXIMUM value in the matrix longest_length = max(longest_length, dp[i][j]) return longest_length
longest-common-subsequence
Python3 | Java | C++ | DP | O(nm) | BottomUp (Tabulation)
khaydaraliev99
10
488
longest common subsequence
1,143
0.588
Medium
17,752
https://leetcode.com/problems/longest-common-subsequence/discuss/2041271/Python-or-DP-or-5-Approaches-or
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: n = len(text1) m = len(text2) dp = [[-1 for i in range(m+1)] for i in range(n+1)] for j in range(m+1): dp[0][j] = 0 for i in range(n+1): dp[i][0] = 0 for ind1 in range(1,n+1): for ind2 in range(1,m+1): if(text1[ind1-1] == text2[ind2-1]): dp[ind1][ind2] = 1 + dp[ind1-1][ind2-1] else: dp[ind1][ind2] = max(dp[ind1-1][ind2],dp[ind1][ind2-1]) return dp[n][m]
longest-common-subsequence
Python | DP | 5 Approaches |
LittleMonster23
9
526
longest common subsequence
1,143
0.588
Medium
17,753
https://leetcode.com/problems/longest-common-subsequence/discuss/2041271/Python-or-DP-or-5-Approaches-or
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: n = len(text1) m = len(text2) prev = [0 for i in range(m+1)] cur = [0 for i in range(m+1)] for ind1 in range(1,n+1): for ind2 in range(1,m+1): if(text1[ind1-1] == text2[ind2-1]): cur[ind2] = 1 + prev[ind2-1] else: cur[ind2] = max(prev[ind2],cur[ind2-1]) prev = [x for x in cur] return prev[m]
longest-common-subsequence
Python | DP | 5 Approaches |
LittleMonster23
9
526
longest common subsequence
1,143
0.588
Medium
17,754
https://leetcode.com/problems/longest-common-subsequence/discuss/598687/PythonJSC%2B%2B-O(-m*n-)-2D-DP.-w-Hint
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: # padding one space for empty string representation text1 = ' ' + text1 text2 = ' ' + text2 w, h = len(text1), len(text2) dp_table = [ [ 0 for x in range(w) ] for y in range(h) ] # update dynamic programming table with optimal substructure for y in range(1, h): for x in range(1, w): if text1[x] == text2[y]: # with the same character # extend the length of common subsequence dp_table[y][x] = dp_table[y-1][x-1] + 1 else: # with different characters # choose the optimal subsequence dp_table[y][x] = max( dp_table[y-1][x], dp_table[y][x-1] ) return dp_table[-1][-1]
longest-common-subsequence
Python/JS/C++ O( m*n ) 2D DP. [w/ Hint]
brianchiang_tw
7
1,300
longest common subsequence
1,143
0.588
Medium
17,755
https://leetcode.com/problems/longest-common-subsequence/discuss/598687/PythonJSC%2B%2B-O(-m*n-)-2D-DP.-w-Hint
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: @cache def dp(i, j): if i == -1 or j == -1: # Any string compare to empty string has no common sequence return 0 elif text1[i] == text2[j]: # Current character is the same return dp(i-1, j-1) + 1 else: # Current characters are different return max( dp(i-1, j), dp(i, j-1) ) # ------------------------------------------------- return dp( len(text1)-1, len(text2)-1 )
longest-common-subsequence
Python/JS/C++ O( m*n ) 2D DP. [w/ Hint]
brianchiang_tw
7
1,300
longest common subsequence
1,143
0.588
Medium
17,756
https://leetcode.com/problems/longest-common-subsequence/discuss/534345/Python3-top-down-and-bottom-up-dp
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: m, n = len(text1), len(text2) dp = [[0]*(n+1) for _ in range(m+1)] for i in range(m-1, -1, -1): for j in range(n-1, -1, -1): if text1[i] == text2[j]: dp[i][j] = 1 + dp[i+1][j+1] else: dp[i][j] = max(dp[i+1][j], dp[i][j+1]) return dp[0][0]
longest-common-subsequence
[Python3] top-down & bottom-up dp
ye15
3
233
longest common subsequence
1,143
0.588
Medium
17,757
https://leetcode.com/problems/longest-common-subsequence/discuss/534345/Python3-top-down-and-bottom-up-dp
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: m, n = len(text1), len(text2) ans = [0]*(n+1) for i in range(m): tmp = ans.copy() for j in range(n): if text1[i] == text2[j]: ans[j+1] = 1 + tmp[j] else: ans[j+1] = max(tmp[j+1], ans[j]) return ans[-1]
longest-common-subsequence
[Python3] top-down & bottom-up dp
ye15
3
233
longest common subsequence
1,143
0.588
Medium
17,758
https://leetcode.com/problems/longest-common-subsequence/discuss/534345/Python3-top-down-and-bottom-up-dp
class Solution: def longestPalindromeSubseq(self, s: str) -> int: @lru_cache(None) def lcs(i, j): """Return longest common subsequence of text1[i:] and text2[j:].""" if i == len(s) or j == len(s): return 0 if s[i] == s[~j]: return 1 + lcs(i+1, j+1) else: return max(lcs(i+1, j), lcs(i, j+1)) return lcs(0, 0)
longest-common-subsequence
[Python3] top-down & bottom-up dp
ye15
3
233
longest common subsequence
1,143
0.588
Medium
17,759
https://leetcode.com/problems/longest-common-subsequence/discuss/534345/Python3-top-down-and-bottom-up-dp
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: m, n = len(text1), len(text2) dp = [0]*(n+1) for i in reversed(range(m)): prev = curr = 0 for j in reversed(range(n)): curr = dp[j] if text1[i] == text2[j]: dp[j] = 1 + prev else: dp[j] = max(dp[j], dp[j+1]) prev = curr return dp[0]
longest-common-subsequence
[Python3] top-down & bottom-up dp
ye15
3
233
longest common subsequence
1,143
0.588
Medium
17,760
https://leetcode.com/problems/longest-common-subsequence/discuss/2074674/100-or-LIS-or-Python3-or-Avg-nlogn
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: text1_dict = defaultdict(deque) for idx1, char1 in enumerate(text1): if char1 in set(text2): text1_dict[char1].appendleft(idx1) # print(text1_dict) # defaultdict(<class 'collections.deque'>, {'a': deque([5, 0]), 'b': deque([1]), 'c': deque([2]), 'e': deque([3])}) nums = [] for char2 in text2: if char2 in text1_set: nums = nums + list(text1_dict[char2]) # print(nums) # [1, 5, 0, 3, 3, 2, 5, 0] or think as [1] + [5, 0] + [3] + [3] + [2] + [5, 0] lis = [] for num in nums: insert_index = bisect_left(lis, num) if insert_index == len(lis): lis.append(num) else: lis[insert_index] = num # print(lis) # [0, 2, 5] or thinik as [0, 3, 5] return len(lis)
longest-common-subsequence
100% | LIS | Python3 | Avg nlogn
yzhao156
2
58
longest common subsequence
1,143
0.588
Medium
17,761
https://leetcode.com/problems/longest-common-subsequence/discuss/2074674/100-or-LIS-or-Python3-or-Avg-nlogn
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: text1_dict, nums, lis = defaultdict(deque), [], [] for idx1, char1 in enumerate(text1): if char1 in set(text2): text1_dict[char1].appendleft(idx1) for char2 in text2: if char2 in set(text1): nums = nums + list(text1_dict[char2]) for num in nums: insert_index = bisect_left(lis, num) if insert_index == len(lis): lis.append(num) else: lis[insert_index] = num return len(lis)
longest-common-subsequence
100% | LIS | Python3 | Avg nlogn
yzhao156
2
58
longest common subsequence
1,143
0.588
Medium
17,762
https://leetcode.com/problems/longest-common-subsequence/discuss/2342233/python3-EASY-FAST-6-Line-Sol
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: dp = [[0 for j in range(len(text2) + 1)] for i in range(len(text1) + 1)] for i in range(len(text1) - 1, -1, -1): for j in range(len(text2) - 1, -1, -1): if text1[i] == text2[j]: dp[i][j] = 1 + dp[i + 1][j + 1] else: dp[i][j] = max(dp[i + 1][j], dp[i][j + 1]) return dp[0][0]
longest-common-subsequence
python3 EASY FAST 6 Line Sol
soumyadexter7
1
155
longest common subsequence
1,143
0.588
Medium
17,763
https://leetcode.com/problems/longest-common-subsequence/discuss/2049815/Python-DP-Solution
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: n, m = len(text1), len(text2) dp = [[0 for i in range(1 + m)] for j in range(1 + n)] for i in range(1, n + 1): for j in range(1, m + 1): if text1[i-1] == text2[j-1]: dp[i][j] = 1 + dp[i-1][j-1] dp[i][j] = max(dp[i][j], dp[i-1][j], dp[i][j-1]) return dp[n][m]
longest-common-subsequence
Python DP Solution
dbansal18
1
51
longest common subsequence
1,143
0.588
Medium
17,764
https://leetcode.com/problems/longest-common-subsequence/discuss/2029014/Pythonor-Easy-DPor-Bottom-Up-Approach
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: dp = [[0 for j in range(len(text2) + 1)] for i in range(len(text1) + 1)] for i in range(len(text1) - 1, -1, -1): for j in range(len(text2) - 1, -1, -1): if text1[i] == text2[j]: dp[i][j] = 1 + dp[i + 1][j + 1] else: dp[i][j] = max(dp[i][j + 1], dp[i + 1][j]) return dp[0][0]
longest-common-subsequence
Python| Easy DP| Bottom Up Approach
shikha_pandey
1
147
longest common subsequence
1,143
0.588
Medium
17,765
https://leetcode.com/problems/longest-common-subsequence/discuss/1813374/Python-easy-to-read-and-understand-or-DP
class Solution: def lcs(self, a, b): M, N = len(a), len(b) t = [[0 for _ in range(N+1)] for _ in range(M+1)] for m in range(1, M+1): for n in range(1, N+1): if a[m-1] == b[n-1]: t[m][n] = 1 + t[m-1][n-1] else: t[m][n] = max(t[m][n-1], t[m-1][n]) return t[M][N] def longestCommonSubsequence(self, text1: str, text2: str) -> int: return self.lcs(text1, text2)
longest-common-subsequence
Python easy to read and understand | DP
sanial2001
1
245
longest common subsequence
1,143
0.588
Medium
17,766
https://leetcode.com/problems/longest-common-subsequence/discuss/1792110/Python-Brute-Force-Top-Down-(Memo)-and-Bottom-Up-(DP)
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: # Brute Force # Time: O(2^(t1+t2), Space: O(t1+t2) return self.lcsBruteForce(text1, text2, 0, 0) # Top-Down # Time: O(t1*t2, Space: O(t1*t2) memo = [[0 for _ in range(len(text2))] for _ in range(len(text1))] return self.lcsTopDown(memo, text1, text2, 0, 0) # Bottom-Up # Time: O(t1*t2), Space: O(t1*t2) dp = [[0 for _ in range(len(text2) + 1)] for _ in range(len(text1) + 1)] return self.lcsBottomUp(dp, text1, text2, 0, 0) def lcsBruteForce(self, text1, text2, i1, i2): # If we've reached the end of a string, then terminate early if i1 >= len(text1) or i2 >= len(text2): return 0 # If chars match, then add once since we claim that char for LCS and advance both indices if text1[i1] == text2[i2]: return 1 + self.lcsBruteForce(text1, text2, i1 + 1, i2 + 1) # If chars differ, then try advancing both indices separately and get the max result from both lcs1 = self.lcsBruteForce(text1, text2, i1 + 1, i2) lcs2 = self.lcsBruteForce(text1, text2, i1, i2 + 1) return max(lcs1, lcs2) def lcsTopDown(self, memo, text1, text2, i1, i2): if i1 >= len(text1) or i2 >= len(text2): return 0 if memo[i1][i2] == 0: if text1[i1] == text2[i2]: return 1 + self.lcsTopDown(memo, text1, text2, i1 + 1, i2 + 1) lcs1 = self.lcsTopDown(memo, text1, text2, i1 + 1, i2) lcs2 = self.lcsTopDown(memo, text1, text2, i1, i2 + 1) memo[i1][i2] = max(lcs1, lcs2) return memo[i1][i2] def lcsBottomUp(self, dp, text1, text2, i1, i2): for i in range(1, len(text1) + 1): for j in range(1, len(text2) + 1): if text1[i-1] == text2[j-1]: # Text indices are offset from DP indices because of row and col of zeroes in DP matrix dp[i][j] = 1 + dp[i-1][j-1] else: dp[i][j] = max(dp[i-1][j], dp[i][j-1]) return dp[len(text1)][len(text2)]
longest-common-subsequence
Python Brute Force, Top-Down (Memo), and Bottom-Up (DP)
doubleimpostor
1
201
longest common subsequence
1,143
0.588
Medium
17,767
https://leetcode.com/problems/longest-common-subsequence/discuss/1633349/Python3-top-down-DP-with-%40cache-cheating.
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: # obviously it has to be common tldr exist in both text1 and text2 so already the length can eliminate all the non matching # then from there, you need it in the same relative order. # longest, max etc. dp?? # the next longest is dependent on the previous longest # if you imagine as graph each "longer" path is reliant on subsequent so dp makes sense here.. # time complexity? M indices in total for text1, N for text2. total with caching is just M*N from functools import cache @cache def dp(i, j): if i == len(text1) or j == len(text2): return 0 # if there is a match, then you add 1 to the path (imagine graph) if text1[i] == text2[j]: res = 1 + dp(i + 1, j + 1) else: # if there is no match then you have two paths, where you move i+1 and j stays same or oyu move j+1 and i stays same res = max(dp(i + 1, j), dp(i, j + 1)) return res return dp(0, 0)
longest-common-subsequence
Python3 top down DP with @cache cheating.
normalpersontryingtopayrent
1
87
longest common subsequence
1,143
0.588
Medium
17,768
https://leetcode.com/problems/longest-common-subsequence/discuss/1463354/PyPy3-Solution-with-memoization-w-comments
class Solution: def longestCommonSubsequence(self, x: str, y: str) -> int: # Recursive solution with memoization def lcs(n: int, m: int, t=dict()) -> int: # Base Conidtion: If any of the string # empty the lenght of longest common # subsequence is 0 if n==0 or m==0: return 0 else: # Memoize overlapping problems key = (n,m) if key not in t: # If elements at current indexes in x and y # matches, add 1 to the the count and call # lcs on smaller version of both the string # w/o the element compared if x[n-1] == y[m-1]: t[key] = lcs(n-1,m-1,t) + 1 # If elements at current indexes in x and y # doesn't match, call lcs on one element less # of either of the strings, and take the max # of both the options else: t[key] = max(lcs(n,m-1,t), lcs(n-1,m,t)) return t[key] # return currrent key return lcs(len(x), len(y))
longest-common-subsequence
[Py/Py3] Solution with memoization w/ comments
ssshukla26
1
184
longest common subsequence
1,143
0.588
Medium
17,769
https://leetcode.com/problems/longest-common-subsequence/discuss/929510/Python3-Longest-Common-Subsequence.-**All-3-concepts-Easy-Code**
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: return self.commonLen(text1,text2,len(text1),len(text2)) def commonLen(self,x,y,n,m): if n==0 or m==0: return 0 if x[n-1] == y[m-1]: return 1 + self.commonLen(x,y,n-1,m-1) else: return max(self.commonLen(x,y,n,m-1), self.commonLen(x,y,n-1,m))
longest-common-subsequence
[Python3] Longest Common Subsequence. **All 3 concepts Easy Code**
tilak_
1
208
longest common subsequence
1,143
0.588
Medium
17,770
https://leetcode.com/problems/longest-common-subsequence/discuss/929510/Python3-Longest-Common-Subsequence.-**All-3-concepts-Easy-Code**
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: return self.commonLen(text1,text2,len(text1),len(text2)) def commonLen(self,x,y,n,m): dp = [[-1]*(m+1) for i in range(n+1)] if n==0 or m==0: return 0 if dp[n][m]!=-1: return dp[n][m] if x[n-1] == y[m-1]: return dp[n][m] = 1 + self.commonLen(x,y,n-1,m-1) else: return dp[n][m] = max(self.commonLen(x,y,n,m-1), self.commonLen(x,y,n-1,m))
longest-common-subsequence
[Python3] Longest Common Subsequence. **All 3 concepts Easy Code**
tilak_
1
208
longest common subsequence
1,143
0.588
Medium
17,771
https://leetcode.com/problems/longest-common-subsequence/discuss/929510/Python3-Longest-Common-Subsequence.-**All-3-concepts-Easy-Code**
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: return self.commonLen(text1,text2,len(text1),len(text2)) def commonLen(self,x,y,n,m): dp = [[-1]*(m+1) for i in range(n+1)] for i in range(n+1): for j in range(m+1): if i==0 or j==0: dp[i][j] = 0 for i in range(1,n+1): for j in range(1,m+1): if x[i-1] == y[j-1]: dp[i][j] = 1 + dp[i-1][j-1] else: dp[i][j] = max(dp[i-1][j], dp[i][j-1]) return dp[n][m]
longest-common-subsequence
[Python3] Longest Common Subsequence. **All 3 concepts Easy Code**
tilak_
1
208
longest common subsequence
1,143
0.588
Medium
17,772
https://leetcode.com/problems/longest-common-subsequence/discuss/624707/Simple-DP-Solution-Python
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: if text1==text2: return len(text1) dp=[] for i in range(len(text1)+1): x=[] for j in range(len(text2)+1): x.append(0) dp.append(x) for i in range(len(text2)+1): dp[0][i]=0 for i in range(len(text1)+1): dp[i][0]=0 maxv=0 for i in range(len(text1)): for j in range(len(text2)): if text1[i]==text2[j]: dp[i][j]=dp[i-1][j-1]+1 else: dp[i][j]=max(dp[i][j-1], dp[i-1][j]) if dp[i][j]>maxv: maxv=dp[i][j] return maxv
longest-common-subsequence
Simple DP Solution Python
Ayu-99
1
89
longest common subsequence
1,143
0.588
Medium
17,773
https://leetcode.com/problems/longest-common-subsequence/discuss/580183/DP-with-Space-Optimization-(Beats-99.5-in-Time-100-in-Space)
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: if len(text1) < len(text2): text1, text2 = text2, text1 n, m = len(text1), len(text2) table = [0] * (m + 1) prev_table = [0] * (m + 1) for c1 in text1: for i, c2 in enumerate(text2): table[i + 1] = max(prev_table[i] + 1 if c1 == c2 else prev_table[i + 1], table[i]) table, prev_table = prev_table, table return prev_table[-1]
longest-common-subsequence
DP with Space Optimization (Beats 99.5% in Time, 100% in Space)
skarakulak
1
377
longest common subsequence
1,143
0.588
Medium
17,774
https://leetcode.com/problems/longest-common-subsequence/discuss/2820313/Python-Solution-Memoization-or-Tabulation
class Solution: #Memoization #Time complexity: O(N*M) #Space complexity: O(N*M) + O(N+M) def helper(self,ind1,ind2,text1,text2,dp): if ind1<0 or ind2<0: return 0 if dp[ind1][ind2]!=-1: return dp[ind1][ind2] if text1[ind1]==text2[ind2]: dp[ind1][ind2] = 1+self.helper(ind1-1,ind2-1,text1,text2,dp) return dp[ind1][ind2] else: dp[ind1][ind2] = max(self.helper(ind1-1,ind2,text1,text2,dp),self.helper(ind1,ind2-1,text1,text2,dp)) return dp[ind1][ind2] def longestCommonSubsequence(self, text1: str, text2: str) -> int: m = len(text1) n = len(text2) dp = [[-1]*(n) for i in range(m+1)] print(dp) return self.helper(m-1,n-1,text1,text2,dp)
longest-common-subsequence
Python Solution - Memoization | Tabulation
ankitabudhia42
0
1
longest common subsequence
1,143
0.588
Medium
17,775
https://leetcode.com/problems/longest-common-subsequence/discuss/2820313/Python-Solution-Memoization-or-Tabulation
class Solution: def longestCommonSubsequence(self, s: str, t: str) -> int: l1 = len(s) l2 = len(t) dp = [[-1]*(l2+1) for i in range(l1+2)] for i in range(l1+1): dp[i][0]=0 for j in range(l2+1): dp[0][j]=0 for i in range(1,l1+1): for j in range(1,l2+1): if s[i-1]==t[j-1]: dp[i][j] = 1+ dp[i-1][j-1] else: dp[i][j]= max(dp[i-1][j],dp[i][j-1]) return dp[l1][l2]
longest-common-subsequence
Python Solution - Memoization | Tabulation
ankitabudhia42
0
1
longest common subsequence
1,143
0.588
Medium
17,776
https://leetcode.com/problems/longest-common-subsequence/discuss/2778769/python-%2B-DP-%2B-O(n*m)
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: n = len(text1) m = len(text2) temp = [[0 for i in range(m+1)] for j in range(n+1)] for i in range(1, n+1): for j in range(1, m+1): if text1[i-1]== text2[j-1]: temp[i][j] = 1+temp[i-1][j-1] else: temp[i][j] = max(temp[i-1][j], temp[i-1][j-1], temp[i][j-1]) return temp[-1][-1]
longest-common-subsequence
python + DP + O(n*m)
surajsoni
0
4
longest common subsequence
1,143
0.588
Medium
17,777
https://leetcode.com/problems/longest-common-subsequence/discuss/2773415/python-soln-using-tabulation-method
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: m=len(text1) n=len(text2) dp=[[-1]*(n+1) for _ in range(m+1)] for i in range(m+1): for j in range(n+1): if i==0 or j==0: dp[i][j]=0 elif text1[i-1]==text2[j-1]: dp[i][j]=1+dp[i-1][j-1] else: dp[i][j]=max(dp[i][j-1],dp[i-1][j]) return dp[m][n]
longest-common-subsequence
python soln using tabulation method
Nischay_2003
0
2
longest common subsequence
1,143
0.588
Medium
17,778
https://leetcode.com/problems/longest-common-subsequence/discuss/2767182/Longest-Common-Subsequence-oror-Python3-ororDP
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: dp=[[-1 for i in range(len(text2)+1)]for j in range(len(text1)+1)] m=len(text1) n=len(text2) return lcs(dp,text1,text2,m,n) def lcs(dp,s1,s2,m,n): if m==0 or n==0: dp[m][n]=0 return dp[m][n] elif s1[m-1]==s2[n-1]: if dp[m][n]!=-1: return dp[m][n] dp[m][n]=1+lcs(dp,s1,s2,m-1,n-1) return dp[m][n] else: if dp[m][n]!=-1: return dp[m][n] dp[m][n]=max(lcs(dp,s1,s2,m-1,n),lcs(dp,s1,s2,m,n-1)) return dp[m][n]
longest-common-subsequence
Longest Common Subsequence || Python3 ||DP
shagun_pandey
0
5
longest common subsequence
1,143
0.588
Medium
17,779
https://leetcode.com/problems/longest-common-subsequence/discuss/2762985/Python%3A-DP(matrix)-%2B-Memoization-technique-oror-Recurrsive-Approach
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: m=len(text1) n=len(text2) dp=[[-1 for i in range(n)] for j in range(m)] def lcs(m,n): if m<0 or n<0: return 0 if dp[m][n]!=-1: return dp[m][n] if text1[m]==text2[n]: dp[m][n]=1+lcs(m-1,n-1) return dp[m][n] dp[m][n]=max(lcs(m-1,n),lcs(m,n-1)) return dp[m][n] return lcs(m-1,n-1)
longest-common-subsequence
Python: DP(matrix) + Memoization technique || Recurrsive Approach
utsa_gupta
0
9
longest common subsequence
1,143
0.588
Medium
17,780
https://leetcode.com/problems/longest-common-subsequence/discuss/2762258/A-clean-efficient-DP-python-solution-that-beats-90.78-runtime-and-88.88-memory
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: rows = len(text1) cols = len(text2) memo = [[None] * (cols + 1) for i in range((rows + 1))] # type: List[List[Optional[int]]] for row in range(rows + 1): for col in range(cols + 1): if row == 0 or col == 0: memo[row][col] = 0 elif text1[row - 1] == text2[col - 1]: memo[row][col] = memo[row - 1][col - 1] + 1 else: memo[row][col] = max(memo[row - 1][col], memo[row][col - 1]) return memo[rows][cols]
longest-common-subsequence
A clean efficient DP python solution that beats 90.78% runtime and 88.88% memory
myaser
0
2
longest common subsequence
1,143
0.588
Medium
17,781
https://leetcode.com/problems/longest-common-subsequence/discuss/2739389/Python3-or-Solved-Using-Top-Down-DP-%2B-Memoization
class Solution: #Time-Complexity: O(2^min(length1, length2)), since branching factor in worst case is 2 where #two compared characters do not match and longest path from root to leaf in rec. tree is #of length min(length1, length2), since either i or j will hit length1 or length2 to go #out of bounds index pos! #Space-Complexity: O(min(length1, length2) + length1 * length2), accounting for #max stack depth due to recursion and size of memo array respectively! def longestCommonSubsequence(self, text1: str, text2: str) -> int: length1, length2 = len(text1), len(text2) #I will solve this top down approach! #For 2-D dp, I will use two state parameters, i and j, which points to index position of current #character onwards of two substrings of two text inputs, text1 and text2, I am considering. #For every state (i, j), I will solve the subproblem needed which would find length of LCS between #text1[i: ] and text2[j:]! #Two cases #1. The ith and jth character match! Length of LCS is 1 + LCS(text1[i+1:], text2[j+1:]). #2. They don't match! We compare length of 2 subproblem answers between LCS(text1[i:], text2[j+1:]) and #LCS(text1[i+1:], text2[j:]). #Base Cases: #1. We know that empty string LCS with anything is 0 -> We'll use this to initialize memo! #2. Memoization base case: avoid recomputing already solved subproblems and simply refer to memo! memo = [[-1 for a in range(length2)] for b in range(length1)] #define a recursive helper function that will fill in memo as top-down dp proceeds! def helper(i, j): nonlocal text1, text2, memo #if either index pos. is out of bounds, return default value 0! if(i >= length1 or j >= length2): return 0 #base case: if state is already solved, refer to it! if(memo[i][j] != -1): return memo[i][j] #if not already solved, recurse further! #first, check index ith character of text1 and index jth character of text2! if(text1[i] == text2[j]): memo[i][j] = 1 + helper(i+1, j+1) else: result = max(helper(i, j+1), helper(i+1, j)) memo[i][j] = result return memo[i][j] return helper(0, 0)
longest-common-subsequence
Python3 | Solved Using Top-Down DP + Memoization
JOON1234
0
3
longest common subsequence
1,143
0.588
Medium
17,782
https://leetcode.com/problems/longest-common-subsequence/discuss/2737547/Python3-Straightforward-2D-DP-(with-comments)
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: dp = [[0] * (len(text2)+1) for _ in range(len(text1)+1)] for i in range(len(text1)-1, -1, -1): for j in range(len(text2)-1, -1, -1): if text1[i] == text2[j]: # match, increase LCS dp[i][j] = dp[i+1][j+1]+1 else: # no match, use prev result and move to next letter dp[i][j] = max(dp[i+1][j], dp[i][j+1]) return dp[0][0]
longest-common-subsequence
Python3 Straightforward 2D DP (with comments)
jonathanbrophy47
0
3
longest common subsequence
1,143
0.588
Medium
17,783
https://leetcode.com/problems/longest-common-subsequence/discuss/2730174/python-dp-top-down-easy-and-short-solution
class Solution: t1,t2=None,None @cache def dynamic(self,i,j): if i >= len(self.t1) or j >= len(self.t2): return 0 if self.t1[i] == self.t2[j]: return 1 + self.dynamic(i+1, j+1) return max(self.dynamic(i+1,j), self.dynamic(i,j+1)) def longestCommonSubsequence(self, text1: str, text2: str) -> int: self.t1,self.t2 = text1, text2 return self.dynamic(0,0)
longest-common-subsequence
python dp top down easy and short solution
benon
0
9
longest common subsequence
1,143
0.588
Medium
17,784
https://leetcode.com/problems/longest-common-subsequence/discuss/2728201/PYTHON-SOLUTION-LCS
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: def f(ind1,ind2,dp): if ind1<0 or ind2<0: return 0 if dp[ind1][ind2]!=-1: return dp[ind1][ind2] if text1[ind1]==text2[ind2]: dp[ind1][ind2]=1+f(ind1-1,ind2-1,dp) return dp[ind1][ind2] else: dp[ind1][ind2]= max(f(ind1-1,ind2,dp),f(ind1,ind2-1,dp)) return dp[ind1][ind2] m,n=len(text1),len(text2) dp=[[-1 for _ in range(n+1)]for _ in range(m+1)] return f(m-1,n-1,dp)
longest-common-subsequence
PYTHON SOLUTION LCS
shashank_2000
0
7
longest common subsequence
1,143
0.588
Medium
17,785
https://leetcode.com/problems/longest-common-subsequence/discuss/2673141/python-easy-solution-using-DP-bottom-up-approach
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: m=len(text1) n=len(text2) dp=[] for i in range (m+1): dp.append([0]*(n+1)) for i in range (1,m+1): for j in range (1,n+1): if text1[i-1]==text2[j-1]: dp[i][j]=1+dp[i-1][j-1] else: dp[i][j]=max(dp[i-1][j],dp[i][j-1]) return dp[-1][-1]
longest-common-subsequence
python easy solution using DP bottom up approach
tush18
0
81
longest common subsequence
1,143
0.588
Medium
17,786
https://leetcode.com/problems/longest-common-subsequence/discuss/2668012/Python-Accepted
class Solution: def longestCommonSubsequence(self, t1: str, t2: str) -> int: matrix = [[0 for j in range(len(t2)+1)] for i in range(len(t1)+1)] for i in range(len(t1)-1, -1, -1): for j in range(len(t2)-1, -1, -1): if t1[i]==t2[j]: matrix[i][j] = 1 + matrix[i+1][j+1] else: matrix[i][j] = max(matrix[i][j+1],matrix[i+1][j]) return matrix[0][0]
longest-common-subsequence
Python Accepted ✅
Khacker
0
35
longest common subsequence
1,143
0.588
Medium
17,787
https://leetcode.com/problems/longest-common-subsequence/discuss/2588160/nlogn-solution-can-anyone-explain
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: text1_dict, nums, lis = defaultdict(list), [], [] text1_set, text2_set = set(text1), set(text2) for idx1, char1 in enumerate(text1): if char1 in text2_set: text1_dict[char1].append(idx1) for char2 in text2: if char2 in text1_set: for num in reversed(text1_dict[char2]): nums.append(num) for num in nums: insert_index = bisect_left(lis, num) if insert_index == len(lis): lis.append(num) else: lis[insert_index] = num return len(lis) ```
longest-common-subsequence
nlogn solution, can anyone explain?
yzhao156
0
15
longest common subsequence
1,143
0.588
Medium
17,788
https://leetcode.com/problems/longest-common-subsequence/discuss/2395873/Weird-issue-with-dp-list-and-list-comprehension
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: useListComprehension=True cache = [[-1 for i in range(len(text2))] for i in range(len(text1))] if useListComprehension else [[-1]*(len(text2))]*(len(text1)) return self.solve(text1,text2, 0, 0, 0, cache) def solve(self, text1, text2, l, r, res, cache): if (l==len(text1) or r==len(text2)): return 0 if (cache[l][r]>-1): return cache[l][r] res = 0 if(text1[l]==text2[r]): res = 1+self.solve(text1,text2,l+1,r+1,res+1, cache) else: res = max(self.solve(text1,text2,l+1,r,res, cache), self.solve(text1,text2,l,r+1,res, cache)) cache[l][r] = res return res
longest-common-subsequence
Weird issue with dp list and list comprehension
shane911
0
10
longest common subsequence
1,143
0.588
Medium
17,789
https://leetcode.com/problems/longest-common-subsequence/discuss/2305677/Python3-Solution-with-using-dp
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: dp = [[0] * (len(text2) + 1) for _ in range(len(text1) + 1)] for i in range(1, len(text1) + 1): for j in range(1, len(text2) + 1): if text1[i - 1] == text2[j - 1]: dp[i][j] = dp[i - 1][j - 1] + 1 else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) return dp[-1][-1]
longest-common-subsequence
[Python3] Solution with using dp
maosipov11
0
41
longest common subsequence
1,143
0.588
Medium
17,790
https://leetcode.com/problems/longest-common-subsequence/discuss/2267683/Python-DP-with-full-working-explanation
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: # Time: O(m * n) and Space: O(m * n) # creating a 2D array with text1+1 rows and text2+1 columns filled with 0 dp = [[0] * (len(text2) + 1) for _ in range(len(text1) + 1)] # we start from i+1 and j+1 because 0th row &amp; column are filled with 0 and there is no characters present at either side for i, r in enumerate(text1): for j, c in enumerate(text2): # if there's a match we would add 1 to that index, else we will pick the max value from above row or left column dp[i + 1][j + 1] = 1 + dp[i][j] if r == c else max(dp[i][j + 1], dp[i + 1][j]) return dp[-1][-1] # returning the most recent updated index i.e. the last index of dp[len(text1)+1][len(text2)+1]
longest-common-subsequence
Python DP with full working explanation
DanishKhanbx
0
111
longest common subsequence
1,143
0.588
Medium
17,791
https://leetcode.com/problems/longest-common-subsequence/discuss/2197284/Easy-python-solution-using-2D-Dynamic-programming
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: dp = [[0 for j in range(len(text2) + 1)] for i in range(len(text1) + 1)] for i in range(len(text1) - 1,-1,-1): for j in range(len(text2) - 1, -1, -1): if text1[i] == text2[j]: dp[i][j] = 1 + dp[i+1][j+1] else: dp[i][j] = max(dp[i+1][j],dp[i][j+1]) return dp[0][0]
longest-common-subsequence
Easy python solution using 2D Dynamic programming
nishanrahman1994
0
90
longest common subsequence
1,143
0.588
Medium
17,792
https://leetcode.com/problems/longest-common-subsequence/discuss/2183535/LCS-oror-DP-table-oror-Easy-to-understand
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: # Standard dp LCS problem # T(n)=O(M*N) # S(n)=O(M*N) m=len(text2) n=len(text1) dp=[[None for j in range(m+1)] for i in range(n+1)] for i in range(n+1): for j in range(m+1): if i==0 or j ==0: dp[i][j]=0 for i in range(1,n+1): for j in range(1,m+1): if text1[i-1]==text2[j-1]: dp[i][j]=1+dp[i-1][j-1] else: dp[i][j]=max(dp[i-1][j],dp[i][j-1]) return dp[i][j]
longest-common-subsequence
LCS || DP table || Easy to understand
Aniket_liar07
0
64
longest common subsequence
1,143
0.588
Medium
17,793
https://leetcode.com/problems/longest-common-subsequence/discuss/2158671/Python-a-classic-DP-problem
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: curr = [0] * (len(text2) + 1) for i1 in range(len(text1)): curr, prev = [0] * (len(text2) + 1), curr for i2 in range(len(text2)): if text1[i1] == text2[i2]: curr[i2 + 1] = prev[i2] + 1 else: curr[i2 + 1] = max(curr[i2], prev[i2 + 1]) return curr[-1]
longest-common-subsequence
Python, a classic DP problem
blue_sky5
0
44
longest common subsequence
1,143
0.588
Medium
17,794
https://leetcode.com/problems/longest-common-subsequence/discuss/2151525/99-efficient-time-and-space
class Solution: def longestCommonSubsequence(self, word1: str, word2: str) -> int: if len(word1)>len(word2): word2,word1=word1,word2 m,n=len(word1),len(word2) prev=[0] * (m+1) for i in range(n-1, -1, -1): curr=[0] * (m+1) for j in range(m-1, -1, -1): if word1[j] == word2[i]: curr[j]=1 + prev[j+1] else: curr[j]=max(curr[j+1], prev[j]) prev=curr return prev[0]
longest-common-subsequence
99% efficient time and space
vivekbharti900
0
29
longest common subsequence
1,143
0.588
Medium
17,795
https://leetcode.com/problems/longest-common-subsequence/discuss/2086656/Python-solution-oror-DP
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: a=text1 b=text2 m=len(text1) n=len(text2) dp =([[0 for i in range(n + 1)] for i in range(m + 1)]) for i in range(m+1): for j in range(n+1): if i==0 or j==0: dp[i][j]=0 for i in range(1,m+1): for j in range(1,n+1): if a[i-1]==b[j-1]: dp[i][j]=1+dp[i-1][j-1] else: dp[i][j]=max(dp[i][j-1],dp[i-1][j]) return dp[m][n]
longest-common-subsequence
Python solution || DP
a_dityamishra
0
49
longest common subsequence
1,143
0.588
Medium
17,796
https://leetcode.com/problems/longest-common-subsequence/discuss/2077447/O(NM)
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: dp = [[0 for col in range(len(text2) + 1)] for row in range(len(text1) + 1)] for i in range(len(text1) -1, -1, -1): for j in range(len(text2) -1, -1, -1): if text1[i] == text2[j]: dp[i][j] = 1 + dp[i+1][j+1] else: dp[i][j] = max(dp[i+1][j], dp[i][j+1]) return dp[0][0] # Shoutout to NeetCode for helping me learn
longest-common-subsequence
O(N^M)
andrewnerdimo
0
28
longest common subsequence
1,143
0.588
Medium
17,797
https://leetcode.com/problems/longest-common-subsequence/discuss/2062568/python3-dp-solution
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: r, c = len(text1) + 1, len(text2) + 1 lcs = [[0] * c for _ in range(r)] for i in range(1, r): for j in range(1, c): lcs[i][j] = lcs[i-1][j-1] + 1 if text1[i-1] == text2[j-1] else max(lcs[i][j-1], lcs[i-1][j]) return lcs[len(text1)][len(text2)]
longest-common-subsequence
python3 dp solution
user2613C
0
40
longest common subsequence
1,143
0.588
Medium
17,798
https://leetcode.com/problems/longest-common-subsequence/discuss/2002450/Python3-Dynamic-Programming-method
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: dp = [[0 for _ in range(len(text2) + 1)] for _ in range(len(text1) + 1)] for i in range(len(text1) - 1, -1, -1): for j in range(len(text2) - 1, -1, -1): if text1[i] == text2[j]: dp[i][j] = 1 + dp[i + 1][j + 1] else: dp[i][j] = max(dp[i][j + 1], dp[i + 1][j]) return dp[0][0]
longest-common-subsequence
Python3 - Dynamic Programming method
dayaniravi123
0
66
longest common subsequence
1,143
0.588
Medium
17,799