Start learning free

LESSON 27 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Tr V3 in Rust: Deleting Characters with a HashSet

Practice Read the full explanation

Build a version of the Unix tr -d command. Given a list of lines and a string chars, remove every character that appears in chars from each line, then return the lines joined by newline characters (\n).

Notes: chars is a non-empty ASCII string whose characters are taken literally (no ranges). Upper and lower case are different characters. A line can become empty after deleting, and then it stays as an empty line in the output.

Function signature:

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

Example:

Input: lines = ["banana", "apple"], chars = "aeiou"

Output: "bnn\nppl"

When printed:
bnn
ppl

Put each character of chars into a HashSet<char> for O(1) lookup. Walk every line and append characters that are NOT in the set.

The full solution:
impl Solution {
    fn tr_delete(lines: Vec<String>, chars: String) -> String {
        let mut set = HashSet::new();
        for ch in chars.chars() {
            set.insert(ch);
        }
        let mut result = String::new();
        for i in 0..lines.len() {
            if i > 0 {
                result.push('\n');
            }
            for ch in lines[i].chars() {
                if !set.contains(&ch) {
                    result.push(ch);
                }
            }
        }
        return result;
    }
}

STEP 1 OF 11
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Tr V3 in Rust, explained

    Problem overview

    Version 3 mirrors tr -d. tr_delete(lines, chars) removes from every line each character that appears in chars, then returns the lines joined by \n. The string chars is non-empty ASCII, its characters are literal, and case matters. A line can become empty after deletion, and it then stays in the output as an empty line. The previous version translated characters through a map. This one only needs to know whether a character is in a group.

    For ["banana", "apple"] with "aeiou", the vowels vanish and the result is "bnn\nppl".

    Approach

    For each character of each line, ask one question: is it one of the characters to delete? A HashSet answers that in constant time on average. Build the set once from chars, then copy every character that is not in the set into the output.

    This solution builds one big String directly instead of collecting lines in a vector. That changes how the newlines work: there is no join, so the loop itself pushes a '\n' before every line except the first. A newline between two lines, and none after the last, is exactly what join would have produced.

    Following "banana" with the set of vowels: b isn't in the set and is kept, a is in it and is skipped, n is kept, and so on, which leaves "bnn". In "apple", the a and the final e are skipped and "ppl" remains. The newline pushed between the two lines is not affected by any deletion, because it is added by the line loop and not by the character loop, and it is never tested against the set.

    Step by step

    1. Create set, an empty HashSet, with let mut.
    2. Loop over the characters of chars with chars.chars(). The function parameter and its method are both named chars, which is legal because one is a variable and the other a method.
    3. Insert each character into the set. A set stores each value once, so repeats in chars are harmless.
    4. Create result, an empty String. Everything is appended to its end.
    5. Loop over the line positions with for i in 0..lines.len().
    6. Check i > 0. The first line needs no newline before it.
    7. Push '\n' inside that check. A single character goes in single quotes.
    8. Loop over the characters of lines[i] with .chars().
    9. Test !set.contains(&ch), which is true for characters to keep.
    10. Push the character onto result inside that test. Characters in the set are skipped, which deletes them.
    11. Return result after both loops.

    The solution in Rust

    impl Solution {
        fn tr_delete(lines: Vec<String>, chars: String) -> String {
            let mut set = HashSet::new();
            for ch in chars.chars() {
                set.insert(ch);
            }
            let mut result = String::new();
            for i in 0..lines.len() {
                if i > 0 {
                    result.push('\n');
                }
                for ch in lines[i].chars() {
                    if !set.contains(&ch) {
                        result.push(ch);
                    }
                }
            }
            return result;
        }
    }
    

    Rust details:

    • HashSet and its type. It lives in std::collections (use std::collections::HashSet; in a standalone program). The element type, char, is inferred from the insert call.
    • contains takes a reference. That is why the call is set.contains(&ch), not set.contains(ch).
    • push against push_str. String::push appends one char, written in single quotes, such as '\n'. push_str appends a whole &str, written in double quotes.
    • Indexing lines[i]. This borrows the line for the loop and doesn't move it out of the vector.
    • Characters. chars() yields char values, so the code compares whole characters and never needs to index into a string by byte.

    The same idea can be written with an iterator. line.chars().filter(|c| !set.contains(c)).collect::<String>() keeps the characters that are not in the set and gathers them into a new String; on "banana" with the vowels set it gives "bnn". The lesson uses explicit loops instead, which makes each step visible. In the filter closure, c is already a reference to the character, so contains takes it without an extra &.

    Complexity

    Time: O(C + L), where C is the length of chars and L the total length of the lines: one insertion per member, then one average-constant-time lookup per line character. Space: O(C + L) for the set and the result.

    Edge cases and common mistakes

    • A line that becomes empty. ["aaa", "bab", "x"] with "a" gives "\nbb\nx". The first line is now empty, but its newline separator is still there.
    • Case. ["Aa"] with "a" gives "A". Only the lowercase letter matches.
    • Empty list. The loop never runs and the result is "".
    • An empty line among others. ["", "q"] gives "\nq", because the newline before the second line is pushed regardless.
    • Repeated characters in chars. ["abc"] with "aab" gives "c". The set just stores a once.
    • Newline placement. Pushing a newline after every line, or when i is the last position, would give a trailing newline the tests don't expect.
    • Deleting the newline too. The separators are written outside the inner loop. If the delete set contained a newline character, it would still not remove them, because the set only filters the characters of the lines.
    • Forgetting the !. Without it, the code keeps only the characters that should be deleted.

    Testing

    • ["banana", "apple"] with "aeiou" gives "bnn\nppl".
    • ["aaa", "bab", "x"] with "a" gives "\nbb\nx".
    • ["Aa"] with "a" gives "A".
    • ["", "q"] with "a" gives "\nq".
    • [] with "a" gives "".
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free