VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimize-operations-to-make-string-z-equal-to-t-by-appending-subsequence-of-s/

⇱ Minimize operations to make string Z equal to T by appending subsequence of S - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimize operations to make string Z equal to T by appending subsequence of S

Last Updated : 24 Feb, 2024

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: 1

Input: 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:

  • Initialize a 2D array nextOccurrence to store the next occurrence position of each character in S.
  • Precompute the next occurrence positions for each character in S using the nextOccurrence array. This helps in efficiently finding the next occurrence of a character during the calculation.
  • Iterate through each character in the target string T.
    • For each character, check if the next occurrence of that character in S is found using the nextOccurrence array.
    • If found, update the position to the next occurrence position + 1.
    • If not found, reset the position to the beginning of S and increment the result, indicating a new subsequence is appended.
    • If it's not possible to find the next occurrence, set result to INF, indicating impossibility.
  • Print the final result. If result is greater than or equal to INF, print -1, else print the number of operations needed.

Below is the implementation of the above approach:


Output
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)

Comment