Start learning free

LESSON 386 OF 410 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: uniq v2 — Count Adjacent Runs in JavaScript

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

    Uniq V2 in JavaScript

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