Start learning free

LESSON 387 OF 409 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: uniq v4 — Loners Only in C++

Practice

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

    Uniq V4 in C++

    Keep going with C++About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free