Start learning free

LESSON 27 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Tr V3 in C++: Deleting Characters with unordered_set

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:

string trDelete(vector<string> lines, string chars)

Example:

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

Output: "bnn\nppl"

When printed:
bnn
ppl

Put each character of chars into an unordered_set<char>. Walk every line and append characters that are NOT in the set.

The full solution:
class Solution {
public:
    string trDelete(vector<string> lines, string chars) {
        unordered_set<char> set;
        for (int i = 0; i < chars.size(); i++) {
            set.insert(chars[i]);
        }
        string result;
        for (int i = 0; i < lines.size(); i++) {
            if (i > 0) result += "\n";
            for (int j = 0; j < lines[i].size(); j++) {
                if (set.find(lines[i][j]) == set.end()) {
                    result += lines[i][j];
                }
            }
        }
        return result;
    }
};

STEP 1 OF 10
    Ctrl + Enter to check

    C++ · PROJECTS: COMMAND-LINE TOOLS

    Tr V3 in C++, explained

    Problem overview

    Version 3 of the tr tool adds deletion, like tr -d. The method trDelete(vector<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, taken literally with no ranges, and case matters. A line can become empty after the deletion, and it then stays in the output as an empty line. For {"banana", "apple"} with chars = "aeiou" the result is "bnn\nppl".

    Approach

    For each character of the input you need one yes-or-no answer: is it one of the characters to delete? Searching chars from the start each time would work, but a set answers the question directly. An unordered_set<char> stores each character once and tests membership in constant time on average.

    The rest is the copying loop from the earlier versions, with a change: instead of appending either a replacement or the original character, the loop appends the character only when it is not in the set. A deleted character is simply never copied.

    The newline logic stays the same. A newline is added before every line except the first, whatever the line contains. Empty lines are not removed, because the newline is added before checking any characters. A line that loses all its characters leaves only its separator behind.

    The difference from version 2 is that nothing is looked up for a replacement. A set is enough when you only need to know whether a character belongs to a group, and a map is needed when each member also carries a value. Choosing the right container is half of the solution here: the loops barely change from version 2, and the container's interface decides how the check is written.

    Step by step

    1. Create an unordered_set<char> named set for the characters to delete.
    2. Loop over the positions of chars with int i.
    3. Insert each character with set.insert(chars[i]). Repeated characters in chars are stored once.
    4. Create an empty result string.
    5. Loop over the lines with int i.
    6. Add a newline when i > 0, in a one-line if.
    7. Loop over the characters of lines[i] with int j.
    8. Test that the character is missing from the set: set.find(lines[i][j]) == set.end(). find returns end() when it finds nothing.
    9. Inside that if, append the character to result.
    10. Return result after the outer loop.

    The solution in C++

    class Solution {
    public:
        string trDelete(vector<string> lines, string chars) {
            unordered_set<char> set;
            for (int i = 0; i < chars.size(); i++) {
                set.insert(chars[i]);
            }
            string result;
            for (int i = 0; i < lines.size(); i++) {
                if (i > 0) result += "\n";
                for (int j = 0; j < lines[i].size(); j++) {
                    if (set.find(lines[i][j]) == set.end()) {
                        result += lines[i][j];
                    }
                }
            }
            return result;
        }
    };
    

    What to know about the C++ parts:

    • find returns an iterator. It points at the element when it is found and equals set.end() when it is not. Comparing with end() is the standard way to say "not found". set.count(c) == 0 is an equivalent test.
    • insert ignores duplicates. Inserting a character that is already there changes nothing, so chars = "aabb" behaves like "ab".
    • A set has no order. The order of unordered_set elements is unspecified. That doesn't matter here, because the code only asks whether a character is present.
    • The name set. A local variable called set hides the standard container std::set inside the function. It compiles and the solution is correct, but a name such as toDelete is clearer in a bigger program.

    The erase-remove alternative

    The standard library has an idiom for deleting elements from a string: remove_if moves the characters to keep to the front and returns the new end, and erase then cuts off the leftover tail.

    unordered_set<char> del(chars.begin(), chars.end());
    // for each line:
    string line = lines[i];
    line.erase(remove_if(line.begin(), line.end(), [&](char c) { return del.count(c) > 0; }), line.end());
    result += line;
    

    With the same newline handling, this returns "bnn\nppl" for the example. It also shows the set built straight from the characters of chars, with no loop. The lesson's version spells out the loops so each step stays visible, and it never needs a temporary copy of a line.

    Complexity

    Filling the set takes one insertion per character of chars. The main loops make one membership test per input character, each constant time on average. The total time is proportional to the length of chars plus the total input length. The set holds at most as many characters as chars has, and the result holds the characters that survive.

    Edge cases and common mistakes

    • Deleting everything on a line. {"aaa", "bab", "c"} with "a" gives "\nbb\nc". The first line becomes empty, so the result starts with a newline.
    • Case. {"Hello"} with "hl" gives "Heo": the capital H stays, and both lowercase l characters go.
    • Deleting commas. {"a,b", "", ",,"} with "," gives "ab\n\n": three lines, the last two empty. Deleting commas does not touch the line breaks, which are added by the loop.
    • Repeated characters in chars. {"abc"} with "aabb" gives "c".
    • Spaces. {"x y"} with " " gives "xy".
    • Skipping the newline for empty lines. Adding the newline only when a line has content loses the empty lines, and the tests expect them.
    • Empty input. An empty vector returns "".

    Testing

    linescharsresult
    {"banana", "apple"}"aeiou""bnn\nppl"
    {"aaa", "bab", "c"}"a""\nbb\nc"
    {"Hello"}"hl""Heo"
    {"a,b", "", ",,"}",""ab\n\n"
    {"abc"}"aabb""c"

    The next version builds on this one.

    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