Microsoft Online Assessment (OA) - 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.

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

Try it yourself


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