Start learning free

LESSON 26 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Tr in Kotlin: Translating a Set with a HashMap

Practice Read the full explanation

Build a more powerful version of the Unix tr command. Given a list of lines and two equal-length strings set1 and set2, replace every character in each line that appears in set1 at index i with set2[i]. Characters not in set1 are unchanged. Return the lines joined by newline characters (\n).

Notes: set1 and set2 have the same length, contain only ASCII characters, and set1 has no repeated character. Characters are taken literally: there are no ranges like a-z. All replacements happen at once, so set1 = "ab", set2 = "ba" swaps the two letters. Lines may be empty.

Function signature:

fun tr(lines: List<String>, set1: String, set2: String): String

Example:

Input: lines = ["banana", "cherry"], set1 = "abc", set2 = "ABC"

Output: "BAnAnA\nCherry"

When printed:
BAnAnA
Cherry

Build a HashMap<Char, Char> from each char in set1 to the matching char in set2. Then walk each line and use map.getOrDefault(ch, ch) to translate.

val map = HashMap<Char, Char>()
for (i in set1.indices) {
    map[set1[i]] = set2[i]
}
// per char: map.getOrDefault(ch, ch)


The full solution:
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")
    }
}

STEP 1 OF 10
    Ctrl + Enter to check

    KOTLIN · PROJECTS: COMMAND-LINE TOOLS

    Tr V2 in Kotlin, explained

    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

    1. Create the map. val map = HashMap<Char, Char>() will say which character becomes which.
    2. Fill it. Loop for (i in set1.indices). Both sets have the same length, so each position is valid in both. Store map[set1[i]] = set2[i], the partners at the same position.
    3. Prepare the output list. result is an ArrayList<String>, empty at first.
    4. Loop over the lines with for (line in lines).
    5. Create a builder per line. val sb = StringBuilder() collects the characters of the translated line. A fresh one per line keeps the lines apart.
    6. Loop over the characters with for (ch in line).
    7. Append the replacement or the original. map.getOrDefault(ch, ch) gives the mapped character, or ch itself when the map has no entry for it.
    8. Store the line. After the inner loop, sb.toString() turns the builder back into a String and result.add stores it.
    9. 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

    • Char against String. set1[i] is a Char, a single character, not a one-letter string. The map is therefore HashMap<Char, Char>, and looping over a string with for (ch in line) hands out Char values too.
    • map[key] = value is Kotlin's index syntax for put. Reading map[key] on a missing key would give null, which is why the solution uses getOrDefault with a fallback instead.
    • set1.indices is the range 0 until set1.length.
    • HashMap and ArrayList are Java's classes, available in Kotlin under those names. mutableMapOf and mutableListOf would work the same way here.
    • Two ways to write the fallback. map.getOrDefault(ch, ch) says "the mapped character, or ch if there is none". Kotlin code also often writes map[ch] ?: ch, where the Elvis operator ?: supplies ch when the lookup gives null. Both give the same result here. The lesson uses getOrDefault because 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, using set2[index] when the index isn't -1. That also works, but it scans set1 for every character of the input. The map pays that cost once, up front, and then each lookup is a single step on average. Because set1 has no repeated character, every key in the map is unique, so no entry overwrites another.
    • StringBuilder appends in place. Building a line with result += ch would 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:

    CharacterIn the map?Builder afterwards
    byes, becomes BB
    ayes, becomes ABA
    nno, keptBAn
    ayesBAnA
    nno, keptBAnAn
    ayesBAnAnA

    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 replace calls. 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 of getOrDefault takes care of it: with "abc" and "ABC", "cherry" keeps its h, e, r, r and y.
    • Empty sets. With set1 and set2 both 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.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free