Start learning free

LESSON 26 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Tr V2 in Rust: Translating a Set with HashMap

Practice Read the full explanation

Build a more powerful version of the Unix tr command. Given a list of lines and two equal-length strings set1 and set2, replace every character in each line that appears in set1 at index i with set2[i]. Characters not in set1 are unchanged. Return the lines joined by newline characters (\n).

Notes: set1 and set2 have the same length, contain only ASCII characters, and set1 has no repeated character. Characters are taken literally: there are no ranges like a-z. All replacements happen at once, so set1 = "ab", set2 = "ba" swaps the two letters. Lines may be empty.

Function signature:

fn tr(lines: Vec<String>, set1: String, set2: String) -> String

Example:

Input: lines = ["banana", "cherry"], set1 = "abc", set2 = "ABC"

Output: "BAnAnA\nCherry"

When printed:
BAnAnA
Cherry

Build a HashMap<char, char> from each char of set1 to the matching char of set2. Then walk each line and translate via map.get(&ch).unwrap_or(&ch).

let mut map = HashMap::new();
for (a, b) in set1.chars().zip(set2.chars()) {
    map.insert(a, b);
}
// per char: *map.get(&ch).unwrap_or(&ch)


The full solution:
impl Solution {
    fn tr(lines: Vec<String>, set1: String, set2: String) -> String {
        let mut map = HashMap::new();
        for (a, b) in set1.chars().zip(set2.chars()) {
            map.insert(a, b);
        }
        let mut result = Vec::new();
        for line in lines {
            let mut out = String::new();
            for ch in line.chars() {
                out.push(*map.get(&ch).unwrap_or(&ch));
            }
            result.push(out);
        }
        return result.join("\n");
    }
}

STEP 1 OF 10
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Tr V2 in Rust, explained

    Problem overview

    Version 2 of tr translates whole sets of characters. tr(lines, set1, set2) receives lines and two strings of equal length. Each character of a line that appears in set1 at index i becomes the character at index i of set2. Other characters stay. The lines are joined by \n. The sets hold only ASCII characters, set1 has no repeats, characters are literal (no ranges such as a-z), and lines may be empty. The previous version swapped a single character.

    For ["banana", "cherry"] with set1 = "abc" and set2 = "ABC", the result is "BAnAnA\nCherry": a becomes A, b becomes B, c becomes C, and the other letters are untouched.

    Approach

    Looping over set1 for every character of every line would work, but a lookup table is cleaner. Build a HashMap once, with each character of set1 as a key and its partner from set2 as the value. Then walk over every line character by character, look each character up, and push either its replacement or the character itself.

    Because every character is looked up in the original table and written to a separate output string, all replacements happen at once. With set1 = "ab" and set2 = "ba", the line "abba" becomes "baab": the new b produced from an a is never translated again. A chain of one-after-another replace calls would not have this property: "abba".replace("a", "b").replace("b", "a") gives "aaaa", because the second call also changes the b characters the first call just created. That is why the table is built first and applied in a single pass.

    On the example, the table holds three pairs: a to A, b to B and c to C. For "banana" the lookups go b found (B), a found (A), n not found (stays n), then a, n, a again, which builds "BAnAnA" exactly as the example expects. In "cherry" only the leading c is in the table, so the result is "Cherry".

    Step by step

    1. Create map, an empty HashMap, with let mut. It records which character becomes which.
    2. Loop over both sets together. set1.chars().zip(set2.chars()) pairs the characters at the same position, and (a, b) names each pair.
    3. Insert the pair with insert(a, b): the key is the character to look for, the value its replacement.
    4. Create result, an empty vector for the translated lines.
    5. Loop over the lines with for line in lines.
    6. Create out, a fresh empty String for the line being translated, so lines don't mix.
    7. Loop over the characters of the line with line.chars().
    8. Push the replacement or the character itself, using the lookup expression explained below.
    9. Push out onto result after the inner loop, once per line.
    10. Join the lines with "\n" after the outer loop.

    The solution in Rust

    impl Solution {
        fn tr(lines: Vec<String>, set1: String, set2: String) -> String {
            let mut map = HashMap::new();
            for (a, b) in set1.chars().zip(set2.chars()) {
                map.insert(a, b);
            }
            let mut result = Vec::new();
            for line in lines {
                let mut out = String::new();
                for ch in line.chars() {
                    out.push(*map.get(&ch).unwrap_or(&ch));
                }
                result.push(out);
            }
            return result.join("\n");
        }
    }
    

    Rust details:

    • Inferred types. The map and the vector have no type annotations. Rust works out HashMap<char, char> from the insert call and Vec<String> from the push call. In a standalone program, HashMap comes from std::collections and needs use std::collections::HashMap; at the top.
    • Characters, not bytes. chars() yields char values, so the code works on whole characters. For the ASCII text in this task, that is the same as bytes.
    • The lookup line. map.get(&ch) returns an Option<&char>: a reference to the stored replacement, or None. unwrap_or(&ch) supplies a reference to ch itself when the key is absent. Both branches are references, so the * in front copies the char out of whichever one is chosen. char is a small Copy type, so that is cheap.
    • zip stops at the shorter side. With equal lengths, as promised, nothing is lost. With unequal lengths, the extra characters of the longer set would be ignored without any error.
    • Moving the lines. for line in lines consumes the vector, which is fine because lines isn't used after the loop.

    Complexity

    Time: O(S + L), where S is the length of the sets and L the total number of characters in the lines. Building the map takes S insertions, and each line character costs one average-constant-time lookup. Space: O(S + L) for the table, the translated lines and the joined result.

    Edge cases and common mistakes

    • Swapping letters. ["abba", "cab"] with "ab" and "ba" gives "baab\ncba". Translating in one pass is what makes a swap work.
    • Empty lines. Nothing is looked up in an empty line. ["", "Hello"] with "l" and "L" gives "\nHeLLo". The empty line stays an empty line.
    • Case. 'a' and 'A' are different keys. With "abc" and "ABC", an uppercase A in the input stays as it is.
    • Empty sets. With "" and "" the map stays empty and the lines come out unchanged.
    • Forgetting the *. out.push(map.get(&ch).unwrap_or(&ch)) tries to push a &char where a char is expected, and the compiler reports expected char, found &char.
    • Mixing up key and value. The character found in set1 is the key, because that is what you look up in the lines.

    Testing

    • ["banana", "cherry"] with "abc" and "ABC" gives "BAnAnA\nCherry".
    • ["abba", "cab"] with "ab" and "ba" gives "baab\ncba".
    • ["", "Hello"] with "l" and "L" gives "\nHeLLo".
    • ["abc"] with "" and "" gives "abc".
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free