Partition a Target String by Source Substrings
DatabricksSoftware Engineer · OnsiteLast updated
Determine the minimum number of contiguous substrings from a source string required to reconstruct a target string.
Problem Statement
You are given two strings, source and target. Determine the minimum number of contiguous substrings of source that can be concatenated together to form target.
If it is impossible to construct target using only contiguous substrings of source, return -1.
Function Signature
def min_source_substrings(source: str, target: str) -> int:
pass
Input & Output Format
- Input: Two non-empty strings,
sourceandtarget, consisting of lowercase English letters. - Output: An integer representing the minimum number of segments, or
-1if impossible.
Constraints
1 <= len(source) <= 5 * 10^41 <= len(target) <= 5 * 10^4sourceandtargetconsist of lowercase English letters ('a'–'z').
Examples
Example 1
Input: source = "abcde", target = "abcab"
Output: 2
Explanation:
We can partition target into "abc" and "ab".
Both "abc" and "ab" are contiguous substrings of source.
Hence, 2 substrings are required.
Example 2
Input: source = "banana", target = "naban"
Output: 2
Explanation:
We can partition target into "na" and "ban", both of which appear as substrings in "banana".
Example 3
Input: source = "abc", target = "abcz"
Output: -1
Explanation:
The character 'z' does not appear in source, making it impossible to form target.
Edge Cases to Consider
targetis identical to or already a substring ofsource(output should be1).- A character in
targetdoes not exist insource(immediate return-1). - Every character must be taken individually (e.g., reversed strings with no multi-character overlap).
Hints
Hint 1
Consider whether a greedy strategy works: does extending the current match as far as possible in source ever prevent an optimal decomposition?
Hint 2
A greedy approach is indeed optimal here; at each index of target, you want to find the longest prefix of the remaining target that exists as a substring in source.
Hint 3
To achieve linear or near-linear time, consider building a Suffix Automaton, a Suffix Tree, or using a rolling hash with binary search on source.
Follow-up questions
- How would you optimize this if source is fixed (e.g., a massive genome or codebase) and you need to answer many online queries for different target strings?
- What would change if each substring extracted from source had a non-uniform cost (e.g., cost proportional to length, or fixed per lookup)?
- How does the solution change if you are allowed to pick subsequences of source rather than contiguous substrings?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.