String Without 3 Identical Consecutive Letters

Microsoft Online Assessment Question String Without 3 Identical Consecutive Letters or Longest string without 3 consecutive characters.

String Without 3 Identical Consecutive Letters

Given a string str having letters, shrink the string to no more than 2 character consecutively exists.

Also See: Microsoft Online Assessment Questions and Solution

Example 1:

Input: ssupppss

Output: ssuppss


Here “p” is repeated 3 times so it’s deleted

Example 2:

Input: uvuuu

Output: uvuu


Here we can see that “u” was repeated 3 times so it’s deleted, if the letters are “uuuu” then it will be “uu” the letter cannot be more then 2 times in case of “uuuuu” it will be “uu”.


Program Python:

Brief: Shrink the string to no more than 2 character consecutively exists

Edge Cases:
1. Empty 2. originally valid

1. Traverse + Counter, when exceeds 2, adding 2 and find next different one, if not exceeds 2 but different, add the exact amount characters

  1. Group up, shrink the list to the maximum of length 2, then concatenate together, group could use itertools.groupby or manually
  2. Travese + Ordered Counter, generate the result finally

Let’s go with approach 2

from itertools import groupby

def solution(s):
    group = [list(l) for _, l in groupby(s)]
    group = ["".join(l[:2]) for l in group]
    return "".join(group)


Program C++:

#include <iostream>
#include <string>

using namespace std;

string solution2(const string & s) {
    const int MAX_COUNT = 3;
    int s_len = s.length();
    int prev_count = 1;
    string res;

    for (int i = 1; i < s_len; ++i) {

        if(s[i] == s[i-1]) {
        else {
            prev_count = 1;
        if(prev_count < MAX_COUNT) {
    return res;

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;

int main() {

    cout << solution("eedaaad") << endl;
    cout << solution("xxxtxxx") << endl;
    cout << solution("uuuuxaaaaxuuu") << endl;
    return 0;

Also See: AMCAT Study Materials, Preparation Guide

Also See: Amazon OA Online Assessment 2021 Questions and Answers

Microsoft Online Assessment 2021 Questions

Leave a Comment