Shortest Way to Form String Problem
Description
LeetCode Problem 1055.
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. (i.e., "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.
Example 1:
Input: source = "abc", target = "abcbc"
Output: 2
Explanation: The target "abcbc" can be formed by "abc" and "bc", which are subsequences of source "abc".
Example 2:
Input: source = "abc", target = "acdbc"
Output: -1
Explanation: The target string cannot be constructed from the subsequences of source string due to the character "d" in target string.
Example 3:
Input: source = "xyz", target = "xzyxz"
Output: 3
Explanation: The target string can be constructed as follows "xz" + "y" + "xz".
Constraints:
1 <= source.length, target.length <= 1000sourceandtargetconsist of lowercase English letters.
Solution
Approach: Greedy Two Pointers
Build target from left to right, one subsequence of source at a time. For each new subsequence, walk once through source and match characters of target greedily: every time source[i] equals the next needed character target[j], take it and advance j.
Taking a matching character as early as possible is never worse. Each pass over source then covers the longest possible next piece of target, and a longer prefix of target done can only leave less work for later passes, so the number of passes is the minimum.
The one case to catch is a character that source does not contain: a full pass then matches nothing (j does not move), and we return -1. Without that check the loop would never end.
Complexity: O(m · n) time in the worst case, where m and n are the lengths of source and target (each pass makes progress on at least one character of target), and O(1) extra space.
class Solution:
def shortestWay(self, source: str, target: str) -> int:
n = len(target)
ans = j = 0 # j: the next character of target still to be formed
while j < n:
start = j
# One pass over source greedily matches as much of target as it can.
for c in source:
if j < n and c == target[j]:
j += 1
if j == start:
return -1 # target[j] does not occur in source at all
ans += 1
return ans