Imagine you have a source cookbook and you want to create a target recipe by copying ingredients in order from the cookbook pages. You can flip through the cookbook multiple times, but you must follow the ingredient order on each page.
Given two strings source and target, find the minimum number of passes through the source string needed to form the target string as a concatenation of subsequences.
A subsequence maintains the original character order but allows skipping characters. For example, "ace" is a subsequence of "abcde", but "aec" is not.
Goal: Return the minimum number of subsequences of source that concatenate to form target. If impossible, return -1.
Example: If source = "abc" and target = "abcbc", we need 2 passes: "abc" + "bc" = "abcbc"
Input & Output
Visualization
Time & Space Complexity
For each character in target (m), we might scan the entire source (n) in worst case
Only using a few integer variables for tracking positions
Constraints
- 1 โค source.length, target.length โค 1000
- source and target consist of lowercase English letters
- Follow-up: Can you optimize for the case where the same source is queried with multiple different targets?