Fewest Source Slices to Spell a Target
StringsAuto-graded · 26 test casesLast 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
targetexactly. - 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^41 <= 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem splits into two parts.
1. Longest usable piece at each position. For each index i of target, let reach[i] be the length of the longest prefix of target[i:] that occurs as a substring of source. Every shorter prefix of that piece also occurs in source, so from i you may legally end a slice at any index in i+1 .. i+reach[i].
2. Minimum number of jumps. Treat the indices 0..n of target as positions. From i you can jump to any position up to i + reach[i]. We want the fewest jumps from 0 to n. This is the classic Jump Game II, solved greedily in one pass: track the end of the current jump layer and the farthest position reachable. When the scan hits the end of the layer, commit one more slice. If the farthest position has not advanced beyond the current index, we are stuck and return -1.
Computing reach efficiently. A suffix automaton gives, for each prefix of a text, the longest suffix of that prefix which is a substring of the automaton's string (matching statistics). We need the longest match starting at each index, so we reverse both strings. We build the automaton on source[::-1] and stream target[::-1] through it. After reading k characters, the match length equals the longest substring of source that starts at target index n - k, so reach[i] = match[n - i].
While streaming, if the current state has no transition on the next character, we follow suffix links (resetting the match length to the length of the state we land on) until a transition exists or we hit the root. If even the root has no transition, the match length is 0.
Why it is correct
- The automaton accepts exactly the substrings of the reversed source, so the tracked match length is always the longest valid one.
- The set of positions reachable from
iin one slice is exactly the interval[i+1, i+reach[i]], because substrings of substrings are substrings. i + reach[i]never decreases asigrows: iftarget[i:i+L]is insource, so istarget[i+1:i+L]. Hence extending as far as possible never hurts, and any optimal answer can be exchanged piece by piece for the greedy one without using more slices.- A character of
targetmissing fromsourcegivesreach = 0there, so the greedy gets stuck and returns-1.
Complexity
With m = len(source) and n = len(target):
- Automaton construction: O(m) (alphabet size is 26, a constant).
- Matching: O(n) amortized, since the match length grows by at most 1 per character and each suffix-link step shrinks it.
- Jump pass: O(n).
- Total time O(m + n); space O(m) for the automaton plus O(n) for
match.
Reference solution
from typing import List
def fewest_source_slices(source: str, target: str) -> int:
src = source[::-1]
tgt = target[::-1]
# Suffix automaton built on the reversed source
nxt = [{}]
link = [-1]
length = [0]
last = 0
for ch in src:
cur = len(nxt)
nxt.append({})
length.append(length[last] + 1)
link.append(0)
p = last
while p != -1 and ch not in nxt[p]:
nxt[p][ch] = cur
p = link[p]
if p == -1:
link[cur] = 0
else:
q = nxt[p][ch]
if length[p] + 1 == length[q]:
link[cur] = q
else:
clone = len(nxt)
nxt.append(nxt[q].copy())
length.append(length[p] + 1)
link.append(link[q])
while p != -1 and nxt[p].get(ch) == q:
nxt[p][ch] = clone
p = link[p]
link[q] = clone
link[cur] = clone
last = cur
# match[k] = longest substring of source starting at target index n - k
n = len(target)
match = [0] * (n + 1)
v = 0
l = 0
for i, ch in enumerate(tgt, 1):
while v and ch not in nxt[v]:
v = link[v]
l = length[v]
if ch in nxt[v]:
v = nxt[v][ch]
l += 1
else:
v = 0
l = 0
match[i] = l
# Greedy jump pass
jumps = 0
current_end = 0
farthest = 0
for i in range(n):
if i > farthest:
return -1
reach = match[n - i]
if i + reach > farthest:
farthest = i + reach
if i == current_end:
jumps += 1
if farthest >= n:
return jumps
if farthest == i:
return -1
current_end = farthest
return -1