Start learning free

LESSON 18 OF 70 · PROJECTS: COMMAND-LINE TOOLS

uniq -c in TypeScript: Counting 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: string[]): string

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: string[]): string {
        let result: string[] = [];
        let count: number = 0;
        let prev: string | null = 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

    TYPESCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Uniq V2 in TypeScript, explained

    Problem overview

    This version builds uniq -c. uniqCount(lines: string[]): string collapses each run of adjacent equal lines into one output line that shows the run's length and then the value. Each output line is count.toString().padStart(7, " ") + " " + value: the count right-aligned in 7 characters, one space, and the value. The output lines are joined with \n.

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

          2 a
          1 b
          3 c

    There are three runs: two "a"s, one "b" and three "c"s.

    Approach: remember the current run

    The previous version could decide about a line as soon as it saw it. Here a line can only be written once the run has ended, because only then is the count known. So the loop keeps two variables describing the run in progress: prev, the value of the run, and count, how many lines it has so far. A line equal to prev extends the run. A different line closes it: write the finished run, then start a new one with this line.

    That leaves one run that nobody closes. The last run never meets a different line after it, so the loop ends with its data still in prev and count. After the loop, the same writing code runs once more for it.

    Step by step

    1. result: an empty string[] that will hold one output line per run.
    2. count: a number starting at 0. Zero means no run has started yet.
    3. prev: typed string | null and set to null, meaning "no line yet". It holds the value of the current run.
    4. Loop by position with i from 0 while i < lines.length.
    5. Same run or not. The if is true when count > 0 and lines[i] === prev. Both must hold: a run exists, and this line equals it. The else handles everything else.
    6. Extend the run. In the if branch, count++.
    7. Was a run going? In the else branch, a different line has arrived, so the previous run is over, if there was one. Before the very first line count is 0, so nothing is written.
    8. Write the finished run. Push count.toString().padStart(7, " ") + " " + prev. toString() makes the number into text, and padStart(7, " ") adds spaces on its left until it is 7 characters long.
    9. Start the next run. Still in the else, set prev = lines[i].
    10. Count it as one. Set count = 1.
    11. After the loop, test again whether a run is open: count > 0.
    12. Write the last run inside that if, with the same expression as before.
    13. Join and return with result.join("\n").

    Tracing the example

    These are the values after each iteration for ["a", "a", "b", "c", "c", "c"], together with the number of output lines pushed so far:

    ilinecountprevpushed
    0a1a0
    1a2a0
    2b1b1
    3c1c2
    4c2c2
    5c3c2

    After the loop two lines have been pushed, and count is still 3. The final if pushes the third line for the run of "c"s.

    Notice that the else branch does two jobs in a fixed order: first it writes the old run, using prev and count, and only then does it overwrite them with the new line. Swapping the two would write the new line with the old count. The same order is what lets the first line work: with count at 0 the writing is skipped, and the run simply starts.

    The solution in TypeScript

    class Solution {
        uniqCount(lines: string[]): string {
            let result: string[] = [];
            let count: number = 0;
            let prev: string | null = 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:

    • string | null is a union type: prev is either text or null. When it is concatenated into a string, a null would turn into the text "null": "1 " + null gives "1 null". The code never reaches that case, because count is above 0 only after prev has been set to a line.
    • padStart(7, " ") never cuts a longer string: "12345678".padStart(7, " ") stays at 8 characters. A count of 12 gives " 12", which is 5 spaces and 2 digits.
    • padStart belongs to strings, so a number has to be converted first. Calling it on a number is reported by the compiler ("Property 'padStart' does not exist on type 'number'") and fails at run time with "n.padStart is not a function".
    • count++ adds one to the variable in place.

    Complexity

    One pass over the lines does constant work per line apart from comparing strings, so the time is O(n) in the total size of the input. The result holds one string per run, so the extra space is O(n) in the worst case, when every line differs from its neighbour.

    Edge cases and common mistakes

    • Forgetting the last run. Without the block after the loop, the last group is never written. For the example the output would stop after the b line.
    • Writing at the start. The count > 0 test in the else prevents a bogus line, with a count of 0 and a null value, from being pushed for the first line.
    • Empty input. [] gives "", because both count > 0 tests fail.
    • Single line. ["x"] gives " 1 x": six spaces, then the digit.
    • Non-adjacent repeats. ["a", "b", "a"] gives three separate lines, each with a count of 1, because the runs are not neighbours.
    • Case. ["a", "A"] are two runs of one.

    Testing

    linesResult
    []""
    ["x"]" 1 x"
    ["a", "b", "a"]" 1 a\n 1 b\n 1 a"
    twelve copies of "z"" 12 z"

    The next version builds on this one.

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