Longest Common Prefix After at Most One Removal Problem
Description
LeetCode Problem 3460.
You are given two strings s and t.
Return the length of the longest common prefix between s and t after removing at most one character from s.
Note: s can be left without any removal.
Example 1:
Input: s = "madxa", t = "madam"
Output: 4
Explanation:
Removing s[3] from s results in "mada", which has a longest common prefix of length 4 with t.
Example 2:
Input: s = "leetcode", t = "eetcode"
Output: 7
Explanation:
Removing s[0] from s results in "eetcode", which matches t.
Example 3:
Input: s = "one", t = "one"
Output: 3
Explanation:
No removal is needed.
Example 4:
Input: s = "a", t = "b"
Output: 0
Explanation:
s and t cannot have a common prefix.
Constraints:
1 <= s.length <= 10^51 <= t.length <= 10^5sandtcontain only lowercase English letters.
Solution
Approach: Two Pointers
We want the longest prefix of t that appears as a subsequence of s in which at most one character of s was skipped before matching it, and the characters must line up from the start.
Keep i in s, j in t, and a flag rem saying whether the one removal has been used. While both are in range: if s[i] == t[j], advance both. Otherwise, if the removal is unused, use it (skip s[i]); if it is already used, stop. The answer is j, the length of the matched prefix of t.
Complexity: O(n + m) time and O(1) extra space.
class Solution:
def longestCommonPrefix(self, s: str, t: str) -> int:
n, m = len(s), len(t)
i = j = 0
rem = False
while i < n and j < m:
if s[i] != t[j]:
if rem:
break
rem = True
else:
j += 1
i += 1
return j