String Without 3 Identical Consecutive Letters

Page Contents

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`

Explanation:

One occurrence of letter `a` is deleted.

Example 2:

Input: `xxxtxxx`

Output: `xxtxx`

Explanation:

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`

Solution

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)
print(res)```

Program Java:

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

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]) {
res.push_back(s[i]);
}
}
return res;
}```

Also See: AMCAT Study Materials, Preparation Guide

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

Microsoft Online Assessment 2021 Questions