Start learning free

LESSON 18 OF 69 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool uniq v2 in C++: Count Adjacent Runs (-c) with sprintf

Practice Read the full explanation

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

    C++ · PROJECTS: COMMAND-LINE TOOLS

    Uniq V2 in C++, explained

    Problem overview

    The function uniqCount takes a vector<string> of lines and collapses each run of adjacent identical lines into one output line. That line shows the run's length and then the value, formatted like "%7d %s": the count right-aligned in 7 characters, one space, then the text. The output lines are joined with newlines. The previous version kept one line per run; this one also counts them.

    For ["a", "a", "b", "c", "c", "c"] the result is:

          2 a
          1 b
          3 c

    As one string it is " 2 a\n 1 b\n 3 c". A count of 2 is padded with 6 spaces to fill 7 characters, then comes a space and the value.

    Approach: track the current run and write it when it ends

    The function walks through the lines while remembering the run it is in, using two variables. prev is the text of the current run, and count is how many lines it has so far. A count of 0 means that no run has started yet.

    For each line there are two cases. If a run is going and the line equals prev, the run continues and count grows by 1. Otherwise the line starts a new run, which means the old run just ended. If there was an old run (count > 0), its output line is formatted and stored. Then prev becomes the new line and count becomes 1.

    A run is written only when a different line arrives, so the last run of the input is never written inside the loop: no line comes after it. After the loop, the same test, count > 0, writes it. This also handles the empty input, where count is still 0 and nothing is written.

    The finished lines are collected in a vector<string> and joined with newlines in a final loop, as in the first version.

    Step by step

    1. Create an empty vector<string> named result that will hold one output line per run.
    2. Create int count = 0. It counts the lines of the current run; 0 means no run yet.
    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. Both parts must hold to continue a run: one exists, and this line repeats it. An else branch follows.
    6. In the if branch, do count++. The run got one line longer.
    7. In the else branch, test count > 0. The branch means the old run ended, but before the first line there was no run, so the first line must not write anything.
    8. Declare char buf[32] inside that if, a character buffer for sprintf to fill.
    9. Call sprintf(buf, "%7d ", count). %7d writes the integer padded with spaces on the left up to width 7, and the space after it is part of the format.
    10. Store the run's line with result.push_back(string(buf) + prev). The buffer holds only the count part, so prev has to follow it.
    11. Still in the else, after the inner if, set prev = lines[i]. The line that ended the old run starts the new one.
    12. Set count = 1. The new run has one line so far.
    13. After the loop, repeat the write for the last run. An if (count > 0) with a new buf, the same sprintf and the same push_back.
    14. Join the lines. Create an empty string out, loop over result, add "\n" when i > 0, and add result[i].
    15. Return out.

    The solution in C++

    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;
        }
    };
    

    The C++ details worth a closer look:

    • sprintf writes into a character array. It comes from <cstdio> and uses C-style format strings. It does not check the size of the buffer, so the buffer must be large enough. An int has at most 11 characters with its sign, and with the padding and the space the text stays well below 32.
    • The width is a minimum. %7d pads short numbers but never cuts a long one: a count with more than 7 digits would print in full and push the text to the right.
    • string(buf) + prev. The character array is turned into a string first, because adding two C-style strings with + is not allowed. The text in buf ends with a space, so the value follows after a single space.
    • The count guard handles blank lines. prev starts as an empty string, and an empty string can also be a real line. The test uses count > 0 and not "prev is empty", so a run of empty lines is counted like any other.
    • The same code appears twice. The formatting inside the loop and the one after it are identical. Larger programs would move them into a helper function; here the repetition makes each step easy to see.

    Complexity

    Time: O(total length). Each line is compared with prev once, each run is formatted once, and the lines are joined in one pass.

    Space: O(total length). The result vector and the output string hold the text of one line per run, plus the counts. The by-value parameter also copies the input.

    Edge cases and common mistakes

    • Empty input. [] gives "": the loop doesn't run, and count is 0 after it, so nothing is written.
    • A single line. ["x"] gives " 1 x". Its run is only written by the check after the loop.
    • Forgetting the last run. Without the check after the loop, the last run is dropped from every result.
    • Runs of blank lines. ["", "", "a"] gives " 2 \n 1 a". The first output line is the count, a space and an empty value, so it ends with that space.
    • Separate runs of the same text. ["a", "b", "a"] gives " 1 a\n 1 b\n 1 a". The two "a"s are not adjacent, so they are two runs of 1.
    • Starting count at 1. Then the first line would write a run with prev equal to the empty string before any real run existed. Starting at 0 and guarding with count > 0 avoids that.
    • Resetting count to 0. In the else branch the new line is already the first line of the next run, so count becomes 1.
    • Wrong padding. The format is "%7d ": 7 characters for the number, then a space. Padding to 8 or leaving out the space gives lines that look similar but fail the tests.

    Testing

    • ["a", "a", "b", "c", "c", "c"] gives " 2 a\n 1 b\n 3 c".
    • ["x"] gives " 1 x".
    • ["", "", "a"] gives " 2 \n 1 a".
    • ["a", "b", "a"] gives " 1 a\n 1 b\n 1 a".
    • [] 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