Start learning free

LESSON 27 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Tr V3 in Scala: 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:

def trDelete(lines: Array[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 mutable.HashSet[Char] for O(1) lookup. Walk every line and append characters that are NOT in the set.

The full solution:
class Solution {
    def trDelete(lines: Array[String], chars: String): String = {
        val set = scala.collection.mutable.HashSet[Char]()
        for (i <- 0 until chars.length) {
            set.add(chars(i))
        }
        val result = scala.collection.mutable.ArrayBuffer[String]()
        for (line <- lines) {
            val sb = new StringBuilder()
            for (j <- 0 until line.length) {
                val ch = line(j)
                if (!set.contains(ch)) {
                    sb.append(ch)
                }
            }
            result += sb.toString()
        }
        return result.mkString("\n")
    }
}

STEP 1 OF 12
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Tr V3 in Scala, explained

    Problem overview

    Version 3 of the tr project behaves like tr -d. The method trDelete(lines: Array[String], chars: String): String removes from every line each character that appears in chars, then returns the lines joined by \n.

    chars is a non-empty ASCII string, taken literally with no ranges, and case matters. A line may become empty after the deletion, and then it stays in the output as an empty line. With ["banana", "apple"] and chars = "aeiou", the answer is "bnn\nppl".

    Approach

    For every character of every line, you have to answer one question: is it one of the characters to delete? A set answers it quickly. Put the characters of chars in a HashSet[Char], then copy into a new string only the characters that are not in the set.

    A set also removes duplicates for free: with chars = "aa", the set still holds a once. A plain loop that searched chars for every character would work too, but the set makes each check cost constant time on average.

    Step by step

    1. Create set, a mutable HashSet[Char], in a val.
    2. Loop over every position i in 0 until chars.length.
    3. In the loop, add chars(i) to the set with set.add.
    4. Create result, an empty ArrayBuffer[String], for the cleaned lines.
    5. Loop over each line in lines.
    6. Create a fresh StringBuilder named sb for this line.
    7. Loop over every position j in 0 until line.length.
    8. Put the character line(j) in a val ch.
    9. Write if (!set.contains(ch)). The ! flips the answer, because a character is kept only when it is not in the set.
    10. Inside the if, append ch to sb. Characters in the set are skipped, which is how they are deleted.
    11. After the inner loop, add sb.toString() to result. A line can be empty here, and it is still added.
    12. After the outer loop, return result.mkString("\n").

    The solution in Scala

    class Solution {
        def trDelete(lines: Array[String], chars: String): String = {
            val set = scala.collection.mutable.HashSet[Char]()
            for (i <- 0 until chars.length) {
                set.add(chars(i))
            }
            val result = scala.collection.mutable.ArrayBuffer[String]()
            for (line <- lines) {
                val sb = new StringBuilder()
                for (j <- 0 until line.length) {
                    val ch = line(j)
                    if (!set.contains(ch)) {
                        sb.append(ch)
                    }
                }
                result += sb.toString()
            }
            return result.mkString("\n")
        }
    }
    

    Details to notice:

    • set.add(x) on a mutable set adds the element and returns a Boolean: true if it was new, false if it was already there. Adding 'a' twice gives true then false, and the set's size stays 1.
    • set.contains(ch) is the membership test. Indexing a string with line(j) gives a Char, which matches the set's element type.
    • The deleted characters are never copied. The loop does not edit line; strings are immutable, so you build a new one in sb.
    • The StringBuilder is created inside the outer loop. If it were created before the loop, every line would be appended to the same builder, and the lines would run together.

    Tracing the example

    For the line "banana" with chars = "aeiou", the set holds the five vowels. Here is what the inner loop does for each character:

    chkeptsb afterwards
    byesb
    anob
    nyesbn
    anobn
    nyesbnn
    anobnn

    The line becomes "bnn". The second line, "apple", loses its two vowels in the same way and becomes "ppl", so the joined answer is "bnn\nppl".

    The same idea can be written with string methods. With val set = "aeiou".toSet, the call "banana".filter(c => !set.contains(c)) gives bnn, and "apple".filterNot(set) gives ppl, because a set can be used as a yes-or-no function on its elements. The loops in the solution do exactly what these calls do, one character at a time, so you can see where the decision happens: at the if, with a check against the set.

    The choice of a set matters for longer inputs. Scanning chars from start to end for every character would cost O(k) per check, while a hash set does the same check in constant time on average. For a short chars such as "aeiou" the difference is tiny, and the set mostly makes the intent clear.

    Joining deserves a last look. Because mkString("\n") puts the separator only between elements, the number of newline characters in the output is always one fewer than the number of lines, whatever the lines hold. Empty lines are elements like any other, which is why ["aaa", "bob", "aea"] with "ae" keeps its blank first and last lines.

    Complexity

    Filling the set takes O(k) for k characters in chars. Cleaning takes O(N) for N characters over all lines, because each membership check is O(1) on average. The set uses O(k) space, and the output uses O(N).

    Edge cases and common mistakes

    • A line that becomes empty. ["aaa", "bob", "aea"] with "ae" gives "\nbob\n". The first and last lines are empty but still present, so the output starts and ends with a newline.
    • Case. ["Banana"] with "b" gives "Banana": the capital B is a different character.
    • Spaces. ["a b c"] with " " gives "abc". A space is an ordinary character here.
    • Repeated characters in chars. ["hello"] with "ll" gives "heo"; both l characters are removed, and the repeated l in chars is harmless.
    • Dropping empty results. Skipping a line that is empty after cleaning would shift the output; the lesson wants it kept.
    • Empty array. The result is "".
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free