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
- Declare
trwithlines []string,set1 stringandset2 string, returning astring. - Create the map
mfrombytetobytewithmake. Since all characters are ASCII, one byte is one character. - Loop over the positions of
set1withifrom 0 whilei < len(set1). Both sets have the same length, soiis valid in both. - Store the pair:
m[set1[i]] = set2[i]. Characters at the same position are partners. - Create
result, an empty slice of strings for the translated lines. - Loop over the lines by position
i. - Start
outas an empty string for the current line. A fresh one per line keeps lines from mixing. - Loop over the bytes of
lines[i]withj. - Read the current byte into
chto keep the next lines short. - Look it up with
if v, ok := m[ch]; ok. The replacement goes inv, andoksays whetherchwas a key. - If found, add
string(v)toout. - Otherwise (
else), addstring(ch), the original character. - After the inner loop, append
outtoresult. - 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]andlines[i][j]have typebyte(an alias ofuint8), not a one-character string. That is why the map ismap[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'yields0andokisfalse. Withoutokyou could not tell a missing key from a key whose value is 0. - Scope of
vandok. They are declared in theifstatement and visible in itsifandelsebranches only. string(v)turns a byte into a one-character string.outis 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
ReplaceAllonce 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 capitalHis not in the set, and everylandois mapped. - Dropping unmapped characters. Forgetting the
elsebranch deletes every character that is not inset1. - Empty sets. With
set1andset2both 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".
