Start learning free

LESSON 28 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Tr V4 in Rust: Squeezing Repeats (-s)

Practice Read the full explanation

Build a version of the Unix tr -s command. Given a list of lines and a string chars, collapse consecutive runs of any character that appears in chars to a single occurrence. Other characters are unchanged. Return the lines joined by newline characters (\n).

Notes: chars is a non-empty ASCII string whose characters are taken literally (no ranges). Only runs of the same character from chars are collapsed; all other characters, and runs of characters not in chars, stay as they are. Upper and lower case are different characters. Lines may be empty.

Function signature:

fn tr_squeeze(lines: Vec<String>, chars: String) -> String

Example:

Input: lines = ["aaabbb", "abaa"], chars = "a"

Output: "abbb\naba"

When printed:
abbb
aba

Collect every char of chars into a HashSet<char>. Walk each line tracking prev (the last char you kept); skip the current char only if it's in the squeeze set AND equals prev.

The full solution:
impl Solution {
    fn tr_squeeze(lines: Vec<String>, chars: String) -> String {
        let squeeze: HashSet<char> = chars.chars().collect();
        let mut result: Vec<String> = Vec::new();
        for line in &lines {
            let mut out = String::new();
            let mut prev = '\0';
            for ch in line.chars() {
                if squeeze.contains(&ch) && ch == prev {
                    continue;
                }
                out.push(ch);
                prev = ch;
            }
            result.push(out);
        }
        result.join("\n")
    }
}

STEP 1 OF 12
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Tr V4 in Rust, explained

    Problem overview

    Version 4 mirrors tr -s. tr_squeeze(lines, chars) collapses each run of the same character into a single character, but only for characters that appear in chars. Other characters, including repeated ones that are not in chars, are left as they are. The lines are joined by \n. The string chars is non-empty ASCII, characters are literal, case matters, and lines may be empty. The previous version deleted characters; this one keeps the first of each run.

    For ["aaabbb", "abaa"] with "a", the result is "abbb\naba". The run aaa shrinks to a, the b run is untouched because b isn't in chars, and in abaa only the final aa shrinks.

    Approach

    A character is dropped only when two things are true: it is in the squeeze set, and it is the same as the character just before it in the output. So the loop needs a fast membership test (a HashSet) and the previous character (prev). Each line starts with prev set to '\0', the null character, which doesn't occur in ordinary text, so the first character of a line never counts as a repeat.

    Because prev is updated after every kept character and a dropped one equals it anyway, prev always holds the last character written. A run of any length therefore reduces to its first character.

    On "abaa" with "a": the first a is kept, because prev is still '\0'. The b is kept (not in the set). The next a is kept, because prev is now b. The last a equals prev and is in the set, so it is dropped. The result is "aba". On "aaabbb", the first a is kept, the next two are dropped, and all three b characters are kept because b isn't in the set, giving "abbb".

    Step by step

    1. Build the set with chars.chars().collect() into a HashSet<char> named squeeze. The type on the left tells collect what to build.
    2. Create result, an empty Vec<String>.
    3. Loop over the lines with for line in &lines.
    4. Create out, a fresh String for each line.
    5. Create prev as '\0', since nothing precedes the first character.
    6. Loop over the characters with line.chars().
    7. Test for a repeat: squeeze.contains(&ch) && ch == prev.
    8. Skip the character with continue, which jumps straight to the next one.
    9. Otherwise push ch onto out.
    10. Set prev to ch, so the next character compares against this one.
    11. Push out onto result after the inner loop. An emptied line stays as an empty line.
    12. Join with "\n" as the function's last expression.

    The solution in Rust

    impl Solution {
        fn tr_squeeze(lines: Vec<String>, chars: String) -> String {
            let squeeze: HashSet<char> = chars.chars().collect();
            let mut result: Vec<String> = Vec::new();
            for line in &lines {
                let mut out = String::new();
                let mut prev = '\0';
                for ch in line.chars() {
                    if squeeze.contains(&ch) && ch == prev {
                        continue;
                    }
                    out.push(ch);
                    prev = ch;
                }
                result.push(out);
            }
            result.join("\n")
        }
    }
    

    Rust details:

    • collect needs a target type. It can build many collections, so the annotation HashSet<char> decides which one. In a standalone program, add use std::collections::HashSet;.
    • The '\0' literal. It is a char, the character with code 0. Its type is fixed by the first use of prev in a comparison with ch.
    • continue in the inner loop. It skips the rest of that iteration only, so neither the push nor the update of prev runs for a dropped character. The outer loop is not affected.
    • Last-expression return. result.join("\n") has no semicolon and no return, so it is the function's value.

    Notice that a dropped character never changes prev, because continue jumps over that line. That is correct, since a dropped character is equal to prev already, so the value would not change anyway.

    Complexity

    Time: O(C + L), where C is the length of chars and L the total length of the lines: building the set, then one pass with average-constant-time lookups. Space: O(C + L) for the set, the output lines and the joined string.

    Edge cases and common mistakes

    • Only listed characters are squeezed. ["aabbcc", "a b c"] with "ab " gives "abcc\na b c". The a, b and space runs shrink, but cc stays because c isn't listed.
    • Case. ["aAaa"] with "a" gives "aAa". Only the final aa is a run, as A is a different character and breaks the run.
    • Alternating characters. ["abab"] with "ab" gives "abab", since no character equals the one just before it.
    • Empty lines. ["", "zz"] with "a" gives "\nzz": the empty line stays and the z run isn't squeezed.
    • The null character itself. The sentinel only works because '\0' isn't expected in the text. If a line did start with a null character and chars contained one, that first character would be treated as a repeat and dropped: "\0\0x" with the set "\0" comes out as just "x". The task's lines are ordinary ASCII text, so it doesn't arise.
    • Comparing with the wrong character. prev must be updated after every kept character, listed or not. Otherwise the comparison for the next character would look at a stale value.
    • Carrying prev across lines. It is created inside the line loop, so a line's first character is never compared with the previous line's last.

    Testing

    • ["aaabbb", "abaa"] with "a" gives "abbb\naba".
    • ["aabbcc", "a b c"] with "ab " gives "abcc\na b c".
    • ["aAaa"] with "a" gives "aAa".
    • ["", "zz"] with "a" gives "\nzz".
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free