Start learning free

LESSON 26 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Tr V2 in C#: Character Mapping with a Dictionary

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:

public string Tr(List<string> lines, string set1, string set2)

Example:

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

Output: "BAnAnA\nCherry"

When printed:
BAnAnA
Cherry

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

Dictionary<char, char> map = new Dictionary<char, char>();
for (int i = 0; i < set1.Length; i++) {
    map[set1[i]] = set2[i];
}
// per char: map.ContainsKey(ch) ? map[ch] : ch


The full solution:
class Solution {
    public string Tr(List<string> lines, string set1, string set2) {
        Dictionary<char, char> map = new Dictionary<char, char>();
        for (int i = 0; i < set1.Length; i++) {
            map[set1[i]] = set2[i];
        }
        List<string> result = new List<string>();
        foreach (string line in lines) {
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < line.Length; j++) {
                char ch = line[j];
                sb.Append(map.ContainsKey(ch) ? map[ch] : ch);
            }
            result.Add(sb.ToString());
        }
        return string.Join("\n", result);
    }
}

STEP 1 OF 11
    Ctrl + Enter to check

    C# · PROJECTS: COMMAND-LINE TOOLS

    Tr V2 in C#, explained

    Problem overview

    This version of Tr takes a List<string> of lines and two strings of equal length, set1 and set2. Every character of a line that appears in set1 at index i becomes set2[i]. All other characters stay as they are. The lines are returned joined with "\n". Characters are literal (no ranges such as a-z), set1 has no repeated character, and lines may be empty.

    For ["banana", "cherry"] with set1 = "abc" and set2 = "ABC", a becomes A, b becomes B and c becomes C. The result is "BAnAnA\nCherry".

    Approach: build a lookup table, then translate character by character

    With many pairs of characters, calling Replace once per pair goes wrong, and the statement explains why: all replacements happen at once. With set1 = "ab" and set2 = "ba" the letters must swap. Chained replacements would turn "abab" into "bbbb" with the first call and then into "aaaa" with the second, undoing the first.

    The fix is to look at each character once and decide its replacement from the original character. A Dictionary<char, char> is the right lookup table: its keys are the characters in set1 and each value is the partner in set2. Then the method walks each line, and every character is either replaced through the map or copied as it is.

    Here is the table for the example. The loop over set1 = "abc" and set2 = "ABC" stores three pairs: 'a' maps to 'A', 'b' to 'B' and 'c' to 'C'. Now the word "cherry": c is a key, so C is appended. h, e, r, r and y are not keys, so each is appended unchanged. The builder ends up holding "Cherry".

    A map is not the only possible table. You could call set1.IndexOf(ch) for every character and use that position in set2. It works, but it scans set1 on every character. The dictionary answers in constant time on average, however long set1 is, and it states the idea directly: a character maps to a character.

    The swap case shows why one pass is safe. With "ab" and "ba" the map holds 'a' to 'b' and 'b' to 'a'. The method reads each character from the original line and appends its partner to a different object, the builder. A character that was just produced is never looked up again, so nothing is translated twice. The line "abab" becomes "baba".

    Step by step

    1. Create map, an empty Dictionary<char, char>.
    2. Loop over the positions of set1 with i from 0 while i < set1.Length. The sets have equal length, so i is a valid position in both.
    3. Store a pair: map[set1[i]] = set2[i]. Characters at the same position are partners.
    4. Create result, an empty List<string>, for the translated lines.
    5. Write a foreach loop over lines with the variable line.
    6. Create a StringBuilder sb inside the loop, a fresh one per line. It builds a string piece by piece with Append, which is cheaper than gluing strings together with + again and again.
    7. Loop over the characters of line with j while j < line.Length.
    8. Read the character at position j into char ch.
    9. Append the replacement or the character itself. map.ContainsKey(ch) ? map[ch] : ch picks map[ch] when ch is a key and ch otherwise.
    10. After the inner loop, add sb.ToString() to result. This runs once per line, outside the inner loop.
    11. After the outer loop, return string.Join("\n", result).

    The solution in C#

    class Solution {
        public string Tr(List<string> lines, string set1, string set2) {
            Dictionary<char, char> map = new Dictionary<char, char>();
            for (int i = 0; i < set1.Length; i++) {
                map[set1[i]] = set2[i];
            }
            List<string> result = new List<string>();
            foreach (string line in lines) {
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < line.Length; j++) {
                    char ch = line[j];
                    sb.Append(map.ContainsKey(ch) ? map[ch] : ch);
                }
                result.Add(sb.ToString());
            }
            return string.Join("\n", result);
        }
    }
    

    The C# details:

    • The indexer both adds and overwrites. map[key] = value inserts the pair when the key is new and replaces the value when it exists. map.Add(key, value) throws an ArgumentException for a duplicate key, but the lesson guarantees there are none.
    • Reading a missing key throws. map['z'] on a map without 'z' raises a KeyNotFoundException, so ContainsKey comes first. TryGetValue is an alternative that does the check and the read in one call.
    • Both sides of the ?: are char. The conditional operator needs compatible types, and Append(char) then adds a single character.
    • line[j] is a char. Strings can be indexed for reading, but not assigned to, since they are immutable. That is why the translated text goes into a StringBuilder.
    • StringBuilder lives in System.Text.

    Complexity

    Let k be the length of set1 and L the total characters in all lines. Time: O(k + L), since building the map takes k steps and each character does two dictionary lookups, which take constant time on average. Space: O(k + L) for the map, the builders and the result.

    Edge cases and common mistakes

    • Swapping. ["abba", "cab"] with "ab" and "ba" gives "baab\ncba". This is what the one-pass approach is for.
    • Chained Replace calls. They break swaps, as shown above, because a replaced character can be replaced again.
    • Empty lines and empty sets. ["hello", ""] with empty sets gives "hello\n": the map is empty and nothing changes.
    • Partial coverage. ["hello"] with "lo" and "01" gives "he001". Characters not in set1 pass through.
    • Case. 'a' and 'A' are different keys.
    • Reading map[ch] without checking. It throws for every character not in set1.

    Testing

    • ["banana", "cherry"], "abc", "ABC" gives "BAnAnA\nCherry".
    • ["abba", "cab"], "ab", "ba" gives "baab\ncba".
    • ["hello"], "lo", "01" gives "he001".
    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