How to Remove Consecutive Characters From a String

Saturday, February 20, 2021 • One minute to read

to-the-point2021data structuresjavascript

Problem Statement

Remove n consecutive characters from a string and return the final string.

For example:

1Input String: abccdeeef
2
3Output String: abdf

Solution

 1const str = "abccdeeef";
 2//-----------012345678
 3let finalStr = "";
 4
 5let isConsecutive = false;
 6
 7for (let i = 0; i < str.length - 1; i++) {
 8  // check if characters are consecutive
 9  if (str[i] === str[i + 1]) {
10    isConsecutive = true;
11  } else {
12    // check if the last character was consecutive
13    if (!isConsecutive) {
14      // add the character to new string
15      finalStr += str[i];
16    }
17    // reset the flag
18    isConsecutive = false;
19  }
20}
21
22// check for last character
23if (!isConsecutive) {
24  finalStr += str[str.length - 1];
25}
26
27console.log(finalStr);

Output

1abdf;

Final words

This is one of very common interview question can be asked in the interview. The solution is easy but in interviews due to time frame, interviewee can get confused. Always go for easy solution and then work on complexity.


to-the-point2021data structuresjavascript

PreviousHow to Sort an Array of Objects in Javascript

NextHow to Format Golang Project