Shortest Way to Form String - Problem

A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. For example, "ace" is a subsequence of "abcde" while "aec" is not.

Given two strings source and target, return the minimum number of subsequences of source such that their concatenation equals target. If the task is impossible, return -1.

Input & Output

Example 1 — Basic Case
$ Input: source = "abc", target = "abcbc"
Output: 2
💡 Note: First subsequence: "abc" matches "abc". Second subsequence: "bc" matches remaining "bc". Total: 2 subsequences needed.
Example 2 — Single Character
$ Input: source = "abc", target = "aaa"
Output: -1
💡 Note: Source only has one 'a' at position 0, but target needs three 'a's. Since 'a' appears only once in source, it's impossible to form target.
Example 3 — Perfect Match
$ Input: source = "xyz", target = "xz"
Output: 1
💡 Note: Target "xz" can be formed as a single subsequence from source "xyz" by taking characters at positions 0 and 2.

Constraints

  • 1 ≤ source.length, target.length ≤ 1000
  • source and target consist of lowercase English letters

Visualization

Tap to expand
Shortest Way to Form String INPUT source = "abc" a b c target = "abcbc" a b c b c Goal: Form target using minimum subsequences of source src="abc" tgt="abcbc" ALGORITHM STEPS 1 Initialize Pointers srcIdx=0, tgtIdx=0, count=1 2 Scan Source Match chars, move pointers 3 Reset on End srcIdx=0, count++ if needed 4 Repeat Until Done Continue until target complete Walkthrough: Pass 1: a-b-c matched OK tgt: [a][b][c] b c Pass 2: b-c matched OK tgt: a b c [b][c] Total: 2 passes FINAL RESULT Subsequences Used: Subsequence 1 a b c Subsequence 2 b c "abc" + "bc" = "abcbc" Output 2 Minimum subsequences = 2 Target formed successfully! Key Insight: Greedy approach - scan source repeatedly, matching as many target characters as possible in each pass. Each time source is exhausted before target is complete, increment count and restart from source[0]. Time: O(|source| * |target|) | Space: O(1) | Return -1 if any target char not in source. TutorialsPoint - Shortest Way to Form String | Optimal Greedy Approach
Asked in
Google 12 Amazon 8 Facebook 6 Microsoft 4
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen