Start learning free

LESSON 20 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Uniq V4 in C++: Keeping Only Lines That Don't Repeat

Practice Read the full explanation

Build a version of the Unix uniq -u command. Given a list of lines, output only the values whose adjacent run length is exactly one — i.e. lines that did NOT repeat back-to-back. Surviving values are joined by \n.

Function signature:

string uniqOnce(vector<string> lines)

Example:

Input: lines = ["a", "a", "b", "c", "c", "c"]

Output: "b"

When printed:
b

The two "a"s and the three "c"s are dropped because their runs are longer than 1. Only the lone "b" survives.


Track string prev and int count. When the line changes (or after the loop), flush prev only if count == 1.

if (count == 1) {
    result.push_back(prev);
}


The full solution:
class Solution {
public:
    string uniqOnce(vector<string> lines) {
        vector<string> result;
        int count = 0;
        string prev = "";
        for (int i = 0; i < lines.size(); i++) {
            if (count > 0 && lines[i] == prev) {
                count++;
            } else {
                if (count == 1) {
                    result.push_back(prev);
                }
                prev = lines[i];
                count = 1;
            }
        }
        if (count == 1) {
            result.push_back(prev);
        }
        string out;
        for (int i = 0; i < result.size(); i++) {
            if (i > 0) out += "\n";
            out += result[i];
        }
        return out;
    }
};

STEP 1 OF 17
    Ctrl + Enter to check

    C++ · PROJECTS: COMMAND-LINE TOOLS

    Uniq V4 in C++, explained

    Problem overview

    This version of the uniq tool works like uniq -u. The method uniqOnce(vector<string> lines) returns only the lines whose run of identical neighbours has length exactly one. A line that repeats right after itself is dropped completely, every copy of it. The survivors are joined by \n.

    Only adjacent repeats count. With {"a", "a", "b", "c", "c", "c"} the two a lines and the three c lines are dropped, and the lone b survives, so the result is "b". With {"a", "b", "a"} the two a lines are not neighbours, so each is a run of length one and the result is "a\nb\na".

    Approach

    Since only neighbours matter, one pass is enough. Think of the input as a series of runs: maximal stretches of equal lines. For each run you need to know its text and its length. If the length is 1, the run's text goes into the output; otherwise it is dropped.

    The loop therefore tracks the current run with two variables: prev, the text of the run, and count, how many lines it has so far. Each line either continues the run (same text, so count grows) or ends it and starts a new one. A run is only known to be finished when a different line arrives, and that is the moment to decide whether to keep it.

    That creates one case the loop cannot handle: the last run never meets a different line, so nothing ends it. The code repeats the check once after the loop for that run. This "flush the last group" step is a common pattern for any loop that processes groups of consecutive items.

    The survivors are collected in a vector first and joined afterwards, with a newline before every line except the first, as in the other tools of this project.

    Step by step

    1. Create an empty vector<string> named result for the lines that stand alone.
    2. Create int count = 0. Zero means no run has started yet.
    3. Create string prev = "", the text of the current run.
    4. Loop over the lines with int i from 0 while i < lines.size().
    5. Test for a continuing run: count > 0 && lines[i] == prev, with an else for the other case.
    6. In the if branch, increase count.
    7. In the else branch, check whether the finished run stood alone: if (count == 1). At the very first line count is 0, so nothing is added.
    8. Inside that check, push_back(prev) onto result.
    9. Still in the else, start the new run with prev = lines[i].
    10. Set count = 1, because the new run has one line so far.
    11. After the loop, repeat the test if (count == 1), since the last run is still open.
    12. Inside it, push_back(prev) again.
    13. Create an empty string named out. C++ has no ready-made join.
    14. Loop over result with int i.
    15. Add "\n" to out when i > 0.
    16. Append result[i] to out.
    17. Return out after the second loop.

    The solution in C++

    class Solution {
    public:
        string uniqOnce(vector<string> lines) {
            vector<string> result;
            int count = 0;
            string prev = "";
            for (int i = 0; i < lines.size(); i++) {
                if (count > 0 && lines[i] == prev) {
                    count++;
                } else {
                    if (count == 1) {
                        result.push_back(prev);
                    }
                    prev = lines[i];
                    count = 1;
                }
            }
            if (count == 1) {
                result.push_back(prev);
            }
            string out;
            for (int i = 0; i < result.size(); i++) {
                if (i > 0) out += "\n";
                out += result[i];
            }
            return out;
        }
    };
    

    Some details of the C++ code:

    • Comparing strings with ==. For std::string it compares contents, so equal text in different variables is equal.
    • Short-circuit &&. In count > 0 && lines[i] == prev the second part is only evaluated if the first is true. The test makes the meaning explicit: a run must exist before a line can continue it.
    • The names prev and out. prev holds the run's text, not the previous index. It changes only when a new run starts.
    • Unsigned sizes. lines.size() and result.size() are unsigned. Compared with the int index they work because the index is never negative.
    • The input is a copy. The vector is passed by value, so the function can read it freely without affecting the caller's vector. For a large input a const reference would avoid the copy.

    Complexity

    The first loop visits each line once and compares it with prev, which costs up to the length of the line. The second loop joins the survivors. The time is proportional to the total size of the input text. The extra space is the vector of survivors and the output string, each at most the size of the input.

    Edge cases and common mistakes

    • Forgetting the last run. Without the check after the loop, a lone last line is lost. With {"q"} the loop only starts the run, and the result is empty instead of "q".
    • Everything repeated. {"x", "x"} returns "".
    • Non-adjacent repeats. {"a", "b", "a"} keeps all three lines, because the lesson counts only neighbours.
    • Empty lines. An empty string is a line like any other. {"", "", "k"} returns "k", since the two empty lines form a run of two. {"", "z"} returns "\nz", because the lone empty line survives and the result starts with its separator.
    • Empty input. No lines, no runs, result "".
    • Keeping one copy of repeated lines. That is plain uniq. Here a repeated line disappears entirely.

    Testing

    linesresult
    {"a", "a", "b", "c", "c", "c"}"b"
    {"a", "b", "a"}"a\nb\na"
    {"x", "x"}""
    {"", "", "k"}"k"
    {"", "z"}"\nz"
    {"q"}"q"
    {}""
    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