Start learning free

LESSON 27 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Tr -d in Kotlin: Deleting Characters with a HashSet

Practice Read the full explanation

Build a version of the Unix tr -d command. Given a list of lines and a string chars, remove every character that appears in chars from each line, then return the lines joined by newline characters (\n).

Notes: chars is a non-empty ASCII string whose characters are taken literally (no ranges). Upper and lower case are different characters. A line can become empty after deleting, and then it stays as an empty line in the output.

Function signature:

fun trDelete(lines: List<String>, chars: String): String

Example:

Input: lines = ["banana", "apple"], chars = "aeiou"

Output: "bnn\nppl"

When printed:
bnn
ppl

Put each character of chars into a HashSet<Char> for O(1) lookup. Walk every line and append characters that are NOT in the set.

The full solution:
class Solution {
    fun trDelete(lines: List<String>, chars: String): String {
        val set = HashSet<Char>()
        for (i in 0 until chars.length) {
            set.add(chars[i])
        }
        val result = ArrayList<String>()
        for (line in lines) {
            val sb = StringBuilder()
            for (j in 0 until line.length) {
                val ch = line[j]
                if (!set.contains(ch)) {
                    sb.append(ch)
                }
            }
            result.add(sb.toString())
        }
        return result.joinToString("\n")
    }
}

STEP 1 OF 12
    Ctrl + Enter to check

    KOTLIN · PROJECTS: COMMAND-LINE TOOLS

    Tr V3 in Kotlin, explained

    Problem overview

    Version 3 of the tr project copies the -d flag, which deletes characters instead of translating them. trDelete(lines: List<String>, chars: String): String removes from every line each character that appears in chars, then returns the lines joined with \n.

    chars is a non-empty ASCII string whose characters are taken literally, and upper and lower case are different characters. A line can become empty after the deletions, and it then stays in the output as an empty line. For ["banana", "apple"] with "aeiou" the result is "bnn\nppl".

    Approach

    The question to answer for every character of every line is: "is this one of the characters to delete?" Searching chars each time would work, but a HashSet answers membership questions in a single step on average. So the function first turns chars into a set, then goes through each line, keeping only the characters that are not in the set.

    The second version of the project used a map for a similar job. Here no replacement is needed, so a set is enough: the only information per character is "delete" or "keep".

    Step by step

    1. Create the set. val set = HashSet<Char>() will hold the characters to delete.
    2. Fill it. Loop for (i in 0 until chars.length) over the positions of chars.
    3. Add each character. set.add(chars[i]). A set stores each character once, even if chars repeats it.
    4. Prepare the output. result is an empty ArrayList<String>.
    5. Loop over the lines with for (line in lines).
    6. Create a builder per line. val sb = StringBuilder() will hold the line without the deleted characters. Making a new one for each line keeps the lines from mixing.
    7. Loop over the positions of the line with for (j in 0 until line.length).
    8. Name the character. val ch = line[j] makes the next lines easier to read.
    9. Keep it unless it is in the set. if (!set.contains(ch)) is true for characters that stay. The ! flips the answer of contains.
    10. Append the kept character with sb.append(ch). Characters in the set are skipped, which is how they are deleted.
    11. Store the line. After the inner loop, result.add(sb.toString()). This sits outside the inner loop's braces, so it runs once per line, even when the line ended up empty.
    12. Join after the outer loop with joinToString("\n").

    The solution in Kotlin

    class Solution {
        fun trDelete(lines: List<String>, chars: String): String {
            val set = HashSet<Char>()
            for (i in 0 until chars.length) {
                set.add(chars[i])
            }
            val result = ArrayList<String>()
            for (line in lines) {
                val sb = StringBuilder()
                for (j in 0 until line.length) {
                    val ch = line[j]
                    if (!set.contains(ch)) {
                        sb.append(ch)
                    }
                }
                result.add(sb.toString())
            }
            return result.joinToString("\n")
        }
    }
    

    Kotlin details in this code

    • Characters are Char. chars[i] and line[j] give Char values, so the set is a HashSet<Char>. A Char in a string indexes at 0, and 0 until line.length stops at the last valid index.
    • !set.contains(ch) can also be written ch !in set, which reads more naturally in Kotlin. Both mean the same thing.
    • Strings can't be edited in place. A Kotlin String is immutable, so you can't remove a character from line. The code builds a new string in a StringBuilder from the characters to keep instead.
    • A shorter form exists. String has a filter method that keeps the characters for which a condition is true, so line.filter { it !in set } builds the same cleaned line in one expression. It gives bnn for "banana" with the same set. The lesson's explicit loop and builder show what filter does underneath.
    • The loop over positions could be a loop over characters, for (ch in line), as in the previous version. The lesson uses positions here to practise indexing, and the result is the same.

    Tracing the example

    For the line "apple" with chars = "aeiou" the set holds a, e, i, o and u. The characters a and e are in the set and are skipped, while p, p and l are not and are appended. The builder ends as ppl. The line "banana" keeps b, n and n, giving bnn, which is why the joined result is "bnn\nppl".

    The deleted characters can be anywhere in the line, at the start, in the middle or at the end, and consecutive ones disappear together. The loop needs no special handling for any of these positions.

    Complexity

    Building the set takes O(m) for a chars string of length m. Each input character is checked once, in constant time on average, so the scan costs O(total characters). The extra space is the set plus the output.

    Edge cases and common mistakes

    • A line that disappears. With ["aaa", "xyz", "Apple"] and "aeiouA" the result is an empty line, then xyz, then ppl. The first line must stay in the output as an empty line, which is why result.add is called for every line, even when the builder is empty.
    • Repeated characters in chars. "aaa" works like "a", because the set holds each character once. With ["aaa", "xyz"] the result is an empty line and xyz.
    • Case matters. With chars = "aeiou", the uppercase A in "Apple" is kept and the result is Appl. Only when "A" is also in chars does it go.
    • Putting result.add inside the inner loop. That would store a partly built line after every character instead of one finished line.
    • Forgetting the !. Without it the function keeps only the characters it should delete.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free