# String Without 3 Identical Consecutive Letters Microsoft OA 2023

Microsoft OA 2023 Question String Without 3 Identical Consecutive Letters or Longest string without 3 consecutive characters. We provide solution to Microsoft Online Assessment Questions and do check out our Microsoft OA 2023 Questions List below.

## String Without 3 Identical Consecutive Letters Solution

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

Example 1:

Input: ssupppss

Output: ssuppss

Explanation:

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

Example 2:

Input: `uvuuu`

Output: `uvuu`

Explanation:

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”.

Also See: Amazon OA Online Assessment 2023 Questions and Answers

### SOLUTION

Program Python: String Without 3 Identical Consecutive Letters Solution in Python

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

Edge Cases:
1. Empty 2. originally valid

Approaches:
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)
print(solution("aaasuaaa"))``````

Program: Longest string without 3 consecutive characters Solution in 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;
res.push_back(s[0]);
for (int i = 1; i < s_len; ++i) {
if(s[i] == s[i-1]) {
prev_count++;
}
else {
prev_count = 1;
}
if(prev_count < MAX_COUNT) {
res.push_back(s[i]);
}
}
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]) {
res.push_back(s[i]);
}
}
return res;
}
int main() {