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
- Create the set
setasmake(map[rune]bool). Aruneis one character. - Fill it: loop with
rangeoverchars, taking each characterchand discarding the index with_. - Mark each character as a member with
set[ch] = true. A character repeated incharsis marked twice, which changes nothing. - Create
resultas an empty string. The whole output is built in it. - Loop over the lines by position
i. - Test
i > 0. A newline goes between two lines, so the first line needs none. - Inside that test, add
"\n"toresultwith+=. - Loop with
rangeover the characters oflines[i], again discarding the index. - Keep the character only if it's not in the set: test
!set[ch]. A missing key reads asfalse, and!flips it. - Inside that test, add
string(ch)toresult. - 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:
rangeover a string yields runes. Each step gives the byte index where a character starts and the character itself as arune(an alias ofint32). For"aé"the loop yields index 0 with rune 97 (a) and index 1 with rune 233 (é). Sochhas typerune, 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 isfalse.set['z']isfalsewhen'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]boolandmap[rune]struct{}are both common; theboolform lets you test membership with a plain index. - Loop variable scope. The inner
rangedeclares its ownch, 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", sinceBis a different character fromb. With"aaB", the duplicateais harmless andBis 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
"".
