KatInterview

Fewest Source Slices to Spell a Target

StringsAuto-graded · 26 test cases
MediumAuto-gradedStringsstringsgreedysuffix-automaton

Last updated

Find the minimum number of source substrings whose concatenation equals the target, using longest-match-per-position and a greedy jump pass.

Spelling a Word from Slices

You have a string source and a string target. You want to build target by joining together several slices of source. A slice is a non-empty run of consecutive characters taken from source.

Rules:

  • The slices are joined in the order you choose, and their concatenation must equal target exactly.
  • The same slice may be used any number of times, and different slices may overlap in source.

Return the smallest number of slices needed. If target cannot be built this way, return -1.

Input

  • source: a non-empty string of lowercase English letters.
  • target: a non-empty string of lowercase English letters.

Output

An integer: the minimum slice count, or -1 if building target is impossible.

Constraints

  • 1 <= len(source) <= 5 * 10^4
  • 1 <= len(target) <= 5 * 10^4
  • Both strings contain only the characters 'a' to 'z'.

Examples

Example 1

Input: fewest_source_slices('abcde', 'abcab')

Output: 2

Example 2

Input: fewest_source_slices('banana', 'naban')

Output: 2

Example 3

Input: fewest_source_slices('abc', 'abcz')

Output: -1

Hints

Hint 1

For each index i of target, ask: what is the longest piece starting at i that appears somewhere in source? Any shorter piece starting at i is then also valid, since a prefix of a substring is a substring.

Hint 2

Once you know that longest length for every index, the task becomes a jump problem: from position i you can move to any position up to i + reach[i]. Greedily extending as far as possible is optimal, as in Jump Game II.

Hint 3

To get the longest match starting at every index quickly, reverse both strings and stream the reversed target through a suffix automaton of the reversed source (or use hashing with binary search on the length). If some index has reach 0, the answer is -1.