Problem
From any string, we can form a subsequence of that string by deleting some number of characters (possibly no deletions).
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
.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 - Greedy
To solve this problem, we need to break down the target string into subsequences of the source string. We will iterate over the target string and attempt to match its characters with those of the source string, forming subsequences.
-
Pointer Initialization:
- Initialize a pointer for the source (source_index) and target (target_index).
- Initialize a counter (subseq_count) to count how many subsequences of the source are needed.
-
Iterate Through the Target:
- For each character in the target, check if it is present in the source starting from the current position of the source_index.
- If a character in the target cannot be matched from the current source_index, increment subseq_count and reset the source_index to 0 to start forming a new subsequence.
- Repeat this process until we have successfully formed the target from subsequences of the source or determine it’s impossible.
-
Return the Result:
- If we successfully concatenate subsequences of the source to form the target, return the subseq_count.
- Otherwise, return
-1
if the target cannot be formed.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m * n)
, wherem
is the length of the target andn
is the length of the source. This is because, in the worst case, checking each character in the target might require scanning through a majority of the source. - 🧺 Space complexity:
O(1)
, since no extra space proportional to the input size is used, aside from a few pointers and counters.