Problem overview
Version 2 of the tr project translates a whole set of characters at once. The method tr(lines: List[String], set1: String, set2: String): String receives a list of lines and two strings of equal length. Every character of a line that appears in set1 at index i becomes set2(i). Other characters stay as they are, and the lines are joined by \n.
The sets are ASCII, set1 has no repeated character, and characters are taken literally, with no ranges such as a-z. Lines may be empty. With ["banana", "cherry"], set1 = "abc" and set2 = "ABC", the answer is "BAnAnA\nCherry".
All replacements happen at once. With set1 = "ab" and set2 = "ba", the line "abba" becomes "baab": the two letters swap.
Approach: build a lookup table, then translate each character once
A tempting approach is to call replace once per pair. It breaks the swap case. Replacing a with b in "abba" gives "bbbb", and the following replacement of b with a then gives "aaaa", which is not the swap that was asked for. Every pair would see the output of the pairs before it.
The reliable approach is to decide each character's fate from the original line. First build a map from each character of set1 to its partner in set2. Then walk through every line, look up each character in the map, and write either its replacement or the character itself into a new string. Each character is looked at exactly once, so nothing is replaced twice.
Step by step
- Create
map, a mutableHashMap[Char, Char], in aval. Keys are characters to look for, values are their replacements. - Loop over every position
iin0 until set1.length. Both sets have the same length, so each position is valid in both. - In the loop, store the pair with
map(set1(i)) = set2(i): the character at positioniofset1maps to the character at positioniofset2. - Below the loop, create
result, an emptyArrayBuffer[String], for the translated lines. - Loop over each
lineinlines. - For each line, create a fresh
StringBuildernamedsb, so that lines don't mix. It builds a string piece by piece, which is cheaper than gluing strings with+again and again. - Write an inner loop over each character
chofline. - In the inner loop, append
map.getOrElse(ch, ch)tosb: the replacement if the map has one, otherwisechitself. - After the inner loop, add
sb.toString()toresult. This runs once per line, outside the inner loop. - After the outer loop, return
result.mkString("\n").
The solution in Scala
class Solution {
def tr(lines: List[String], set1: String, set2: String): String = {
val map = scala.collection.mutable.HashMap[Char, Char]()
for (i <- 0 until set1.length) {
map(set1(i)) = set2(i)
}
val result = scala.collection.mutable.ArrayBuffer[String]()
for (line <- lines) {
val sb = new StringBuilder()
for (ch <- line) {
sb.append(map.getOrElse(ch, ch))
}
result += sb.toString()
}
return result.mkString("\n")
}
}
Scala details that matter here:
map(set1(i)) = set2(i)is an update. Writingmap(key) = valuecalls the map'supdatemethod, and it replaces any earlier value for the same key.- A string is indexed with parentheses, and
set1(i)is aChar, which is why the map is typedHashMap[Char, Char]. getOrElse(key, default)never fails on a missing key. By contrast,map(key)on a missing key throwsNoSuchElementExceptionwith the messagekey not found: b. UsinggetOrElseis what lets unchanged characters pass straight through.for (ch <- line)hands out the characters of the string one at a time.- The map is a
scala.collection.mutable.HashMap, spelled out in full. The defaultMapin Scala is immutable, and you could not fill it with an update like this.
Tracing the swap
With set1 = "ab" and set2 = "ba", the map holds a -> b and b -> a. For the line "abba", here is sb after each character:
| ch | sb after appending |
|---|---|
a | b |
b | ba |
b | baa |
a | baab |
Each character is looked up in the map exactly once, using the original line. The b that was written into sb for the first a is never looked up again, so it is never turned back into an a. That is the difference from chained replace calls.
Notice where the map is built. It is filled once, before any line is read, and then shared by every line. Building it inside the line loop would give the same output but repeat the same work for each line. Notice too that the lookup table makes the cost of a line independent of how many pairs there are: a line of 1,000 characters needs 1,000 lookups whether set1 has 3 characters or 90.
Scala also offers shorter ways to write the same idea. For example, "ab".zip("ba").toMap builds the map Map(a -> b, b -> a) in one expression, and "abba".map(c => m.getOrElse(c, c)) then gives baab. The lesson's loops show each step explicitly, which makes the logic easier to follow.
Complexity
Building the map takes O(k) for k characters in set1. Translating takes O(N) for N characters across all lines, since each lookup in a hash map takes constant time on average. The extra space is O(k) for the map plus O(N) for the output.
Edge cases and common mistakes
- Swaps.
["abba", "cab"]with"ab"and"ba"gives"baab\ncba". Chainedreplacecalls give the wrong answer here, as shown above. - Characters outside
set1.["a-b c"]with" -"and"_+"gives"a+b_c": the letters are left alone, and the space and hyphen are translated. - Empty lines.
["", "xyz"]with"a"and"b"gives"\nxyz". The empty line stays. - Several matches.
["hello world"]with"lo"and"01"gives"he001 w1r0d". - Empty list. The result is
"". - Using
map(ch)directly. It throws for any character not inset1. UsegetOrElse.
