Skip to main content

Remove Consecutive Characters

Problem​

Given a string S. For each index i(1<=i<=N-1), erase it if s[i] is equal to s[i-1] in the string.

Examples:​

Example 1:

Input:
S = aabb
Output: ab
Explanation: 'a' at 2nd position is appearing 2nd time consecutively. Similiar explanation for b at 4th position.

Example 2:

Input:
S = aabaa
Output: aba
Explanation: 'a' at 2nd position is appearing 2nd time consecutively. 'a' at fifth position is appearing 2nd time consecutively.

Your task:​

You dont need to read input or print anything. Complete the function removeConsecutiveCharacter() which accepts a string as input parameter and returns modified string.

  • Expected Time Complexity: O(∣S∣)O(|S|)
  • Expected Auxiliary Space: O(∣S∣)O(|S|)

Constraints:​

  • 1<=∣S∣<=1051<=|S|<=10^5

All characters are lowercase alphabets.

Solution​

Python​

def removeConsecutiveCharacter(self, S):
if len(S) == 0:
return ""
result = []
result.append(S[0])
for i in range(1, len(S)):
if S[i] != S[i - 1]:
result.append(S[i])
return ''.join(result)

Java​

public String removeConsecutiveCharacter(String S){
if (S == null || S.length() == 0) {
return "";
}
StringBuilder result = new StringBuilder();
result.append(S.charAt(0));
for (int i = 1; i < S.length(); i++) {
char currentChar = S.charAt(i);
char previousChar = result.charAt(result.length() - 1);
if (currentChar != previousChar) {
result.append(currentChar);
}
}
return result.toString();
}

C++​

string removeConsecutiveCharacter(string S) {
if (S.empty()) {
return "";
}
string result;
result.push_back(S[0]);
for (int i = 1; i < S.length(); i++) {
if (S[i] != result.back()) {
result.push_back(S[i]);
}
}
return result;
}

C​

char* removeConsecutiveCharacter(const char* S) {
if (S == NULL || strlen(S) == 0) {
char* result = (char*) malloc(sizeof(char));
result[0] = '\0';
return result;
}
int len = strlen(S);
char* result = (char*) malloc((len + 1) * sizeof(char));
if (result == NULL) {
return NULL;
}
int resultIndex = 0;
result[resultIndex++] = S[0];
for (int i = 1; i < len; i++) {
if (S[i] != result[resultIndex - 1]) {
result[resultIndex++] = S[i];
}
}
result[resultIndex] = '\0';
return result;
}

  • Time Complexity: O(∣S∣)O(|S|)
  • Auxiliary Space: O(∣S∣)O(|S|)