Start learning free

LESSON 26 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Tr in Go: Translate a Set of Characters with a 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:

func tr(lines []string, set1 string, set2 string) string

Example:

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

Output: "BAnAnA\nCherry"

When printed:
BAnAnA
Cherry

Build a map[byte]byte from each byte of set1 to the matching byte of set2. Then walk each line byte-by-byte and translate via the map, leaving unmapped bytes unchanged.

m := make(map[byte]byte)
for i := 0; i < len(set1); i++ {
    m[set1[i]] = set2[i]
}
// per byte: if v, ok := m[ch]; ok { ... } else { ... }


The full solution:
func tr(lines []string, set1 string, set2 string) string {
    m := make(map[byte]byte)
    for i := 0; i < len(set1); i++ {
        m[set1[i]] = set2[i]
    }
    result := []string{}
    for i := 0; i < len(lines); i++ {
        out := ""
        for j := 0; j < len(lines[i]); j++ {
            ch := lines[i][j]
            if v, ok := m[ch]; ok {
                out += string(v)
            } else {
                out += string(ch)
            }
        }
        result = append(result, out)
    }
    return strings.Join(result, "\n")
}

STEP 1 OF 15
    Ctrl + Enter to check

    GO · PROJECTS: COMMAND-LINE TOOLS

    Tr V2 in Go, explained

    Problem overview

    This version of tr translates whole character sets. The function tr takes a slice of lines and two strings of equal length, set1 and set2. Every character in a line that appears at index i of set1 is replaced by set2[i]. Characters not in set1 stay as they are. The lines are joined by "\n".

    The notes set the boundaries: both sets are ASCII, set1 has no repeated character, characters are literal (no ranges like a-z), and lines may be empty. 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 once, apply it to every byte

    The pairing between the sets is a lookup table: character in, replacement out. A Go map[byte]byte is that table. It is built once from the two sets, and then every byte of every line is looked up in it. A byte found in the map becomes its replacement. A byte not found is copied unchanged.

    The lookup is also what makes the replacement simultaneous. Each byte of the original line is read once and either mapped or kept, and the output is a separate string, so a letter that was just produced is never looked at again. Applying ReplaceAll pair by pair would not behave this way: for "abba", replacing a with b and then b with a gives "aaaa", while the map gives "baab".

    On the example, the table is a to A, b to B and c to C. In "banana" the byte b is in the table and becomes B, each a becomes A, and each n is not in the table and is copied. That gives "BAnAnA". In "cherry" only the first letter is in the table, so the line becomes "Cherry".

    The previous version swapped one character. This one generalises it from one pair to many, which is why a table fits better than a single ReplaceAll call.

    Step by step

    1. Declare tr with lines []string, set1 string and set2 string, returning a string.
    2. Create the map m from byte to byte with make. Since all characters are ASCII, one byte is one character.
    3. Loop over the positions of set1 with i from 0 while i < len(set1). Both sets have the same length, so i is valid in both.
    4. Store the pair: m[set1[i]] = set2[i]. Characters at the same position are partners.
    5. Create result, an empty slice of strings for the translated lines.
    6. Loop over the lines by position i.
    7. Start out as an empty string for the current line. A fresh one per line keeps lines from mixing.
    8. Loop over the bytes of lines[i] with j.
    9. Read the current byte into ch to keep the next lines short.
    10. Look it up with if v, ok := m[ch]; ok. The replacement goes in v, and ok says whether ch was a key.
    11. If found, add string(v) to out.
    12. Otherwise (else), add string(ch), the original character.
    13. After the inner loop, append out to result.
    14. After the outer loop, return strings.Join(result, "\n").

    The solution in Go

    func tr(lines []string, set1 string, set2 string) string {
        m := make(map[byte]byte)
        for i := 0; i < len(set1); i++ {
            m[set1[i]] = set2[i]
        }
        result := []string{}
        for i := 0; i < len(lines); i++ {
            out := ""
            for j := 0; j < len(lines[i]); j++ {
                ch := lines[i][j]
                if v, ok := m[ch]; ok {
                    out += string(v)
                } else {
                    out += string(ch)
                }
            }
            result = append(result, out)
        }
        return strings.Join(result, "\n")
    }
    

    Go details to notice:

    • Indexing a string gives a byte. set1[i] and lines[i][j] have type byte (an alias of uint8), not a one-character string. That is why the map is map[byte]byte. For ASCII text a byte is a whole character.
    • The comma-ok lookup. Reading a missing key from a map does not fail: it gives the zero value. m['z'] on a map without 'z' yields 0 and ok is false. Without ok you could not tell a missing key from a key whose value is 0.
    • Scope of v and ok. They are declared in the if statement and visible in its if and else branches only.
    • string(v) turns a byte into a one-character string. out is a string, and a string grows only by adding text to it with +=.
    • Strings are immutable. Each out += ... builds a new string, copying the old content. That is fine at this size.

    Complexity

    Time: O(k + L), where k is the length of set1 and L the total length of the lines. Building the map takes k steps, and each byte costs one map lookup, which is constant time on average. The repeated += makes the cost of building a long line grow faster than its length, since every addition copies what is already there.

    Space: O(k + L) for the map, the output lines and the joined result.

    Edge cases and common mistakes

    • Swaps. ["abba", "cab"] with "ab" and "ba" gives "baab\ncba". Both letters are exchanged at once.
    • Chained replacement. Calling ReplaceAll once per pair makes later pairs act on earlier results, which breaks swaps.
    • Empty lines. ["", "xyz"] with "abc" and "ABC" gives "\nxyz".
    • Case. ["Hello"] with "lo" and "01" gives "He001". The capital H is not in the set, and every l and o is mapped.
    • Dropping unmapped characters. Forgetting the else branch deletes every character that is not in set1.
    • Empty sets. With set1 and set2 both empty, the map has no entries and ["banana"] comes back unchanged.

    Testing

    • ["banana", "cherry"], "abc", "ABC" gives "BAnAnA\nCherry".
    • ["abba", "cab"], "ab", "ba" gives "baab\ncba".
    • ["", "xyz"], "abc", "ABC" gives "\nxyz".
    • ["Hello"], "lo", "01" gives "He001".
    • ["banana"], "", "" gives "banana".
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free