Start learning free

LESSON 28 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Tr -s in Go: Squeeze Repeats with strings.Builder

Practice Read the full explanation

Build a version of the Unix tr -s command. Given a list of lines and a string chars, collapse consecutive runs of any character that appears in chars to a single occurrence. Other characters are unchanged. Return the lines joined by newline characters (\n).

Notes: chars is a non-empty ASCII string whose characters are taken literally (no ranges). Only runs of the same character from chars are collapsed; all other characters, and runs of characters not in chars, stay as they are. Upper and lower case are different characters. Lines may be empty.

Function signature:

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

Example:

Input: lines = ["aaabbb", "abaa"], chars = "a"

Output: "abbb\naba"

When printed:
abbb
aba

Build a map[byte]bool acting as a set of the squeeze characters. Walk each line tracking prev (the last byte you kept); skip the current byte only if it's in the set AND equals prev.

The full solution:
func trSqueeze(lines []string, chars string) string {
    squeeze := make(map[byte]bool)
    for i := 0; i < len(chars); i++ {
        squeeze[chars[i]] = true
    }
    result := []string{}
    for i := 0; i < len(lines); i++ {
        var sb strings.Builder
        var prev byte = 0
        for j := 0; j < len(lines[i]); j++ {
            ch := lines[i][j]
            if squeeze[ch] && ch == prev {
                continue
            }
            sb.WriteByte(ch)
            prev = ch
        }
        result = append(result, sb.String())
    }
    return strings.Join(result, "\n")
}

STEP 1 OF 15
    Ctrl + Enter to check

    GO · PROJECTS: COMMAND-LINE TOOLS

    Tr V4 in Go, explained

    Problem overview

    This version of tr mimics tr -s. The function trSqueeze takes a slice of lines and a string chars. In every line, a run of the same character that appears in chars collapses to a single occurrence. All other characters stay unchanged, and the lines are joined by "\n".

    chars is a non-empty ASCII string taken literally, with no ranges. Upper and lower case differ. Only runs of one repeated character from chars are collapsed: a run of characters outside chars stays as it is, and so does a mixed run such as "ab" repeated. Lines may be empty. For ["aaabbb", "abaa"] with "a" the result is "abbb\naba": the as are squeezed and the bs are not, because b is not in chars.

    Approach: skip a byte that repeats the one just kept

    A repeat means "this byte equals the byte right before it, and that byte is one we squeeze". So the loop only has to remember the previous byte. Walk through a line byte by byte, and for each one:

    • If it is in the squeeze set and equals the previous byte, skip it.
    • Otherwise, keep it, and remember it as the new previous byte.

    The first byte of a run is always kept, because nothing before it matches. Every later byte of the run equals its predecessor and is skipped. The set of squeezable characters is a map used as a set, as in the previous version. Each line is built in a strings.Builder, and the finished lines are joined at the end.

    Step by step

    1. Create the set squeeze as make(map[byte]bool). All characters are ASCII, so a byte is one character.
    2. Loop over the positions of chars with i.
    3. Mark each byte chars[i] as a member with squeeze[chars[i]] = true.
    4. Create result, an empty slice of strings.
    5. Loop over the lines by position i.
    6. Declare a strings.Builder named sb with var. It assembles a string piece by piece without the repeated copying that gluing with + causes. A new one per line keeps lines apart.
    7. Declare prev as a byte set to 0. At the start of a line nothing came before, so prev starts as a value no line character is expected to equal.
    8. Loop over the bytes of lines[i] with j.
    9. Read the current byte into ch.
    10. Test for a repeat: squeeze[ch] && ch == prev. Both parts must hold: the byte is squeezable and it repeats the previous one.
    11. If so, continue. That jumps to the next byte, so this one is never written.
    12. Otherwise write it: sb.WriteByte(ch).
    13. Set prev to ch, so the next byte is compared with the last one kept.
    14. After the inner loop, append sb.String() to result. This sits outside the inner loop, so it runs once per line. A line can end up empty and still goes into the output.
    15. After the outer loop, return strings.Join(result, "\n").

    The solution in Go

    func trSqueeze(lines []string, chars string) string {
        squeeze := make(map[byte]bool)
        for i := 0; i < len(chars); i++ {
            squeeze[chars[i]] = true
        }
        result := []string{}
        for i := 0; i < len(lines); i++ {
            var sb strings.Builder
            var prev byte = 0
            for j := 0; j < len(lines[i]); j++ {
                ch := lines[i][j]
                if squeeze[ch] && ch == prev {
                    continue
                }
                sb.WriteByte(ch)
                prev = ch
            }
            result = append(result, sb.String())
        }
        return strings.Join(result, "\n")
    }
    

    Go details to notice:

    • strings.Builder needs no setup. var sb strings.Builder gives an empty builder whose zero value is ready to use. WriteByte appends one byte, and String() returns what was written. Building with a builder avoids copying the whole string on every addition.
    • Indexing a string gives a byte. lines[i][j] and chars[i] are byte values, which is why squeeze is a map[byte]bool and prev is a byte.
    • A missing key reads as false. squeeze[ch] is false for any byte that was never added, so no comma-ok form is needed.
    • && short-circuits. If squeeze[ch] is false, the comparison with prev is not evaluated. Either way the result is the same here.
    • continue skips the rest of the loop body, including prev = ch. That is harmless because ch already equals prev at that point.
    • var prev byte = 0 states the type explicitly. It is the same as var prev byte, since the zero value of a byte is 0.

    Complexity

    Time: O(k + L), where k is the length of chars and L the total number of bytes in the lines. Each byte costs one map lookup and at most one write, and the joins are linear.

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

    Edge cases and common mistakes

    • Only squeezable characters collapse. ["aaabbb"] with "a" gives "abbb", and with "ab" gives "ab".
    • Squeeze the run, not the character. ["abab", "aAaA"] with "a" comes back unchanged: the as are never adjacent, and A is a different character.
    • Different squeezable characters don't merge. ["abba"] with "ab" gives "aba". The two bs collapse, but a and b next to each other stay.
    • Spaces. ["a b c", "x"] with " " gives "a b c\nx".
    • Several runs in a line. ["", "mississippi"] with "sp" gives "\nmisisipi": the ss pairs and the pp collapse, while the single letters are untouched. The empty first line stays.
    • Comparing with the wrong byte. If prev were updated only when a byte is in the set, a run broken up by another character would be treated as continuous.
    • Not resetting between lines. Declaring sb and prev inside the outer loop gives each line a fresh start, so a line's last character can't affect the next line's first.
    • Empty input. An empty slice gives "".

    Testing

    • ["aaabbb", "abaa"], "a" gives "abbb\naba".
    • ["aaabbb"], "ab" gives "ab".
    • ["aabb"], "b" gives "aab".
    • ["a b c", "x"], " " gives "a b c\nx".
    • ["abab", "aAaA"], "a" gives "abab\naAaA".
    • ["abba"], "ab" gives "aba".
    • ["", "mississippi"], "sp" gives "\nmisisipi".
    • 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