String Without 3 Identical Consecutive Letters

Microsoft Online Assessment Question String Without 3 Identical Consecutive Letters

String Without 3 Identical Consecutive Letters

Given a string S having lowercase English letters, returns a string with no instances of three identical consecutive letters, obtained from S by deleting the minimum possible number of letters.

Also See: Microsoft Online Assessment Questions and Solution

Example 1:

Input: eedaaad

Output: eedaad


One occurrence of letter a is deleted.

Example 2:

Input: xxxtxxx

Output: xxtxx


Note that letter x can occur more than three times in the returned string if the occurrences are not consecutive.

Example 3:

Input: uuuuxaaaaxum

Output: uuxaaxum


Program Python:

def filter_string(s: str) -> str:
    news = s[0:2]
    for i in range(2, len(s)):
        # Do not append if the previous chars are the same
        if s[i] != s[i - 1] or s[i] != s[i - 2]:
            news += s[i]
    return news
if __name__ == '__main__':
    s = input()
    res = filter_string(s)

Program Java:

import java.util.Scanner;
class Solution {
    public static String filterString(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 2; i < s.length(); ++i) {
            if (s.charAt(i) != s.charAt(i - 1) || s.charAt(i) != s.charAt(i - 2)) {
        return sb.toString();
    public static void main(String[] args) {
        Scanner scanner = new Scanner(;
        String s = scanner.nextLine();
        String res = filterString(s);

Program C++:

string solution(const string & s) {
    int s_len = s.length();
    string res(s.begin(), s.begin()+2);
    for (int i = 2; i < s_len; ++i) {
        if (s[i] != s[i-1] || s[i] != s[i-2]) {
    return res;

Also See: AMCAT Study Materials, Preparation Guide

Also See: Amazon OA 2021 (Online Assessment) Questions Preparation

Microsoft Online Assessment 2021 Questions

Leave a Comment