Start learning free

LESSON 27 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Tr -d in Go: Delete Characters Using a Map as a Set

Practice Read the full explanation

Build a version of the Unix tr -d command. Given a list of lines and a string chars, remove every character that appears in chars from each line, then return the lines joined by newline characters (\n).

Notes: chars is a non-empty ASCII string whose characters are taken literally (no ranges). Upper and lower case are different characters. A line can become empty after deleting, and then it stays as an empty line in the output.

Function signature:

func trDelete(lines []string, chars string) string

Example:

Input: lines = ["banana", "apple"], chars = "aeiou"

Output: "bnn\nppl"

When printed:
bnn
ppl

Put each character of chars into a map[rune]bool for O(1) lookup. Walk every line and append characters that are NOT in the map.

The full solution:
func trDelete(lines []string, chars string) string {
    set := make(map[rune]bool)
    for _, ch := range chars {
        set[ch] = true
    }
    result := ""
    for i := 0; i < len(lines); i++ {
        if i > 0 {
            result += "\n"
        }
        for _, ch := range lines[i] {
            if !set[ch] {
                result += string(ch)
            }
        }
    }
    return result
}

STEP 1 OF 11
    Ctrl + Enter to check

    GO · PROJECTS: COMMAND-LINE TOOLS

    Tr V3 in Go, explained

    Problem overview

    This version of tr mimics tr -d. The function trDelete takes a slice of lines and a string chars, removes every character that appears in chars from each line, and returns the lines joined by "\n".

    chars is a non-empty ASCII string taken literally, with no ranges. Upper and lower case are different characters. A line can become empty after deleting, and it then stays in the output as an empty line. For ["banana", "apple"] and "aeiou" the result is "bnn\nppl".

    Approach: a set of characters to drop

    For each character in a line, the question is "is it in chars?". Scanning chars every time works, but a set answers faster and reads better. Go has no built-in set type; the usual substitute is a map whose keys are the members. map[rune]bool does it: a key that is present means "delete this character".

    The rest is a pass over the lines. Walk the characters of each line and keep only the ones that are not in the set. The newlines between lines are added as the output grows, before every line except the first, so there is no newline after the last line.

    On the example, the set holds a, e, i, o and u. In "banana" the three as are dropped, leaving "bnn". In "apple" the a and the final e are dropped, leaving "ppl". The two results are joined with one newline between them. The previous version replaced characters; this one removes them, so the output can be shorter than the input.

    Step by step

    1. Create the set set as make(map[rune]bool). A rune is one character.
    2. Fill it: loop with range over chars, taking each character ch and discarding the index with _.
    3. Mark each character as a member with set[ch] = true. A character repeated in chars is marked twice, which changes nothing.
    4. Create result as an empty string. The whole output is built in it.
    5. Loop over the lines by position i.
    6. Test i > 0. A newline goes between two lines, so the first line needs none.
    7. Inside that test, add "\n" to result with +=.
    8. Loop with range over the characters of lines[i], again discarding the index.
    9. Keep the character only if it's not in the set: test !set[ch]. A missing key reads as false, and ! flips it.
    10. Inside that test, add string(ch) to result.
    11. After both loops, return result. The newlines are already in it.

    The solution in Go

    func trDelete(lines []string, chars string) string {
        set := make(map[rune]bool)
        for _, ch := range chars {
            set[ch] = true
        }
        result := ""
        for i := 0; i < len(lines); i++ {
            if i > 0 {
                result += "\n"
            }
            for _, ch := range lines[i] {
                if !set[ch] {
                    result += string(ch)
                }
            }
        }
        return result
    }
    

    Go details to notice:

    • range over a string yields runes. Each step gives the byte index where a character starts and the character itself as a rune (an alias of int32). For "aé" the loop yields index 0 with rune 97 (a) and index 1 with rune 233 (é). So ch has type rune, matching the map's key type, and the loop would handle non-ASCII text correctly as well.
    • A missing key reads as the zero value. For a map[rune]bool, that is false. set['z'] is false when 'z' was never added, and reading it does not add the key (the set still has one entry afterwards, in a test with only 'a'). That is why !set[ch] needs no comma-ok form here.
    • string(ch) converts a rune to a one-character string, which is what += needs on a string.
    • A map used as a set is idiomatic Go. map[rune]bool and map[rune]struct{} are both common; the bool form lets you test membership with a plain index.
    • Loop variable scope. The inner range declares its own ch, separate from the one in the first loop, which is out of scope by then.

    Complexity

    Time: O(k + L), where k is the length of chars and L the total number of characters in the lines. Each character costs one map lookup, constant on average. Because each += copies the string built so far, a very long output costs more than a linear amount of copying.

    Space: O(k + L) for the set and the output.

    Edge cases and common mistakes

    • Lines that become empty. ["aaa", "bab", "x"] with "a" gives "\nbb\nx". The first line is empty but still takes its place. Skipping empty results would break the line count.
    • Case. ["Banana"] with "a" gives "Bnn", since B is a different character from b. With "aaB", the duplicate a is harmless and B is removed too, giving "nn".
    • Newline placement. Adding a newline after every line leaves a trailing one. Adding it before every line except the first (i > 0) gives exactly the separators needed.
    • Two empty lines. ["a", "a"] with "a" gives "\n": two empty lines with one separator between them.
    • Empty input. An empty slice gives "".
    • Forgetting the !. Without it the function keeps only the deleted characters.

    Testing

    • ["banana", "apple"], "aeiou" gives "bnn\nppl".
    • ["aaa", "bab", "x"], "a" gives "\nbb\nx".
    • ["Banana"], "a" gives "Bnn".
    • ["Banana"], "aaB" gives "nn".
    • ["", "a"], "a" gives "\n".
    • ["a", "a"], "a" gives "\n".
    • An empty slice gives "".
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free