Start learning free

LESSON 26 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Tr V2 in C++: Translating a Set of Characters with unordered_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:

string tr(vector<string> lines, string set1, string set2)

Example:

Input: lines = ["banana", "cherry"], set1 = "abc", set2 = "ABC"

Output: "BAnAnA\nCherry"

When printed:
BAnAnA
Cherry

Build an unordered_map<char, char> from each char of set1 to the matching char of set2. Then walk each line and translate via map.count(ch) + map[ch].

unordered_map<char, char> map;
for (int i = 0; i < set1.size(); i++) {
    map[set1[i]] = set2[i];
}
// per char: map.count(ch) ? map[ch] : ch


The full solution:
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;
    }
};

STEP 1 OF 11
    Ctrl + Enter to check

    C++ · PROJECTS: COMMAND-LINE TOOLS

    Tr V2 in C++, explained

    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

    1. Create an unordered_map<char, char> named map to hold the translation table.
    2. Loop over the positions of set1 with int i. The sets have equal length, so every i is valid in both.
    3. Store the pair with map[set1[i]] = set2[i];. The square brackets add the key if it is not there yet.
    4. Create an empty result string.
    5. Loop over the lines with int i.
    6. Add a newline when i > 0, so the first line gets none.
    7. Loop over the characters of lines[i] with int j.
    8. Save the current character in a char named ch.
    9. If map.count(ch) is non-zero, append the replacement map[ch].
    10. Otherwise, append ch itself.
    11. Return result after 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. Reading map[x] for a key that is missing adds it with a default value, which is '\0' for a char. Starting from an empty map, one such read makes its size 1. The solution avoids the trap by checking map.count(ch) first, so map[ch] only runs for keys that exist.
    • count as a yes/no. For an unordered_map it 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 that set1 has 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. char works 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": xyz is 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 set2 were 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

    linesset1, set2result
    {"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.

    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free