Remove Consecutive Duplicates

Easy
0/40
37 upvotes
Asked in companies
SAP LabsAmazonGoldman Sachs

Problem statement

For a given string(str), remove all the consecutive duplicate characters.

Example:
Input String: "aaaa"
Expected Output: "a"

Input String: "aabbbcc"
Expected Output: "abc"
 Input Format:
The first and only line of input contains a string without any leading and trailing spaces. All the characters in the string would be in lower case.
Output Format:
The only line of output prints the updated string.

You are not required to print anything. It has already been taken care of.
Constraints:
0 <= N <= 10^6
Where N is the length of the input string.

Time Limit: 1 second
Constraints:
0 <= N <= 10^6
Where N is the length of the input string.

Time Limit: 1 second
Sample Input 1:
aabccbaa
Sample Output 1:
abcba
Sample Input 2:
xxyyzxx
Sample Output 2:
xyzx
Approaches (1)
Checking equality with last Character
  • Store the length of the String in a variable n.
  • We handle a simple corner case to avoid runtime error. This is when the length of the string is 0.
  • We append the character at position 0 as a simple base case.
  • For each consecutive run of equal characters, we only append the first character. This can be ensured simply by checking input[i-1] ≠ input[i].
  • For eg consider aaabbb. Only First instance of b will be appended to output since only this occurrence satisfies the condition input[i-1] ≠ input[i].
  • We do this until we reach the end of the string.
  • We return the final output string.
Time Complexity
Space Complexity
Code Solution
(100% EXP penalty)
Remove Consecutive Duplicates
Full screen
Console