Problem overview
The second version of the tr project translates many characters at once. tr(lines: List<String>, set1: String, set2: String): String gets 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 returned joined with \n.
set1 has no repeated character and the characters are taken literally, with no ranges such as a-z. For ["banana", "cherry"] with "abc" and "ABC" the result is "BAnAnA\nCherry".
All replacements happen at once. With set1 = "ab" and set2 = "ba" the line "abba" becomes "baab": the two letters swap, instead of one being changed twice.
Approach
The previous version swapped one character with a single replace call. Repeating replace for each pair would be wrong here. After replace("a", "b") turns "abba" into "bbbb", the next step replace("b", "a") gives "aaaa", and the swap is lost.
The fix is to look at each character once and decide its replacement from the original character. A HashMap from each set1 character to its partner in set2 answers that question fast. Then every character of every line is looked up in the map and appended to a builder.
Step by step
- Create the map.
val map = HashMap<Char, Char>()will say which character becomes which. - Fill it. Loop
for (i in set1.indices). Both sets have the same length, so each position is valid in both. Storemap[set1[i]] = set2[i], the partners at the same position. - Prepare the output list.
resultis anArrayList<String>, empty at first. - Loop over the lines with
for (line in lines). - Create a builder per line.
val sb = StringBuilder()collects the characters of the translated line. A fresh one per line keeps the lines apart. - Loop over the characters with
for (ch in line). - Append the replacement or the original.
map.getOrDefault(ch, ch)gives the mapped character, orchitself when the map has no entry for it. - Store the line. After the inner loop,
sb.toString()turns the builder back into aStringandresult.addstores it. - Join with
joinToString("\n")after the outer loop.
The solution in Kotlin
class Solution {
fun tr(lines: List<String>, set1: String, set2: String): String {
val map = HashMap<Char, Char>()
for (i in set1.indices) {
map[set1[i]] = set2[i]
}
val result = ArrayList<String>()
for (line in lines) {
val sb = StringBuilder()
for (ch in line) {
sb.append(map.getOrDefault(ch, ch))
}
result.add(sb.toString())
}
return result.joinToString("\n")
}
}
Kotlin details in this code
CharagainstString.set1[i]is aChar, a single character, not a one-letter string. The map is thereforeHashMap<Char, Char>, and looping over a string withfor (ch in line)hands outCharvalues too.map[key] = valueis Kotlin's index syntax forput. Readingmap[key]on a missing key would givenull, which is why the solution usesgetOrDefaultwith a fallback instead.set1.indicesis the range0 until set1.length.HashMapandArrayListare Java's classes, available in Kotlin under those names.mutableMapOfandmutableListOfwould work the same way here.- Two ways to write the fallback.
map.getOrDefault(ch, ch)says "the mapped character, orchif there is none". Kotlin code also often writesmap[ch] ?: ch, where the Elvis operator?:supplieschwhen the lookup givesnull. Both give the same result here. The lesson usesgetOrDefaultbecause it states the intent in one call. - Why a map and not a search. You could skip the map and call
set1.indexOf(ch)for every character, usingset2[index]when the index isn't -1. That also works, but it scansset1for every character of the input. The map pays that cost once, up front, and then each lookup is a single step on average. Becauseset1has no repeated character, every key in the map is unique, so no entry overwrites another. StringBuilderappends in place. Building a line withresult += chwould create a new string on every step.
Tracing the example
With set1 = "abc" and set2 = "ABC" the first loop fills the map with three entries: a=A, b=B and c=C. The line "banana" then grows in the builder one character at a time:
| Character | In the map? | Builder afterwards |
|---|---|---|
b | yes, becomes B | B |
a | yes, becomes A | BA |
n | no, kept | BAn |
a | yes | BAnA |
n | no, kept | BAnAn |
a | yes | BAnAnA |
A lookup of a missing key, such as map['z'], gives null in Kotlin. For n, map.getOrDefault('n', 'n') gives 'n', which is the original character. The second line, "cherry", goes through the same loop with a fresh builder and comes out as "Cherry", since only its c is in the map.
Complexity
Building the map takes O(m) for m characters in set1. Each character of the input is looked up once, in constant time on average, so translating costs O(total characters). The extra space is the map plus the output.
Edge cases and common mistakes
- Chained
replacecalls. Replacing pair by pair breaks swaps. In Kotlin,"abba".replace("a", "b").replace("b", "a")gives"aaaa", while the map-based solution turns"abba"into"baab"and"cab"into"cba". - Characters outside
set1. They must stay as they are. The fallback argument ofgetOrDefaulttakes care of it: with"abc"and"ABC","cherry"keeps itsh,e,r,randy. - Empty sets. With
set1andset2both empty, the map is empty and"hello"comes back unchanged. - Empty lines. The inner loop doesn't run,
sb.toString()is"", and the line stays in the output as an empty line. - Case.
'a'and'A'are different keys.
