Partition a Target String by Source Substrings
Company: Databricks
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates understanding of string algorithms and optimal partitioning, specifically substring matching and minimizing the number of contiguous segments extracted from a source string.
Part 1: Minimum Partition of Target by Source Substrings
Constraints
- 0 <= len(target), len(source) <= 2000
- target and source consist of lowercase English letters
- Indices in the answer must be 0-based and inclusive
- Return any one optimal partition if multiple exist
Examples
Input: ("abcdbcd", "sabcd")
Expected Output: [[1, 4], [2, 4]]
Explanation: source[1:5] is abcd and source[2:5] is bcd. Together they form abcdbcd using 2 pieces, which is minimum.
Input: ("cab", "zzcabx")
Expected Output: [[2, 4]]
Explanation: The whole target is already a substring of source.
Input: ("b", "abc")
Expected Output: [[1, 1]]
Explanation: Single-character target.
Input: ("", "abc")
Expected Output: []
Explanation: An empty target needs zero pieces.
Input: ("az", "abc")
Expected Output: []
Explanation: z does not appear in source, so no partition is possible.
Hints
- Think about the longest common prefix between target[i:] and source[j:] for every pair of positions.
- Once you know the maximum usable piece length from each target index, the problem becomes a minimum-jumps / shortest-path problem on positions 0..len(target).
Part 2: Minimum Partition After Deleting One Character
Constraints
- 0 <= len(target), len(source) <= 2000
- target and source consist of lowercase English letters
- For a valid delete operation, 0 <= delete_index < len(target)
- Indices in the answer must be 0-based and inclusive
Examples
Input: ("abcdbcd", "sabcd", 3)
Expected Output: [[1, 3], [2, 4]]
Explanation: Deleting index 3 removes d, so the new target is abcbcd. That can be formed as abc + bcd.
Input: ("xabc", "zzabc", 0)
Expected Output: [[2, 4]]
Explanation: After deleting x, the updated target is abc, which appears directly in source.
Input: ("q", "abc", 0)
Expected Output: []
Explanation: Deleting the only character leaves an empty target, which needs zero pieces.
Input: ("az", "bc", 0)
Expected Output: []
Explanation: After deletion the new target is z, which does not appear in source.
Input: ("abc", "abc", 3)
Expected Output: []
Explanation: delete_index is out of range, so return the agreed error value [].
Hints
- After removing one character, the remaining task is the same core problem as Part 1 on a shorter target string.
- If you already know how to compute the best partition for a target string, wrap that logic in a helper and call it on target[:delete_index] + target[delete_index+1:].