Problem overview
Version 2 of the tr tool translates a whole set of characters at once. The method tr(vector<string> lines, string set1, string set2) gets two strings of equal length. Every character of a line that appears in set1 at index i becomes set2[i]. Other characters stay. The lines are returned joined by \n.
The sets contain ASCII characters taken literally, with 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 set1 = "abc" and set2 = "ABC" the result is "BAnAnA\nCherry".
Approach
Version 1 compared each character with one letter. Now each character must be checked against several, and each match has its own replacement. Scanning set1 for every character would work but repeats the same search many times. A lookup table does better: build it once from the two sets, then answer "what does this character become?" directly.
In C++ that table is an unordered_map<char, char>: the key is a character from set1 and the value is the partner at the same index in set2. Lookups take constant time on average. Because the input is ASCII, a plain array with one slot per character code would also work, but the map says directly what the table means and does not depend on the character codes.
Because each character is replaced by a lookup in the table and the output is built in a new string, a replacement is never translated a second time. That is why a swap works: when a becomes b the new b is appended to result and never meets the table again. A solution that edited the line in place, one letter at a time, would turn all the as into bs first and then all the bs, old and new, into as.
Step by step
- Create an
unordered_map<char, char>namedmapto hold the translation table. - Loop over the positions of
set1withint i. The sets have equal length, so everyiis valid in both. - Store the pair with
map[set1[i]] = set2[i];. The square brackets add the key if it is not there yet. - Create an empty
resultstring. - Loop over the lines with
int i. - Add a newline when
i > 0, so the first line gets none. - Loop over the characters of
lines[i]withint j. - Save the current character in a
charnamedch. - If
map.count(ch)is non-zero, append the replacementmap[ch]. - Otherwise, append
chitself. - Return
resultafter both outer loops finish.
The solution in C++
class Solution {
public:
string tr(vector<string> lines, string set1, string set2) {
unordered_map<char, char> map;
for (int i = 0; i < set1.size(); i++) {
map[set1[i]] = set2[i];
}
string result;
for (int i = 0; i < lines.size(); i++) {
if (i > 0) result += "\n";
for (int j = 0; j < lines[i].size(); j++) {
char ch = lines[i][j];
if (map.count(ch)) result += map[ch];
else result += ch;
}
}
return result;
}
};
The C++ details to know:
operator[]inserts. Readingmap[x]for a key that is missing adds it with a default value, which is'\0'for achar. Starting from an empty map, one such read makes its size 1. The solution avoids the trap by checkingmap.count(ch)first, somap[ch]only runs for keys that exist.countas a yes/no. For anunordered_mapit returns 0 or 1, so it works directly as a condition.map.find(ch) != map.end()means the same.- Later pairs overwrite earlier ones. Assigning through
[]replaces an existing key's value. The lesson guarantees thatset1has no repeats, so this does not come up. - The name
map. It is also the name of a standard container,std::map. As a local variable it hides that name inside the function, which is fine here but worth avoiding in larger programs. - Characters are keys.
charworks as a hash-map key without any extra code, and upper and lower case are different keys.
Complexity
Building the table takes one step per character of set1. Translating takes one lookup per character of the input, and each lookup is constant time on average. The total time is proportional to the length of set1 plus the total number of input characters. The table holds one entry per character of set1, and the result string holds a copy of the text.
Edge cases and common mistakes
- Swapping.
{"abba"}with"ab"and"ba"returns"baab". - Several replacements in one line.
{"hello world"}with"lo"and"01"returns"he001 w1r0d". - Characters not in the set.
{"xyz", ""}with"abc"and"ABC"returns"xyz\n":xyzis unchanged and the empty second line stays, so the result ends with a newline. - Case.
{"aAa"}with"a"and"b"gives"bAb". - Using
map[ch]without checking. Looking up every character through[]would fill the map with entries that translate to'\0'and would write null characters into the output. - Editing the line while reading it. This breaks the "all at once" rule, as explained above.
- Sets of different lengths. The lesson guarantees equal lengths. If
set2were shorter,set2[i]would read past its end, which gives wrong results or undefined behaviour, so check the lengths first in any code that accepts other input. - Empty input. An empty vector returns
"".
Testing
| lines | set1, set2 | result |
|---|---|---|
{"banana", "cherry"} | "abc", "ABC" | "BAnAnA\nCherry" |
{"abba"} | "ab", "ba" | "baab" |
{"hello world"} | "lo", "01" | "he001 w1r0d" |
{"xyz", ""} | "abc", "ABC" | "xyz\n" |
{"aAa"} | "a", "b" | "bAb" |
The next version builds on this one.
