Shortest Way to Form String
Real-world version: Fewest Passes Of The Letter StencilThe statement here is our own: the same inputs, outputs and technique.
A printing stencil carries the lowercase letters of stencil in a fixed left-to-right order.
One pass of the stencil prints a chosen set of its letters onto the right-hand end of the sheet. Within a pass the chosen letters come out in stencil order, each position on the stencil may be used at most once, and at least one letter must be printed; letters may be left out freely, so a pass can print anything from a single letter up to the whole stencil.
The finished sheet has to read exactly wanted. Return the smallest number of passes that produces it, or -1 when no number of passes can. The value -1 is never a valid pass count, so it is unambiguous as an answer.
Examples
Example 1
- Input
- stencil = "mnp", wanted = "mnpnm"
- Output
- 3
Print mnp on the first pass, then n on the second, then m on the third. The sheet reads mnpnm, so 3 passes are used.
Example 2
- Input
- stencil = "mnp", wanted = "mnq"
- Output
- -1
The stencil carries m, n and p only, and the sheet has to show a q, which no pass can print, so the answer is -1.
Example 3
- Input
- stencil = "ab", wanted = "aabb"
- Output
- 3
Print a on the first pass, then ab on the second, then b on the third. The sheet reads aabb, so 3 passes are used.
Constraints
- 1 <= stencil.length <= 1000
- 1 <= wanted.length <= 1000
- stencil and wanted consist of lowercase English letters.
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def shortest_way(stencil: str, wanted: str) -> int:public int shortestWay(String stencil, String wanted)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 12 test cases: 12 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Valid Palindrome IIReal-world version: Mosaic Border InspectionEasy
- Earliest Finish Time for Land and Water Rides IReal-world version: Forge and Kiln BookingEasy
- Partition LabelsReal-world version: Duty Roster BlocksMedium
- Find the Lexicographically Smallest Valid SequenceReal-world version: Cheapest Probe Slots On A ReelMedium