All problems
0643MediumTwo PointersStringBinary SearchGreedy

Fewest Passes Of The Letter Stencil

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1055Shortest Way to Form String

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def shortest_way(stencil: str, wanted: str) -> int:
Java
public int shortestWay(String stencil, String wanted)
September 7
Apply