Problem Description
Given two strings s and t, determine the length of the longest common prefix after removing at most one character from s. The removal is optional; you may choose to not remove any character if s already aligns well with t.
Key Insights
- The obvious approach is to first match s and t from the beginning.
- When a mismatch occurs at position i, you can consider removing s[i] (the first differing character) to potentially extend the common prefix.
- Only one removal is allowed, so the removal must occur at the first mismatch to maximize the prefix length.
- Use two pointers to simulate the matching process: one pointer for t and two for s (one for before removal and one for after removal).
Space and Time Complexity
Time Complexity: O(n) where n is the length of the strings (in the worst case, you scan both fully). Space Complexity: O(1) as only a few extra variables are used.
Solution
We start by comparing s and t character by character from the beginning. Let i be the index up to which the characters match. If we reach the end of one string, then the answer is simply the length of the matched portion. When a mismatch s[i] != t[i] occurs, we have one chance to remove a character from s. The best candidate for removal is at index i since the prefix up to i is already matching. After removing s[i], we set two pointers: one (j) to continue from s[i+1] and one (k) to continue from t[i]. We then further match until a mismatch occurs or end of either string is reached. The candidate longest prefix becomes the sum of the initially matched characters (i) plus the count of matching characters after the removal. Finally, the answer is the maximum of the prefix without removal and the prefix obtained after the potential removal.