KatInterview

Longest Shared Block After Removing One Character

Dynamic ProgrammingAuto-graded · 24 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingstringslongest-common-substring

Last updated

Find the longest block shared with a second string after optionally deleting one character from the first, using an O(n*m) DP with a deletion-used state.

You are given two strings, source and target.

You may edit source once, by removing exactly one character from any position, or you may leave it unchanged. Only source can be edited, and target is never changed.

After that choice, look at the resulting string and find the longest contiguous block of characters in it that also appears as a contiguous block somewhere in target. Return the length of that block.

Rules and edge cases

  • Skipping the removal is allowed, so if source already contains a block that appears in target, that block counts without any edit.
  • Comparison is case-sensitive and character by character.
  • If either string is empty, or the two strings share no characters, the answer is 0.
  • You choose the removal (or no removal) that gives the largest possible result, so the answer is the best over all options.

Return a single integer.

Constraints

  • 0 <= len(source), len(target) <= 1000
  • Your solution should run faster than O(N^3).

Examples

Example 1

Input: longest_shared_block_after_removal('abcde', 'abce')

Output: 4

Example 2

Input: longest_shared_block_after_removal('xabcd', 'abcd')

Output: 4

Example 3

Input: longest_shared_block_after_removal('aaaa', 'baaa')

Output: 3

Example 4

Input: longest_shared_block_after_removal('', 'anything')

Output: 0

Hints

Hint 1

Trying every possible removal and then running a longest-common-substring check on each costs about O(n^2 * m). Instead, track whether the removal has been used inside the DP state.

Hint 2

Keep two tables over (i, j), both for matches that end exactly at source[i-1] and target[j-1]: one with no removal, and one that has skipped at most one character of source inside the match.

Hint 3

When source[i-1] == target[j-1], the removal-allowed value is the larger of extending the previous removal-allowed value, or skipping source[i-2] and extending the no-removal value that ended at source[i-3] and target[j-2]. Only the last two rows are needed.