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.
- Print Kth character in sorted concatenated substrings of a string
- Nth character in Concatenated Decimal String
- Concatenated string with uncommon characters in Python
- Concatenated string with uncommon characters of two strings
- Maximum Consecutive Zeroes in Concatenated Binary String
- Print the final string when minimum value strings get concatenated in every operation
- Minimal moves to form a string by adding characters or appending string itself
- Find the count of palindromic sub-string of a string in its sorted form
- Check if a string is a scrambled form of another string
- Number of substrings of a string
- Replace two substrings (of a string) with each other
- Program to print all substrings of a given string
- Split the string into substrings using delimiter
- Sum of all substrings of a string representing a number | Set 1
- Number of substrings of one string present in other
- Number of even substrings in a string of digits
- Count of substrings of a binary string containing K ones
- Different substrings in a string that start and end with given strings
- Lexicographical concatenation of all substrings of a string
- Count of bitonic substrings from the given string
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.