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
You are given two strings, `source` and `target`. A subsequence of `source` is any string obtained by deleting zero or more characters of `source` without changing the order of the characters that remain.
Return the minimum number of subsequences of `source` that, concatenated in order, form exactly `target`. If `target` cannot be formed this way, return `-1`.
In the reported screen this came in two stages: first decide only whether `target` can be formed at all, then compute the minimum number of subsequences. The function below answers both, with `-1` meaning that it cannot be formed.
### Function Signature
```python
def min_subsequences_to_form(source: str, target: str) -> int:
```
### Rules
- The same subsequence of `source` may be used any number of times, and each use counts separately.
- Every subsequence used must be non-empty.
- Characters are matched exactly.
### Constraints
- `1 <= len(source) <= 1000`
- `1 <= len(target) <= 1000`
- `source` and `target` contain only lowercase English letters `a` to `z`.
- The result is either `-1` or an integer from `1` to `len(target)` inclusive, and it is uniquely determined by the input.
### Examples
**Example 1**
- Input: `source = "cab"`, `target = "abcab"`
- Output: `2`
- Explanation: `"ab"` and `"cab"` are both subsequences of `"cab"`, and `"ab" + "cab" = "abcab"`. One subsequence is not enough, because `target` is longer than `source`.
**Example 2**
- Input: `source = "abc"`, `target = "abd"`
- Output: `-1`
- Explanation: `d` does not occur in `source`, so no concatenation of its subsequences can contain it.
**Example 3**
- Input: `source = "xyz"`, `target = "zyxz"`
- Output: `3`
- Explanation: One optimal split is `"z" + "y" + "xz"`. Two pieces are impossible: in `source`, `z` comes after `y` and `y` comes after `x`, so no subsequence contains `"zy"` or `"yx"`, and each of `z`, `y` and the following `x` must therefore start a new piece.
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