Longest Shared Block After Removing One Character
Dynamic ProgrammingAuto-graded · 24 test casesLast 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
sourcealready contains a block that appears intarget, 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Trying every removal and recomputing a longest common substring each time costs O(n^2 * m), which is too slow. Instead, make "has the removal been used yet?" part of a single DP.
Any block of the edited source is one of two kinds:
- It does not cross the removed position, so it is an ordinary block of
source. - It crosses the removed position, so it is a block of
sourcewith one interior character left out.
Removing a character at the edge of a block never lengthens it, so only interior removals matter.
For prefixes source[:i] and target[:j], consider matches that end exactly at source[i-1] and target[j-1]:
plain[i][j]: the longest common suffix with no removal. This is the classic longest-common-substring table.skip[i][j]: the longest matched length where at most one character ofsourcewas skipped inside the match.
If source[i-1] == target[j-1]:
plain[i][j] = plain[i-1][j-1] + 1skip[i][j] = max(skip[i-1][j-1] + 1, plain[i-2][j-1] + 1)
The second term in skip skips source[i-2] and extends a removal-free match that ended at source[i-3] and target[j-2]. If the characters differ, both values are 0. The answer is the maximum over all cells.
Each row needs only the previous row, and plain also needs the row before that, so three rolling arrays are enough.
Why it is correct
- A skip is introduced only through the
plain[i-2]transition, which contains no skip. Afterwards it is carried forward only throughskip[i-1][j-1], so at most one removal is ever used. - Every block of the form
source[a..k-1] + source[k+1..b]that appears intargetis counted. Walking backward fromb, the cells use theskiptransition until just pastk, then switch toplain. - Blocks with no removal are covered by
plain, and also byskip, sinceskipmeans "at most one". - Only one removal is allowed in total, so the answer is a single best window, and the global maximum is correct.
- The value counts matched characters, which equals the block's length in the edited string.
Complexity
- Time:
O(n * m), about 10^6 cell updates at the maximum size. - Space:
O(m)with rolling rows.
Reference solution
def longest_shared_block_after_removal(source: str, target: str) -> int:
n, m = len(source), len(target)
prev_plain = [0] * (m + 1) # no-removal table, row i-1
prev_skip = [0] * (m + 1) # at-most-one-removal table, row i-1
older_plain = [0] * (m + 1) # no-removal table, row i-2
best = 0
for i in range(1, n + 1):
cur_plain = [0] * (m + 1)
cur_skip = [0] * (m + 1)
for j in range(1, m + 1):
if source[i - 1] == target[j - 1]:
cur_plain[j] = prev_plain[j - 1] + 1
cur_skip[j] = prev_skip[j - 1] + 1
if i >= 2:
cur_skip[j] = max(cur_skip[j], older_plain[j - 1] + 1)
best = max(best, cur_plain[j], cur_skip[j])
older_plain, prev_plain = prev_plain, cur_plain
prev_skip = cur_skip
return best