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
O(n) to build position map, then O(m*n) for finding positions in worst case where we scan all positions for each target character
Space for storing all character positions in hash map
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?