Start learning free

LESSON 19 OF 69 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool uniq v3 in C++: Duplicates Only (-d) by Run Length

Practice Read the full explanation

Build a version of the Unix uniq -d command. Given a list of lines, output only the values whose adjacent run length is greater than one — i.e. lines that actually repeat back-to-back. Each surviving value is printed once (no count, just the value), joined by \n.

Function signature:

string uniqDups(vector<string> lines)

Example:

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

Output: "a\nc"

When printed:
a
c

The run of "a"s has length 2 and the run of "c"s has length 3, so both survive. The single "b" is dropped.


Track string prev and int count. When the line changes (or after the loop), flush prev only if count > 1. After collecting the survivors, join with "\n".

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


The full solution:
class Solution {
public:
    string uniqDups(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 V3 in C++, explained

    Problem overview

    The function uniqDups takes a vector<string> of lines and returns only the values whose adjacent run is longer than one, that is, the lines that repeat back to back. Each such value appears once in the output, with no count, and the lines are joined by newline characters.

    For ["a", "a", "b", "c", "c", "c"] the result is "a\nc". The run of "a"s has length 2 and the run of "c"s has length 3, so both survive. The single "b" has a run of length 1 and is dropped.

    Approach: measure each run, keep the long ones

    The function walks through the lines and tracks the run it is in with two variables: prev, the text of the run, and count, its length so far. A count of 0 means that no run has started.

    When a line equals prev and a run exists, the run grows: count goes up by 1. When a different line arrives, the run before it is over, and this is the moment to decide. If count is above 1, the run repeated, and one copy of prev goes into result. A run of 1 line is skipped, and so is the non-existent run before the first line, where count is 0. Then the new line becomes prev and count becomes 1.

    The last run is the special case. No line follows it to end it, so the loop never decides about it. After the loop, the same test, count > 1, handles it. The kept values are joined with newlines at the end.

    Step by step

    1. Create an empty vector<string> named result for one copy of each value that repeated.
    2. Create int count = 0. It counts the lines of the current run.
    3. Create string prev = "", the text of the current run.
    4. Loop over the lines with i from 0 while i < lines.size().
    5. Test count > 0 && lines[i] == prev. It means a run is going and this line continues it. An else follows.
    6. In the if branch, do count++.
    7. In the else branch, test count > 1. The old run ended, and only a run that repeated is kept.
    8. Add prev to result with push_back. One copy is enough, however long the run was.
    9. Still in the else, set prev = lines[i]. The line that ended the old run starts the next one.
    10. Set count = 1. The new run has one line so far.
    11. After the loop, test count > 1 again for the last run, which the loop never ended.
    12. Add prev to result inside that if, as in the loop.
    13. Create an empty string named out. The joining loop adds each kept value to its end.
    14. Loop over result with i from 0 while i < result.size().
    15. Add "\n" to out when i > 0. A newline goes between two values.
    16. Add result[i] to out.
    17. Return out after the second loop.

    The solution in C++

    class Solution {
    public:
        string uniqDups(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;
        }
    };
    

    The C++ details worth a closer look:

    • No formatting needed. The values are stored as they are, so push_back(prev) is all that is required, unlike a version that has to build a count and a value into one line.
    • count and prev together describe a run. The first line of the input meets count == 0, so the if condition is false at once and the else branch starts the first run. The test count > 1 is false there, so nothing is stored for a run that doesn't exist.
    • Comparing with ==. Two string values are equal when their contents are, so lines[i] == prev is the whole test for "the same line as before". An empty string is a valid line.
    • The condition appears twice. The check inside the loop and the check after it are the same on purpose: a run is decided when it ends, and the end of the input ends the last run.

    Complexity

    Time: O(total length). Each line is compared once with prev, and each kept value is copied once into result and once into out.

    Space: O(total length). The vector and the output string hold at most one copy of each repeated value, and the by-value parameter copies the input.

    Edge cases and common mistakes

    • Empty input. [] gives "": no run ever starts, so count stays 0 and nothing is stored.
    • No repeats. ["a", "b", "a"] gives "". The two "a"s are not adjacent, so each is a run of 1.
    • The same value in two runs. ["a", "a", "b", "a", "a"] gives "a\na". Each run is decided on its own, so a value that repeats in two places appears twice.
    • Forgetting the last run. Without the check after the loop, a repeated value at the end of the input is lost. In the main example, the "c" run would be missing from the result.
    • Using count > 0. That keeps every run, which gives the output of the first version, not the duplicates only. The test must be count > 1.
    • Adding the value for every repeat. Pushing prev each time count grows would print a value once per extra line. The value goes into result once, when its run ends.
    • A trailing newline. The separator goes before every value except the first, so the output has no newline at the end.

    Testing

    • ["a", "a", "b", "c", "c", "c"] gives "a\nc".
    • ["a", "a", "b", "a", "a"] gives "a\na".
    • ["a", "b", "a"] gives "".
    • [] 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