Start learning free

LESSON 27 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Tr V3 in C#: 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<char> 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) {
        HashSet<char> set = new HashSet<char>();
        for (int i = 0; i < chars.Length; i++) {
            set.Add(chars[i]);
        }
        List<string> result = new List<string>();
        foreach (string line in lines) {
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < line.Length; j++) {
                char ch = line[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

    C# · PROJECTS: COMMAND-LINE TOOLS

    Tr V3 in C#, explained

    Problem overview

    This version of TrDelete imitates tr -d. It takes a List<string> of lines and a non-empty string chars, removes every character that appears in chars from each line, and returns the lines joined with "\n". Characters are literal, and case matters. A line that becomes empty stays in the output as an empty line.

    For ["banana", "apple"] with chars = "aeiou", the vowels disappear and the result is "bnn\nppl".

    Approach: a set of banned characters, a filter per line

    For each character of a line the method asks one question: is it one of the characters to delete? A HashSet<char> answers that quickly. The method fills the set once from chars, then copies a line character by character into a StringBuilder, skipping the characters that are in the set. The builder's text is the cleaned line.

    Each line gets its own builder, so cleaned lines never mix, and the empty-line rule needs no code: a builder that received nothing produces "", which goes into the result like any other line.

    Trace the word "banana" with the set {a, e, i, o, u}. b is not in the set, so it is appended. a is in the set and is skipped. n is appended, a skipped, n appended, a skipped. The builder holds "bnn".

    Two other designs are possible. You could call line.Replace once for each character in chars, replacing it with an empty string. That works for deletion, because removing one character never creates a match for another, but it builds a new string per character. Or you could test membership with chars.Contains(ch) and skip the set. That is simpler, but it scans chars for every character of every line. The set trades a short set-up loop for lookups that don't depend on the length of chars.

    Step by step

    1. Create set, an empty HashSet<char>.
    2. Loop over the positions of chars with i while i < chars.Length.
    3. Add chars[i] to the set. A set stores each character once, so a repeated character in chars does no harm.
    4. Create result, an empty List<string>.
    5. Write a foreach loop over lines with the variable line.
    6. Create a StringBuilder sb for the current line.
    7. Loop over the characters of line with j while j < line.Length.
    8. Read the character at position j into char ch.
    9. Test !set.Contains(ch). A character is kept only when it is not in the set, and ! flips the answer.
    10. Append ch to sb inside that if. Characters in the set are skipped, which is how they get deleted.
    11. After the inner loop, add sb.ToString() to result, once per line.
    12. After the outer loop, return string.Join("\n", result).

    The solution in C#

    class Solution {
        public string TrDelete(List<string> lines, string chars) {
            HashSet<char> set = new HashSet<char>();
            for (int i = 0; i < chars.Length; i++) {
                set.Add(chars[i]);
            }
            List<string> result = new List<string>();
            foreach (string line in lines) {
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < line.Length; j++) {
                    char ch = line[j];
                    if (!set.Contains(ch)) {
                        sb.Append(ch);
                    }
                }
                result.Add(sb.ToString());
            }
            return string.Join("\n", result);
        }
    }
    

    The C# details:

    • HashSet<T> membership is fast. Contains takes constant time on average, no matter how many characters are in the set. Add on a value that is already present just returns false and leaves the set unchanged, with no exception.
    • Strings can't be edited in place. You can read line[j], but you can't remove a character from line. Building a new string is the only way, and StringBuilder makes that cheap, because it appends to an internal buffer instead of creating a new string for every +.
    • char compares by code. 'a' and 'A' are different values, so the set deletes only the case you listed.
    • set is an ordinary variable name here. It is only special inside a property definition.

    One more point: the lines are processed independently, and the output has exactly as many lines as the input. Deleting characters can shorten a line, but it never removes a line, so the number of newline separators in the result is always one less than the number of lines (or the result is "" for an empty list).

    Complexity

    Let k be the length of chars and L the total number of characters in all lines. Time: O(k + L), since the set is built in k steps and each character gets one constant-time lookup. Space: O(k + L) for the set, the builders and the output.

    Edge cases and common mistakes

    • A line that empties out. ["x", "aa", "y"] with chars = "a" gives "x\n\ny". The middle line is empty but still takes its place. Skipping empty results would shift the later lines up.
    • Everything deleted. ["aaa", "bob"] with "ab" gives "\no".
    • Case. ["Banana"] with "a" gives "Bnn": the capital B is untouched, and the lowercase as are gone. A capital A would stay.
    • Repeated characters in chars. "aa" behaves like "a", thanks to the set.
    • Putting the result.Add inside the inner loop. That would add the partly built line once per character.
    • Reusing one StringBuilder for all lines. The lines would pile up into one long string.

    Testing

    • ["banana", "apple"], "aeiou" gives "bnn\nppl".
    • ["x", "aa", "y"], "a" gives "x\n\ny".
    • ["Banana"], "a" gives "Bnn".
    • [], "a" gives "".
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free