Start learning free

LESSON 616 OF 671 · PROJECTS: COMMAND-LINE TOOLS

uniq -c in JavaScript: Counting Adjacent Runs with padStart

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 count.toString().padStart(7, ' ') + " " + value: a 7-character right-aligned count, a single space, then the line value. Join all output lines with \n.

Function signature:

uniqCount(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 prev and count as you walk the input. When you see a NEW value, flush the previous run as count.toString().padStart(7, ' ') + " " + prev and reset to count 1. When you finish the loop, flush again.

if (count > 0 && lines[i] === prev) {
    count++;
} else {
    if (count > 0) {
        result.push(count.toString().padStart(7, ' ') + " " + prev);
    }
    prev = lines[i];
    count = 1;
}


The full solution:
class Solution {
    uniqCount(lines) {
        let result = [];
        let count = 0;
        let prev = null;
        for (let i = 0; i < lines.length; i++) {
            if (count > 0 && lines[i] === prev) {
                count++;
            } else {
                if (count > 0) {
                    result.push(count.toString().padStart(7, ' ') + " " + prev);
                }
                prev = lines[i];
                count = 1;
            }
        }
        if (count > 0) {
            result.push(count.toString().padStart(7, ' ') + " " + prev);
        }
        return result.join("\n");
    }
}

STEP 1 OF 13
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Uniq V2 in JavaScript, explained

    Problem overview

    The method uniqCount(lines) is the -c flag of the Unix uniq command. It collapses every run of adjacent equal lines into one output line that shows how many times the line occurred. Each output line is the count padded on the left to 7 characters, then one space, then the value. The output lines are joined by "\n".

    For ["a", "a", "b", "c", "c", "c"] there are three runs, so the result, printed, is:

          2 a
          1 b
          3 c

    The same text as a JavaScript string is " 2 a\n 1 b\n 3 c". An empty array gives "".

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

    Now the function must remember something about the past: which line the current run is made of, and how long it is so far. Two variables hold that. prev is the run's line and count is its length; count being 0 means no run has started yet.

    For each incoming line there are two cases. If a run is going and the line equals prev, the run grows: add 1 to count. Otherwise the line is different, so the previous run is over: write its output line (if there was a run at all), then start a new run with this line, with count set to 1.

    A run is only written when a different line arrives. The very last run is never followed by a different line, so the loop leaves it unwritten. After the loop, one more check writes it. Forgetting this final flush is the classic bug of run-length code, and it silently drops the last group.

    Step by step

    1. Create result as an empty array that will hold one output line per run.
    2. Create count at 0. Zero means "no run yet".
    3. Create prev as null, meaning no value yet. It remembers the line the current run consists of.
    4. Loop over the positions with for (let i = 0; i < lines.length; i++).
    5. Branch: if (count > 0 && lines[i] === prev) continues a run, and its else handles everything else. Both conditions are needed: a run exists, and this line matches it.
    6. In the if, do count++.
    7. In the else, first check count > 0, because before the first line no run exists and nothing should be written.
    8. Inside that check, push the finished run: count.toString().padStart(7, ' ') + " " + prev.
    9. Still in the else, after the inner if, set prev = lines[i]: the line that ended the old run starts the new one.
    10. Set count = 1, since the new run has one line so far.
    11. After the loop, test count > 0 again, because the last run is still open.
    12. Push the last run with the same expression.
    13. Return result.join("\n").

    Tracing the example

    For ["a", "a", "b", "c", "c", "c"], the state after each pass of the loop is:

    ilineprev aftercount afteroutput lines written so far
    0"a""a"10
    1"a""a"20
    2"b""b"11
    3"c""c"12
    4"c""c"22
    5"c""c"32

    Only two lines are written inside the loop, one when "b" arrives and one when the first "c" does. The run of "c" is still open when the loop ends, with count at 3, and the check after the loop writes it as the third line. That is why the final check is not optional.

    The solution in JavaScript

    class Solution {
        uniqCount(lines) {
            let result = [];
            let count = 0;
            let prev = null;
            for (let i = 0; i < lines.length; i++) {
                if (count > 0 && lines[i] === prev) {
                    count++;
                } else {
                    if (count > 0) {
                        result.push(count.toString().padStart(7, ' ') + " " + prev);
                    }
                    prev = lines[i];
                    count = 1;
                }
            }
            if (count > 0) {
                result.push(count.toString().padStart(7, ' ') + " " + prev);
            }
            return result.join("\n");
        }
    }
    

    Language details:

    • count.toString() turns the number into text, which is needed because padStart is a string method. padStart(7, ' ') adds spaces on the left until the string is 7 characters long, so "2" becomes six spaces and a 2.
    • padStart never cuts. A count with more than 7 digits, such as "12345678".padStart(7, " "), comes back unchanged at 8 characters.
    • Because the numbers are padded and then joined to " " and prev with +, the line value starts at the same column in every output line.
    • The code uses === against prev. When prev is null the left side count > 0 is false first, so the comparison is skipped.

    A common alternative is to compare lines[i] with lines[i - 1] and count backwards, but that needs special handling at index 0 and at the end too. Keeping prev and count as explicit state makes both boundaries visible in the code, which is easier to check.

    Complexity

    One pass visits each line once, comparing it with prev, so the time is proportional to the total text size. The result holds one string per run, so the extra space is at most proportional to the number of lines.

    Edge cases and common mistakes

    • Missing final flush. Without the check after the loop, the last run vanishes: the example would end after b.
    • Writing a run for the first line. The count > 0 check in the else prevents a bogus output line with count 0.
    • Non-adjacent repeats stay separate. ["a", "b", "a"] gives three runs, each with count 1.
    • Empty-string lines. ["", ""] is one run of 2 and gives " 2 ", with a trailing space after the count.
    • Empty input. The loop does not run and count stays 0, so the result is "".

    Testing

    linesresult
    ["a", "a", "b", "c", "c", "c"]" 2 a\n 1 b\n 3 c"
    ["a", "b", "a"]" 1 a\n 1 b\n 1 a"
    ["", ""]" 2 "
    []""
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free