Fewest Subsequences of a Source String That Concatenate to a Target String
Company: Pinterest
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Onsite
Overview: Given a source string and a target string, return the fewest subsequences of the source whose concatenation equals the target, or -1 when the target cannot be formed. It tests subsequence matching, greedy reasoning about why a choice is optimal, and an efficient iterative implementation.
Read the full Pinterest Software Engineer interview experience this question came from
Constraints
- 1 <= len(source) <= 1000
- 1 <= len(target) <= 1000
- source and target contain only lowercase English letters 'a' to 'z'
- The result is -1 or an integer from 1 to len(target) inclusive, so it fits in a 32-bit signed int
Examples
Input: ('cab', 'abcab')
Expected Output: 2
Input: ('abc', 'abd')
Expected Output: -1
Hints
- If some letter of target never appears in source, no number of pieces can help. Otherwise, is the answer always finite?
- When building one piece, is it ever worse to match each target character at the earliest possible position in source that is still available?
- Precompute, for every index i of source and every letter, the next index at or after i where that letter occurs, so each target character is handled in O(1).
Community answers
Answer by akhil.gandhi10.ag