Start learning free

LESSON 398 OF 414 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: tr v2 — Set Translation in TypeScript

Practice

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

    Tr V2 in TypeScript

    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free