Longest Common Prefix After at Most One Removal - Problem

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.

Input & Output

Example 1 — Basic Mismatch
$ Input: s = "abcde", t = "abfgh"
Output: 2
💡 Note: The common prefix without removal is "ab" (length 2). Removing any character from s doesn't improve this, so the answer is 2.
Example 2 — Remove to Extend
$ Input: s = "axbc", t = "abc"
Output: 3
💡 Note: Without removal: common prefix is "a" (length 1). Removing s[1]='x' gives "abc" vs "abc", common prefix "abc" (length 3).
Example 3 — No Improvement
$ Input: s = "abc", t = "def"
Output: 0
💡 Note: No common prefix exists regardless of removal. The answer is 0.

Constraints

  • 1 ≤ s.length, t.length ≤ 1000
  • s and t consist of only lowercase English letters

Visualization

Tap to expand
Longest Common Prefix After Removal INPUT String s = "abcde" a b c d e 0 1 2 3 4 String t = "abfgh" a b f g h Compare character by character OK OK X - - s = "abcde" t = "abfgh" ALGORITHM STEPS 1 Find Initial LCP Compare s and t from start LCP = 2 (a,b match) 2 Try Skip at Mismatch Skip s[2]='c', compare s[3]='d' vs t[2]='f' --X 3 Try All Skip Positions Skip each char in s[0..2] Best result still = 2 4 Return Maximum max(no_removal, with_removal) max(2, 2) = 2 Skip Options Tried: bcde vs abfgh -- 0 acde vs abfgh -- 1 FINAL RESULT Longest Common Prefix a b c d Prefix: "ab" (length 2) OUTPUT 2 Verification: s[0:2] = "ab" t[0:2] = "ab" Match! Length = 2 Key Insight: The optimal approach tries two strategies: (1) Find LCP without any removal, and (2) At each position where mismatch occurs, try skipping one character from s and continue matching. The answer is the maximum of all attempts. Time complexity: O(n) where n = min(len(s), len(t)). TutorialsPoint - Longest Common Prefix After at Most One Removal | Optimal Solution
Asked in
Microsoft 25 Google 18
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen