Start learning free

LESSON 385 OF 409 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: uniq v2 — Count Adjacent Runs in C++

Practice

Build a version of the Unix uniq -c command. Given a list of lines, collapse each run of adjacent duplicates into a single output line that shows the run's count followed by the value.

Each output line is formatted as "%7d %s": a 7-character right-aligned count, a single space, then the line value. Join all output lines with \n.

Function signature:

string uniqCount(vector<string> lines)

Example:

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

Output (when printed):
      2 a
      1 b
      3 c

The first run is two "a"s, then a single "b", then three "c"s — three output lines.


Track string prev and int count. When a NEW value arrives (or you reach the end), flush the previous run. Use sprintf with format "%7d " to right-align the count, then concat the line.

char buf[32];
sprintf(buf, "%7d ", count);
result.push_back(string(buf) + prev);
Don't forget to flush after the loop ends.

The full solution:
class Solution {
public:
    string uniqCount(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 > 0) {
                    char buf[32];
                    sprintf(buf, "%7d ", count);
                    result.push_back(string(buf) + prev);
                }
                prev = lines[i];
                count = 1;
            }
        }
        if (count > 0) {
            char buf[32];
            sprintf(buf, "%7d ", count);
            result.push_back(string(buf) + prev);
        }
        string out;
        for (int i = 0; i < result.size(); i++) {
            if (i > 0) out += "\n";
            out += result[i];
        }
        return out;
    }
};

STEP 1 OF 21
    Ctrl + Enter to check

    Uniq V2 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