![]() |
VOOZH | about |
Given a string, you have to remove the three consecutive duplicates from the string. If no three are consecutive then output the string as it is.
Examples:
Input : aabbbaccddddc Output :ccdc Input :aabbaccddc Output :aabbaccddc
Explanation :
We insert the characters of string one by one to vector and keep on checking the size of vector. If the size of vector is greater than 2, then we will check whether the last 3 characters of the string are same or not. If the characters are same
Then we will move three steps backwards in array using resize() else not.
Implementation:
ccdc
Time Complexity: O(n)
Auxiliary Space: O(n)
This article is contributed by Roshni Agarwal.
1. Use the re library to search for any sequence of 3 consecutive identical characters in the input string.
2. Replace any matches with an empty string.
3. Repeat step 1 and 2 until no matches are found.
ccdc
Time Complexity: O(n^2), where n is the length of the input string. This is because we could potentially iterate over the entire string multiple times (once for each match).
Space Complexity: O(n), where n is the length of the input string. This is because we need to store the input string and any intermediate regular expression matches..
Approach: Using Dynamic Programming
dp[k] == 3 (three consecutive duplicates), remove the last three characters from result and move k back to continue building the string. Input: aabbbaccddddc Output: aaaccdc Input: aabbaccddc Output: aabbaccddc
Time Complexity: O(n), where n is the length of the input String.
Auxiliary Space: O(n), dp table requires O(n) space to store the count of consecutive duplicates. In worst case, the space complexity will be near about O(n), where n is the length of the input String.