Start learning free

LESSON 26 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Tr V2 in TypeScript: Translating a Character Set 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: string[], set1: string, set2: string): string

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<string, string>();
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: string[], set1: string, set2: string): string {
        let map = new Map<string, string>();
        for (let i = 0; i < set1.length; i++) {
            map.set(set1[i], set2[i]);
        }
        let result: string[] = [];
        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

    TYPESCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Tr V2 in TypeScript, explained

    Problem overview

    The second version of the tr project translates a whole set of characters at once. The method tr(lines: string[], set1: string, set2: string) receives lines and two strings of equal length. Every character of a line that sits at index i of set1 becomes set2[i]. Characters that are not in set1 stay. The result is the lines joined by \n.

    The characters are ASCII and literal (no ranges such as a-z), and set1 has no repeated character. All replacements happen at once, so set1 = "ab" with set2 = "ba" swaps the two letters. For ["banana", "cherry"] with "abc" and "ABC" the result is "BAnAnA\nCherry".

    Approach: build a lookup table, then translate character by character

    The previous version swapped one character with split and join. With several pairs, that idea is the trap: swapping a for b and then b for a on "abba" would turn everything into a. Done one pair after another, the second pass also changes the characters the first pass produced. Doing every replacement in one pass avoids that.

    So the code first builds a Map from each character of set1 to its partner in set2. Then it visits every character of every line exactly once. If the map has the character, it appends the partner; otherwise it appends the character itself. Because each character is looked up in the original table and never revisited, a swap such as "ab" to "ba" works: "abba" becomes "baab".

    A Map is not the only way. You could call set1.indexOf(ch) for each character: a result of -1 means "not in the set", and any other result is the position to read in set2. That needs no extra structure, but it scans set1 for every character of every line. The map answers each lookup directly, and the table is built once, before the lines are touched.

    The notes in the statement make the table safe to build. set1 has no repeated character, so no key is stored twice. (Setting a key that already exists would silently replace its value, so with repeats the last pair would win.) The sets have the same length, so every set2[i] exists.

    On the first example, the table holds a to A, b to B and c to C. In "banana", the b and each a are found in the table and replaced, while each n is not, so it is copied unchanged. That gives "BAnAnA". In "cherry" only the first letter is in the table, and the rest of the word is copied as it is, giving "Cherry".

    Step by step

    1. Create the map: let map = new Map<string, string>(). Keys are the characters to look for, values their replacements.
    2. Loop over set1 with i. Both sets have the same length, so i is valid in both.
    3. Store each pair: map.set(set1[i], set2[i]).
    4. Create result, an empty string[] for the translated lines.
    5. Loop over the lines with i.
    6. Create out, an empty string, for the translated line. Making it inside the loop gives each line a fresh one.
    7. Loop over the characters of the line with j.
    8. Read the character into ch.
    9. Append the replacement when map.has(ch), and ch itself otherwise, using the conditional operator test ? a : b.
    10. Push out onto result after the inner loop.
    11. Return result.join("\n") after the outer loop.

    The solution in TypeScript

    class Solution {
        tr(lines: string[], set1: string, set2: string): string {
            let map = new Map<string, string>();
            for (let i = 0; i < set1.length; i++) {
                map.set(set1[i], set2[i]);
            }
            let result: string[] = [];
            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");
        }
    }
    

    Language details

    • Map<string, string> is a generic type: the angle brackets name the key and value types. They are checked by the compiler and erased from the generated JavaScript.
    • map.get(ch) has the type string | undefined, because a missing key gives undefined. The map.has(ch) test makes sure the lookup succeeds. Without it, appending the result of get for a missing key would add the text "undefined" to the line.
    • s[i] on a string gives a one-character string, so the keys and the values are strings of length one.
    • out += ... builds a new string each time, since strings are immutable. For line-sized text that is fine.

    Complexity

    Building the map takes O(k) for k characters in set1. Translating visits every character of every line once, with an average O(1) map lookup, so the time is O(k + N) for N characters of input. The map uses O(k) space and the output O(N).

    Edge cases and common mistakes

    • Sequential replacement. Translating "abba" with "ab" to "ba" gives "baab" in a single pass. Replacing a with b across the whole line first and then b with a gives "aaaa".
    • Missing keys. Characters outside set1 must stay. ["hello world"] with "lo" and "01" gives "he001 w1r0d": the letters h, e, w, r, d and the space are untouched.
    • Forgetting has. out += map.get(ch) alone appends "undefined" for every character that is not in set1.
    • Empty lines. An empty line gives an empty out and stays as an empty line.
    • Resetting out. Declare it inside the outer loop, not before it. Declared outside, every line would be appended to the previous ones, and the output would grow with each line instead of holding separate lines.

    Testing

    InputResult
    ["banana", "cherry"], "abc", "ABC""BAnAnA\nCherry"
    ["abba"], "ab", "ba""baab"
    ["hello world"], "lo", "01""he001 w1r0d"
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free