Start learning free

LESSON 625 OF 671 · PROJECTS: COMMAND-LINE TOOLS

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

public String trDelete(List<String> lines, String chars)

Example:

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

Output: "bnn\nppl"

When printed:
bnn
ppl

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

The full solution:
class Solution {
    public String trDelete(List<String> lines, String chars) {
        Set<Character> set = new HashSet<>();
        for (int i = 0; i < chars.length(); i++) {
            set.add(chars.charAt(i));
        }
        List<String> result = new ArrayList<>();
        for (String line : lines) {
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < line.length(); j++) {
                char ch = line.charAt(j);
                if (!set.contains(ch)) {
                    sb.append(ch);
                }
            }
            result.add(sb.toString());
        }
        return String.join("\n", result);
    }
}

STEP 1 OF 12
    Ctrl + Enter to check

    JAVA · PROJECTS: COMMAND-LINE TOOLS

    Tr V3 in Java, explained

    Problem overview

    The third version of the tr tool behaves like tr -d. The method trDelete(List<String> lines, String chars) removes from every line each character that appears in chars, then returns the lines joined by \n.

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

    For ["banana", "apple"] and chars = "aeiou", the answer is "bnn\nppl". Printed, that is bnn and ppl.

    Approach: keep a character only if it isn't in the set

    Instead of deleting from a string, which Java can't do because strings are immutable, build each cleaned line from the characters that survive. A character survives when it isn't one of the characters to delete.

    That test runs once for every character of every line, so it should be quick. A Set<Character> answers "is this character a member?" in constant time on average. Searching the string chars would also work, but it scans the string each time. Filling the set takes one pass over chars, and a set keeps each character once, however often it appears in chars.

    For each line, a StringBuilder collects the kept characters, and toString() turns it back into a String that goes into a result list. The list is joined at the end.

    Here is "banana" with chars = "aeiou", showing the builder after each character:

    j=0 ch=b sb=b
    j=1 ch=a sb=b
    j=2 ch=n sb=bn
    j=3 ch=a sb=bn
    j=4 ch=n sb=bnn
    j=5 ch=a sb=bnn
    

    The builder only grows on characters that aren't in the set. Each a is looked at and ignored, and the final bnn is what goes into the result.

    Deleting characters with a regular expression, such as replaceAll, is a trap for this task. A pattern gives special meaning to characters like ., [ and ], and the lesson wants every character taken literally. The set-based loop never interprets anything.

    The set is built once, before the loop over the lines, because it depends only on chars. Building it inside the line loop would repeat the same work for every line and give the same answer each time.

    Step by step

    1. Create set, a Set<Character> set to a new HashSet. It holds the characters to delete.
    2. Loop over the positions of chars with i from 0 to chars.length() - 1.
    3. Add each character with set.add(chars.charAt(i)).
    4. Create result, an empty list of strings for the cleaned lines.
    5. Loop over the lines with a for-each loop that names each element line.
    6. Create a fresh StringBuilder named sb for each line.
    7. Loop over the positions of line with j from 0 to line.length() - 1.
    8. Read the character at position j into a char named ch.
    9. Test for a keeper. !set.contains(ch) is true when the character isn't in the set. The ! flips the answer of contains.
    10. Append ch to sb inside that if. Characters in the set are simply never appended, which is how they get deleted.
    11. After the inner loop, add sb.toString() to result. This runs once per line, so it sits outside the inner loop's braces. A line that lost every character is added as an empty string.
    12. After the outer loop, return String.join("\n", result).

    The solution in Java

    class Solution {
        public String trDelete(List<String> lines, String chars) {
            Set<Character> set = new HashSet<>();
            for (int i = 0; i < chars.length(); i++) {
                set.add(chars.charAt(i));
            }
            List<String> result = new ArrayList<>();
            for (String line : lines) {
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < line.length(); j++) {
                    char ch = line.charAt(j);
                    if (!set.contains(ch)) {
                        sb.append(ch);
                    }
                }
                result.add(sb.toString());
            }
            return String.join("\n", result);
        }
    }
    

    Details worth knowing:

    • Autoboxing. The set holds Character objects, while charAt returns a primitive char. Java converts automatically in set.add(...) and set.contains(ch).
    • add ignores duplicates. For chars = "aab" the set has two elements. No check is needed in the loop.
    • A StringBuilder per line. Declaring it inside the for-each loop gives every line a fresh, empty builder. Declared outside, it would carry the previous lines along.
    • Imports. List, ArrayList, Set and HashSet are in java.util.

    Complexity

    Time: O(m + t), where m is the length of chars and t is the total number of characters in all lines. Building the set takes m additions, and each character of the text costs one membership test, which is constant on average.

    Space: O(m + t). The set holds at most m characters, and the builders and the result hold the cleaned text.

    Edge cases and common mistakes

    • Lines that become empty. ["aaa", "bob"] with "ab" gives "\no": the first line is empty and is still a line. Skipping empty results would shift every later line up.
    • Empty lines in the input. ["a", "", "b"] with "a" gives "\n\nb": two empty lines, then b.
    • Case. ["Hello, World!"] with "lo" gives "He, Wrd!". The capital W and the capital H are not in the set, and every lowercase l and o is gone.
    • Punctuation is just characters. Commas, spaces and exclamation marks are kept unless they are in chars.
    • Repeated characters in chars. ["aab"] with "aa" gives "b", the same as with "a".
    • Using contains without !. That keeps only the characters to delete and throws the rest away.

    Testing

    • ["banana", "apple"] with "aeiou" gives "bnn\nppl".
    • ["aaa", "bob"] with "ab" gives "\no".
    • ["Hello, World!"] with "lo" gives "He, Wrd!".
    • ["a", "", "b"] with "a" gives "\n\nb".
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free