![]() |
VOOZH | about |
Given two strings S and T, and an empty string Z, the task is to print the minimum operations required to make string Z equal to T by appending any subsequence of S at the end of Z. If it is impossible to do so, then print -1.
Example:
Input: S = "aabce", T="ace"
Output: 1Input: S = "abacaba", T = "aax"
Output: -1
Approach:
The idea is to precomputes the next occurrence (nextOccurrence) positions of each character in the source string S. Iterates backward through S and fills in this array with the rightmost positions of each character occurrence. Then, for each character in the target string T and traverses through the occurrences in S, updating the position and counting the operations needed. If the end of S is reached, resets the position to the beginning and increments the result. If a valid occurrence is not found for a character in T, the position is reset, and the result is incremented. If no valid occurrence is found while the position is at the beginning, the result is set to INF.
Steps:
Below is the implementation of the above approach:
1
Time Complexity: O(n+m), where n is the size of string s and m is the size of string t.
Auxiliary Space: O(n)