diff --git a/DynamicProgramming/longest_common_subsequence.py b/DynamicProgramming/longest_common_subsequence.py index 85d627e..12d298a 100644 --- a/DynamicProgramming/longest_common_subsequence.py +++ b/DynamicProgramming/longest_common_subsequence.py @@ -16,6 +16,35 @@ def longestCommonSubsequence(self, text1: str, text2: str) -> int: return 3 Approach: Bottom up, Tabular + + T=O(mn), beats 93.88 % + S=O(n), beats 91.28 % + """ + if not text1 or not text2: + return 0 + + l1 = len(text1)+1 if text1 else 0 + l2 = len(text2)+1 if text2 else 0 + + curr = [0]*l2 + prv = [0]*l2 + + for r in range(1, l1): + for c in range(1, l2): + if text1[r-1] == text2[c-1]: + curr[c] = 1 + prv[c-1] + else: + curr[c] = max( + prv[c], + curr[c-1] + ) + prv = curr.copy() + + return prv[-1] + + def longestCommonSubsequence_full(self, text1: str, text2: str) -> int: + """ + Approach: Bottom up, Full Tabular Make a table using Text1 as a row, Text2 as a column The first row is without any char from Text 1 The first col is without any char from Text 2 @@ -29,21 +58,27 @@ def longestCommonSubsequence(self, text1: str, text2: str) -> int: c 0 1 2 2 d 0 1 2 2 e 0 1 2 3 + + T=O(mn) beats 79.45%, + S=O(mn) beats 52.78% """ if not text1 or not text2: return 0 l1 = len(text1)+1 if text1 else 0 - l2 = len(text2)+1 if text2 else 0 + l2 = len(text2)+1 if text2 else 0 - longest = [[0]*l2 for _ in range(l1)] + max_length = [[0]*l2 for _ in range(l1)] for r in range(1, l1): for c in range(1, l2): if text1[r-1] == text2[c-1]: - longest[r][c] = 1 + longest[r-1][c-1] + max_length[r][c] = 1 + max_length[r-1][c-1] else: - longest[r][c] = max(longest[r-1][c], longest[r][c-1]) + max_length[r][c] = max( + max_length[r-1][c], + max_length[r][c-1] + ) - return longest[r][c] + return max_length[-1][-1]