Given a string str of size N and an integer K, the task is to generate a string whose substrings of size K can be concatenated to form the given string.
Input: str = “abbaaa” K = 2
All substring of size 2 of parent string “abaa” are “ab”, “ba” and “aa”. After concatenating all these substrings, the given string “abbaaa” can be obtained.
Input: str = “abcbcscsesesesd” K = 3
All substring of size 3 of parent string “abcsesd” are “abc”, “bcs”, “cse”, “ses” and “esd”. After concatenating all these substrings, the given string “abcbcscsesesesd” can be obtained.
Follow the steps below to solve the problem:
- We can clearly observe that by concatenating substrings of length K, except the first character, the remaining K-1 characters of any substring is present in the next substring as well.
- Hence, traverse the string and append the first character of every substring to ans and then ignore next the K-1 characters.
- Repeat this process for all substrings except the last substring.
- Append all characters of the last substring to ans.
- Return ans as the required decoded string.
Below is the implementation of the above approach :
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.