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

Explanation:

One occurrence of the letter a is deleted.

Example 2:

Input: xxxtxxx

Output: xxtxx

Explanation:

Note that the 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

Implementation

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
8
9if __name__ == '__main__':
10    s = input()
11    res = filter_string(s)
12    print(res)
13
1import java.util.Scanner;
2
3class Solution {
4    public static String filterString(String s) {
5        StringBuilder sb = new StringBuilder();
6        sb.append(s.charAt(0));
7        sb.append(s.charAt(1));
8        for (int i = 2; i < s.length(); ++i) {
9            if (s.charAt(i) != s.charAt(i - 1) || s.charAt(i) != s.charAt(i - 2)) {
10                sb.append(s.charAt(i));
11            }
12        }
13        return sb.toString();
14    }
15
16    public static void main(String[] args) {
17        Scanner scanner = new Scanner(System.in);
18        String s = scanner.nextLine();
19        scanner.close();
20        String res = filterString(s);
21        System.out.println(res);
22    }
23}
24
1function filterString(s) {
2    const res = [s.charAt(0), s.charAt(1)];
3    for (let i = 2; i < s.length; ++i) {
4        if (s.charAt(i) !== s.charAt(i - 1) || s.charAt(i) !== s.charAt(i - 2)) {
5            res.push(s[i]);
6        }
7    }
8    return res.join('');
9}
10
11function* main() {
12    const s = yield;
13    const res = filterString(s);
14    console.log(res);
15}
16
17class EOFError extends Error {}
18{
19    const gen = main();
20    const next = (line) => gen.next(line).done && process.exit();
21    let buf = '';
22    next();
23    process.stdin.setEncoding('utf8');
24    process.stdin.on('data', (data) => {
25        const lines = (buf + data).split('\n');
26        buf = lines.pop();
27        lines.forEach(next);
28    });
29    process.stdin.on('end', () => {
30        buf && next(buf);
31        gen.throw(new EOFError());
32    });
33}
34

Got a question?ย Ask the Teaching Assistantย anything you don't understand.

Still not clear? Ask in the Forum, ย Discordย orย Submitย the part you don't understand to our editors.

โ†
โ†‘TA ๐Ÿ‘จโ€๐Ÿซ