Start learning free

LESSON 19 OF 70 · PROJECTS: COMMAND-LINE TOOLS

uniq -d in TypeScript: Lines That Repeat Back-to-Back

Practice Read the full explanation

Build a version of the Unix uniq -d command. Given a list of lines, output only the values whose adjacent run length is greater than one — i.e. lines that actually repeat back-to-back. Each surviving value is printed once (no count, just the value), joined by \n.

Function signature:

uniqDups(lines: string[]): string

Example:

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

Output: "a\nc"

When printed:
a
c

The run of "a"s has length 2 and the run of "c"s has length 3, so both survive. The single "b" is dropped.


Same scaffolding as uniq -c: track prev and count, flush when the value changes (or you reach the end). The only difference is the filter: only flush if count > 1, and push just the value (no count).

if (count > 1) {
    result.push(prev);
}
Remember to flush AFTER the loop too.

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

STEP 1 OF 13
    Ctrl + Enter to check

    TYPESCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Uniq V3 in TypeScript, explained

    Problem overview

    This version builds uniq -d. uniqDups(lines: string[]): string outputs only the values whose run of adjacent equal lines is longer than one, each printed once, with no count, joined by \n.

    For ["a", "a", "b", "c", "c", "c"] the result is "a\nc". The run of "a"s has length 2 and the run of "c"s has length 3, so both survive. The single "b" is dropped.

    Runs are what matter, not values. With ["a", "a", "b", "a", "a"] there are two separate runs of "a", each of length 2, so the result is "a\na".

    Approach: the run tracker of the last version, with a different test

    The previous version tracked the current run with prev and count and wrote an output line when a run ended. This version uses the same tracker. Only two things change. The line that is written is just the value, and it is written only when the finished run had more than one line, that is when count > 1. A run of length 1 is silently dropped.

    The handling of the final run is the same as before: it never meets a different line, so the loop leaves it open, and a block after the loop applies the same test to it.

    Step by step

    1. result: an empty string[] holding one copy of each value that repeated.
    2. count: starts at 0, meaning no run has started.
    3. prev: typed string | null, starting as null.
    4. Loop by position with i from 0 while i < lines.length.
    5. Same run or not. The if requires count > 0 and lines[i] === prev. Everything else goes to the else.
    6. Extend the run: count++ in the if branch.
    7. Was the finished run repeated? In the else, a different line has arrived. An inner if (count > 1) asks whether the run that just ended had more than one line. At the very first line count is 0, which is not above 1 either, so nothing is written.
    8. Write the value once. result.push(prev), however long the run was.
    9. Start the next run with prev = lines[i].
    10. Count it as one: count = 1.
    11. After the loop, test the open run with if (count > 1).
    12. Write its value with result.push(prev).
    13. Join and return: result.join("\n").

    Tracing the example

    For ["a", "a", "b", "c", "c", "c"] the values after each iteration are:

    ilinecountprevpushed
    0a1a0
    1a2a0
    2b1b1
    3c1c1
    4c2c1
    5c3c1

    The "a" was pushed at i = 2, when "b" ended its run of 2. When "b" ended at i = 3 its count was 1, so nothing was pushed. The loop ends with the run of "c"s still open and a count of 3, and the block after the loop pushes it: the result is "a\nc".

    The solution in TypeScript

    class Solution {
        uniqDups(lines: string[]): string {
            let result: string[] = [];
            let count = 0;
            let prev: string | null = null;
            for (let i = 0; i < lines.length; i++) {
                if (count > 0 && lines[i] === prev) {
                    count++;
                } else {
                    if (count > 1) {
                        result.push(prev);
                    }
                    prev = lines[i];
                    count = 1;
                }
            }
            if (count > 1) {
                result.push(prev);
            }
            return result.join("\n");
        }
    }

    Language details:

    • let count = 0 has no annotation: TypeScript infers number from the initial value. prev needs one, because starting from null alone would not say that a string will be stored there later.
    • prev has the type string | null, and result is a string[]. The lesson compiles with strict checking off, so pushing prev compiles without complaint. The code is safe at run time, because count > 1 is only true after prev has been set to a line.
    • count++ and count = 1 change the same variable, so the one variable always describes the run in progress.
    • The condition count > 1 is what separates this version from the previous one, where the test was count > 0.

    One more point about the design: nothing needs to be remembered about earlier runs. At any moment the method only knows the current run, through prev and count, and a finished run is either written or forgotten right away. That is why the extra memory stays small and why a value that repeats in two separate places is reported twice, once for each run, instead of being merged into one.

    Complexity

    The loop visits each line once, so the time is O(n) in the total size of the input. The result holds at most one value per run of two or more lines, so the extra space is at most proportional to the input.

    Edge cases and common mistakes

    • Forgetting the last run. For ["a", "a"] the loop never sees a line that ends the run. Only the block after the loop writes "a". Without it the result would be empty.
    • Writing the value more than once. Pushing for every extra line in the run would give "c\nc" for a run of three "c"s. The value belongs in the output once per run.
    • Separate runs of one value. ["a", "a", "b", "a", "a"] gives "a\na": each run is judged and written on its own.
    • No repeats and empty input. ["a", "b"] and [] both give "".
    • Wrong threshold. Using count > 0 would turn this into the plain uniq of the first version.

    Testing

    linesResult
    ["a", "a", "b", "c", "c", "c"]"a\nc"
    ["a", "b"]""
    ["a", "a"]"a"
    ["x", "y", "y"]"y"
    ["a", "a", "b", "a", "a"]"a\na"
    []""

    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