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
- Create an empty
Mapnamedmap. Its keys are the characters to look for and its values are their replacements. - Loop over the positions of
set1withi. Both sets have the same length, so eachiis valid in both. - Store the pair with
map.set(set1[i], set2[i]). - Create
result, an empty array for the translated lines. - Loop over the lines with
iagain, for a new loop after the first one. - Create
out, an empty string for the current line. A fresh one per line keeps lines separate. - Loop over the characters of
lines[i]withj. - Take the character at position
jintoch. - Append the translation.
map.has(ch)asks whetherchis a key,map.get(ch)returns its value, and a? :expression picks the replacement orchitself.out +=adds the choice to the line. - Push
outontoresultafter the inner loop, once per line. - 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]andlines[i][j]give one-character strings. Because the lesson's text is ASCII, each index is one visible character. map.hasbeforemap.get.getreturnsundefinedfor a missing key, and appendingundefinedwould write the word "undefined" into the line. Thehastest prevents that.- The precedence of
? :. Inout += 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 inout. 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 fromset1matches 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:
| j | ch | out 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
outoutside the line loop. The lines would run together into one growing string. - Appending
map.get(ch)without checkinghas. Every character outsideset1would turn intoundefined.
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".
