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 StringSource: "abc"abcTarget: "abcbc"abcbcGreedy Matching ProcessSubsequence 1: "abc"abcSubsequence 2: "bc"bcResult: 2Minimum subsequences needed
Understanding the Visualization
1
Input
Source string and target string to be formed
2
Process
Greedily match characters using subsequences
3
Output
Minimum number of subsequences needed
Key Takeaway
🎯 Key Insight: Greedily match as many characters as possible in each pass through source to minimize subsequence count
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