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
- Create the map:
let map = new Map<string, string>(). Keys are the characters to look for, values their replacements. - Loop over
set1withi. Both sets have the same length, soiis valid in both. - Store each pair:
map.set(set1[i], set2[i]). - Create
result, an emptystring[]for the translated lines. - Loop over the lines with
i. - Create
out, an empty string, for the translated line. Making it inside the loop gives each line a fresh one. - Loop over the characters of the line with
j. - Read the character into
ch. - Append the replacement when
map.has(ch), andchitself otherwise, using the conditional operatortest ? a : b. - Push
outontoresultafter the inner loop. - 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 typestring | undefined, because a missing key givesundefined. Themap.has(ch)test makes sure the lookup succeeds. Without it, appending the result ofgetfor 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. Replacingawithbacross the whole line first and thenbwithagives"aaaa". - Missing keys. Characters outside
set1must stay.["hello world"]with"lo"and"01"gives"he001 w1r0d": the lettersh,e,w,r,dand the space are untouched. - Forgetting
has.out += map.get(ch)alone appends"undefined"for every character that is not inset1. - Empty lines. An empty line gives an empty
outand 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
| Input | Result |
|---|---|
["banana", "cherry"], "abc", "ABC" | "BAnAnA\nCherry" |
["abba"], "ab", "ba" | "baab" |
["hello world"], "lo", "01" | "he001 w1r0d" |
