Quickest Concat

Quickest Concat

Given a target and a list of words (reusable), return the fewest words needed to concatenate into the target, or -1 if it's impossible.

quickestConcat(target, words)

Input format: target | words.

Examples

target="purple", words=[purp, p, ur, le, purpl]   // → 2   (purp+le)
target="abcdef", words=[ab, abc, cd, def, abcd]    // → 2   (abc+def)
target="xyz", words=[a]                            // → -1

Walkthrough

Turning "can it be built" into "how cheaply can it be built"

Builds on the buildability check, but now wants the minimum words used. The first word must prefix the remaining target; after removing it, build the rest with as few additional words as possible. So the minimum for a suffix is 1 plus the smallest "minimum for the leftover" over every prefixing word.

Base case

An empty suffix needs 0 more words.

Why naive recursion is costly, and the subproblem

Different earlier word choices can leave the same remaining suffix reachable through multiple paths. The naive version recomputes the minimum for that suffix every time, even though — just like buildability — the answer depends only on the suffix itself.

Memoizing

Cache from suffix to minimum word count (or "impossible"). Check before recursing; otherwise, for every prefixing word, recurse on the leftover, take the smallest result across all choices, add 1, cache, return. If nothing matches, the suffix is impossible — propagating to -1 for the original target if unbuildable.

Complexity payoff

At most n+1 distinct suffixes, each resolved once against every word — roughly O(n²·m) instead of exponential. Once a "can this be done" recursion and a "cheapest way to do this" recursion share the same subproblem structure, memoize both the same way — tracking a number instead of a boolean.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.