Rust Interview Puzzles: Remove adjacent duplicate characters

Rust Interview Puzzles: Remove adjacent duplicate characters

·

1 min read

Problem

For a provided string str we need to remove adjacent duplicate characters. It is acceptable for this puzzle to return a new string as a result instead of doing the actual in-place mutation.

Examples:

Input strOutput
aaabccccdddeabcde
abbbcabc
aaaa

Solution

fn remove_adjacent_duplicate_chars(str: &str) -> String {
    let mut prev_char: Option<char> = None;

    str.chars()
        .filter(|&char| {
            if Some(char) != prev_char {
                prev_char = Some(char);
                true
            } else {
                false
            }
        })
        .collect()
}

Explanation

A simple solution is to iterate once over the string characters and filter in only chars not equal to the previously saved character prev_char. For such a character we save it to prev_char and filter it in (return true), otherwise, we filter it out (return false).

Complexity

The time complexity of the solution is O(n) (where n is the length of the input string).


Rust Playground with this code