VOOZH about

URL: https://www.geeksforgeeks.org/dsa/valid-compressed-string/

⇱ Valid Compressed String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Valid Compressed String

Last Updated : 27 Apr, 2023

A special compression mechanism can arbitrarily delete 0 or more characters and replace them with the deleted character count.
Given two strings, S and T where S is a normal string and T is a compressed string, determine if the compressed string  T is valid for the plaintext string S.

Examples:

Input: S = "GEEKSFORGEEKS", T = "G7G3S"
Output: 1
Explanation: We can clearly see that T is a valid compressed string for S.

Input: S = "DFS", T = "D1D"
Output: 0
Explanation: T is not a valid compressed string.

Approach: To solve the problem follow the below idea:

Idea is to traverse through the string T using variable i and take a variable j and initialize it to 0, if we find an integer in string T, increase the j pointer by that integer and then compare S[j] and T[i]. If at any point, it doesn't match, the compressed String isn't valid.

Below are the steps for the above approach:

  • Initialize 3 variables flag = 1, j = 0, and n = 0.
  • Run a loop from i = 0 to i < length of t.
  • Check if t[i] is a digit, retrieve the digit, and decrement j by 1.
  • Else update j += n and check if t[i] != s[j], mark the flag = 0, and break the loop. Reset n to 0 and increment j by 1.
  • When the loop ends, Increment j by n.
  • Check if j != s.length(), and mark the flag = 0.
  • Check if flag == 1, return 1, else return 0.

Below is the implementation of the above approach:


Output
1

Time Complexity: O(T)  //In the above-given approach, there is one loop for iterating over string which takes O(T) time in worst case. Therefore, the time complexity for this approach will be O(T).
Auxiliary Space: O(1) //since no extra array or data structure is used so the space taken by the algorithm is constant

Comment
Article Tags:
Article Tags: