Start learning free

LESSON 624 OF 671 · PROJECTS: COMMAND-LINE TOOLS

Tr V2 in JavaScript: Translating a Set of Characters with a Map

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:

tr(lines, set1, set2)

Example:

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

Output: "BAnAnA\nCherry"

When printed:
BAnAnA
Cherry

Build a Map from each char of set1 to the same-index char of set2. Then walk every line and replace each char via the map (or pass it through unchanged).

let map = new Map();
for (let i = 0; i < set1.length; i++) {
    map.set(set1[i], set2[i]);
}
// per char: map.has(ch) ? map.get(ch) : ch


The full solution:
class Solution {
    tr(lines, set1, set2) {
        let map = new Map();
        for (let i = 0; i < set1.length; i++) {
            map.set(set1[i], set2[i]);
        }
        let result = [];
        for (let i = 0; i < lines.length; i++) {
            let out = "";
            for (let j = 0; j < lines[i].length; j++) {
                let ch = lines[i][j];
                out += map.has(ch) ? map.get(ch) : ch;
            }
            result.push(out);
        }
        return result.join("\n");
    }
}

STEP 1 OF 11
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Tr V2 in JavaScript, explained

    Problem overview

    The second version of the tr tool translates a whole set of characters at once. The method tr(lines, set1, set2) receives an array of lines and two strings of equal length. Every character of a line that appears in set1 at index i becomes set2[i]. Other characters are unchanged. The result is the lines joined by \n.

    The sets contain only ASCII characters, set1 has no repeated character, and the characters are literal: there are no ranges such as a-z. Lines may be empty.

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

    Approach: a lookup table, then one pass over each line

    Version 1 swapped a single character. For a set, repeated swapping would be wrong: with set1 = "ab" and set2 = "ba", replacing every a by b and then every b by a would turn everything into a. The task requires that all replacements happen at once, so that "abba" becomes "baab".

    The fix is to decide each character independently, using the original character. First build a Map from each character of set1 to its partner in set2. Then walk through every line character by character: if the map has the character as a key, output its value; otherwise output the character itself. Each output character depends only on the original one, never on an earlier replacement.

    A simpler-looking alternative is to call set1.indexOf(ch) for each character and use that index into set2. It gives the same answer, but it rescans set1 for every character. The map is built once and answers each question directly, which is the point of this lesson: a lookup table turns a repeated search into a single step.

    Step by step

    1. Create an empty Map named map. Its keys are the characters to look for and its values are their replacements.
    2. Loop over the positions of set1 with i. Both sets have the same length, so each i is valid in both.
    3. Store the pair with map.set(set1[i], set2[i]).
    4. Create result, an empty array for the translated lines.
    5. Loop over the lines with i again, for a new loop after the first one.
    6. Create out, an empty string for the current line. A fresh one per line keeps lines separate.
    7. Loop over the characters of lines[i] with j.
    8. Take the character at position j into ch.
    9. Append the translation. map.has(ch) asks whether ch is a key, map.get(ch) returns its value, and a ? : expression picks the replacement or ch itself. out += adds the choice to the line.
    10. Push out onto result after the inner loop, once per line.
    11. Return result.join("\n") after the outer loop.

    The solution in JavaScript

    class Solution {
        tr(lines, set1, set2) {
            let map = new Map();
            for (let i = 0; i < set1.length; i++) {
                map.set(set1[i], set2[i]);
            }
            let result = [];
            for (let i = 0; i < lines.length; i++) {
                let out = "";
                for (let j = 0; j < lines[i].length; j++) {
                    let ch = lines[i][j];
                    out += map.has(ch) ? map.get(ch) : ch;
                }
                result.push(out);
            }
            return result.join("\n");
        }
    }
    

    The details to know:

    • Indexing a string. set1[i] and lines[i][j] give one-character strings. Because the lesson's text is ASCII, each index is one visible character.
    • map.has before map.get. get returns undefined for a missing key, and appending undefined would write the word "undefined" into the line. The has test prevents that.
    • The precedence of ? :. In out += map.has(ch) ? map.get(ch) : ch, the whole conditional is evaluated first and its result is appended.
    • Strings are immutable. out += builds a new string each time and stores it back in out. For ordinary line lengths that is fine.
    • Keys are compared by value. Map keys that are strings match when their text is equal, so the key "a" built from set1 matches the character "a" read from a line.

    Tracing the swap

    For the line "abba" with set1 = "ab" and set2 = "ba", the map holds a to b and b to a. The value of out after each character of the line is:

    jchout after the step
    0"a""b"
    1"b""ba"
    2"b""baa"
    3"a""baab"

    Each step reads the original character from the line, never from out, so the letter that was just written cannot be translated a second time. Compare this with replacing in two passes, as in "abba".split("a").join("b").split("b").join("a"): the first pass gives "bbbb", the second turns all of it into "aaaa". The map lookup avoids that problem.

    Complexity

    Let k be the length of set1 and N the total number of characters in all lines.

    Time: O(k + N). Building the map takes k steps. Each character of the lines costs one map lookup, which is constant time on average.

    Space: O(k + N): the map has k entries, and the translated lines are the same size as the input.

    Edge cases and common mistakes

    • Swapping two characters. ["abba", "cab"] with "ab" and "ba" gives "baab\ncba". A chain of one-letter replacements would not do this.
    • Several characters mapped to digits. ["hello world"] with "lo" and "01" gives "he001 w1r0d".
    • Empty lines. ["", "xyz"] with "x" and "y" gives "\nyyz". The first line stays empty.
    • Special characters are literal. ["a.b"] with "." and "!" gives "a!b", with no regular expression involved.
    • Declaring out outside the line loop. The lines would run together into one growing string.
    • Appending map.get(ch) without checking has. Every character outside set1 would turn into undefined.

    Testing

    • ["banana", "cherry"], "abc", "ABC" gives "BAnAnA\nCherry".
    • ["abba", "cab"], "ab", "ba" gives "baab\ncba".
    • ["hello world"], "lo", "01" gives "he001 w1r0d".
    • ["", "xyz"], "x", "y" gives "\nyyz".
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free