From 79928a347a96a7e177029bcc787c24eb0cd41651 Mon Sep 17 00:00:00 2001 From: Goun Na Date: Mon, 28 Oct 2024 22:08:45 +0900 Subject: [PATCH 1/2] 1143. Longest Common Subsequence (Medium) --- .../longest_common_subsequence.py | 45 ++++++++++++++++--- 1 file changed, 40 insertions(+), 5 deletions(-) diff --git a/DynamicProgramming/longest_common_subsequence.py b/DynamicProgramming/longest_common_subsequence.py index 85d627e..d1ebbd0 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], # Insert + max_length[r][c-1] # Delete + ) - return longest[r][c] + return max_length[-1][-1] From d627163442a295903ea9eeb3e20a94b98e737adb Mon Sep 17 00:00:00 2001 From: Goun Na Date: Mon, 28 Oct 2024 22:12:10 +0900 Subject: [PATCH 2/2] 1143. Longest Common Subsequence (Medium) --- DynamicProgramming/longest_common_subsequence.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DynamicProgramming/longest_common_subsequence.py b/DynamicProgramming/longest_common_subsequence.py index d1ebbd0..12d298a 100644 --- a/DynamicProgramming/longest_common_subsequence.py +++ b/DynamicProgramming/longest_common_subsequence.py @@ -76,8 +76,8 @@ def longestCommonSubsequence_full(self, text1: str, text2: str) -> int: max_length[r][c] = 1 + max_length[r-1][c-1] else: max_length[r][c] = max( - max_length[r-1][c], # Insert - max_length[r][c-1] # Delete + max_length[r-1][c], + max_length[r][c-1] ) return max_length[-1][-1]