Write a program to remove three consecutive duplicate characters from String

In this article, we will learn how to remove three consecutive duplicate characters from String. This is one of the tricky questions asked in various interviews.

Approach

  1. Loop from i =0 to string's length-2
  2. Check whether charAt(i) == charAt(i+1) == charAt(i+2) if yes then delete the characters at i, i+1 and i+2 position and reset the counter i= (i-2)>0?(i-2):0.

Resetting counter at i=0 is very important at step 2 because there may be the case that previous i-2 and i-1 characters are same as i+3 characters so we should start checking triplets from two places before the current position of the string.

Code Snippet

public class RemoveTriplet {

	public static void main(String[] args) {

		//input
		StringBuilder inputString = new StringBuilder("aabbbaccddddc");
		
		//processing
		removeTriplet(inputString);
		
		//output
		System.out.println(inputString);
	}

	private static void removeTriplet(StringBuilder input) {
		int start = 0;

		while (start < input.length() - 2) {
			if (input.charAt(start) == input.charAt(start + 1)
					&& input.charAt(start) == input.charAt(start + 2)) {
				input.deleteCharAt(start);
				input.deleteCharAt(start);
				input.deleteCharAt(start);

				start = (start-2)>0?(start-2):0;
			} else {
				start = start + 1;
			}

		}
	}
}

Output

ccdc

The space complexity is O(1) and time complexity is O(n) for above solution approach discussed. In this article, we learned how to remove three consecutive duplicate characters from String.

Author
Author: Amit Gupta
Published On: 13/05/2017
Last revised On: 13/05/2017
View all articles by Amit Gupta

Share this post

Comments

Comments
comments powered by Disqus

Navigation

Social Media