FastPrepShortest Way to Form a Target String

Shortest Way to Form a Target String

Pinterest logoPinterest● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

You may choose any subsequence of source, preserving character order, and concatenate any number of chosen subsequences.

Return the minimum number of source subsequences whose concatenation equals target. Return -1 when formation is impossible.

Function

shortestWay(source: String, target: String) → int

Examples

Example 1

source = "abc"target = "abcbc"return = 2

Use abc and then bc.

Example 2

source = "abc"target = "acdbc"return = -1

The character d never appears in the source.

Example 3

source = "xyz"target = "xzyxz"return = 3

One optimal decomposition is xz, y, and xz.

Constraints

  • 1 <= source.length, target.length <= 100000.
  • Both strings contain lowercase English letters.

More Pinterest problems

See Pinterest hiring insights
public int shortestWay(String source, String target) {
    // Write your solution here.
}
source"abc"
target"abcbc"
expected2
Checking account…