In the Find Maximum Removals From Source String coding problem, you are given two strings, source and pattern, and an array of indices in source that are "removable." You want to remove the maximum number of characters from the removable indices such that pattern remains a subsequence of the modified source.
Google asks this to test your understanding of Dynamic Programming on Subsequences. It requires balancing the need to preserve a subsequence while maximizing removals. It evaluation your ability to define a state that tracks the progress in both the source and the pattern strings while identifying which removals are "safe."
This is a 2D Dynamic Programming problem.
dp[i][j] be the maximum removals from the first characters of source such that the first characters of pattern are matched as a subsequence.source[i-1]:
dp[i][j] = dp[i-1][j] + (1 if removable).source[i-1] == pattern[j-1]: You can choose to use this character to match the pattern. In this case, you cannot remove it. dp[i][j] = max(dp[i][j], dp[i-1][j-1]).dp[sourceLen][patternLen].source = "abcde", pattern = "ae", removable = [1, 2, 3] (indices of 'b', 'c', 'd')
isSubsequence. This is and too slow.For problems where you want to "Max/Min X while preserving subsequence Y," the state is usually dp[index_in_source][index_in_pattern]. This is a direct extension of the "Longest Common Subsequence" template.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Longest String Chain | Medium | Solve | |
| Find the Substring With Maximum Cost | Medium | Solve | |
| Longest Uncommon Subsequence II | Medium | Solve | |
| Shortest Word Distance II | Medium | Solve | |
| Extra Characters in a String | Medium | Solve |