FastPrepShortest Way to Form a Target String
Problems/Shortest Way to Form a Target String

Shortest Way to Form a Target String

Pinterest logoPinterest● MediumFULLTIMEPHONE SCREEN
QuestionFunctionExamplesConstraints

Problem statement

Source note: The interview report names the canonical exercise, first asks whether formation is possible, and then asks for the minimum using a two-pointer greedy scan. The practice statement supplies only bounds and a callable interface. The judged task matches the report at about 98%.

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

  • Gaussian Naive Bayes Classifier (Machine Learning OA)OA · Seen Nov 2026
  • Top K Pins with Insert and QueryPHONE SCREEN · Seen Nov 2026
  • Pins Violation Log QueriesPHONE SCREEN · Seen Nov 2026
All Pinterest interview questionsSee Pinterest hiring insights
Saved
class Solution {
    public int shortestWay(String source, String target) {
        // Write your solution here.
    }
}
Checking account…