Start learning free

LESSON 20 OF 70 · PROJECTS: COMMAND-LINE TOOLS

Uniq V4 in TypeScript: uniq -u with a Run Counter

Practice Read the full explanation

Build a version of the Unix uniq -u command. Given a list of lines, output only the values whose adjacent run length is exactly one — i.e. lines that did NOT repeat back-to-back. Surviving values are joined by \n.

Function signature:

uniqOnce(lines: string[]): string

Example:

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

Output: "b"

When printed:
b

The two "a"s and the three "c"s are dropped because their runs are longer than 1. Only the lone "b" survives.


Same scaffolding as uniq -d, but the filter flips: flush prev only when count === 1.

if (count === 1) {
    result.push(prev);
}
Don't forget to flush AFTER the loop too.

The full solution:
class Solution {
    uniqOnce(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 === 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 V4 in TypeScript, explained

    Problem overview

    This version of the uniq project imitates uniq -u. The method uniqOnce receives an array of lines and returns a single string that holds only the lines that stand alone, joined with \n. A line stands alone when its run has length exactly one: the lines right before and right after it are different (or it is at an end of the array). Anything that repeats back to back is dropped completely, including its first copy.

    For ["a", "a", "b", "c", "c", "c"] the runs are a a, b and c c c. Only the run of b has length one, so the result is "b". The earlier version of this tool already walked through the lines tracking runs; this one changes what is kept.

    Approach: track the current run, decide when it ends

    The key word is adjacent. The lines are not sorted and not grouped, so you can't count occurrences with a single tally for the whole array. For ["a", "b", "a"] each "a" is alone, because the two copies are separated by "b", and the result is "a\nb\na".

    So the code follows one run at a time with two variables: prev, the text of the current run, and count, how many lines it has so far. When the next line equals prev, the run grows. When it differs, the current run is finished, and that is the moment to decide: keep prev if count is 1, then start a new run with the new line.

    A run only ends when a different line shows up, and the last run has nothing after it. That is why a second check is needed after the loop. It is the most common mistake in this lesson.

    A tempting shortcut is a Map from line to total count, keeping lines whose count is 1. It answers a different question: for ["a", "b", "a"] it would drop both "a"s, while the real command keeps them. The command works on neighbours only, which is why it is usually run on sorted input, where equal lines are already next to each other. This version doesn't sort: it takes the lines in the order given, and the single pass with prev and count needs no extra data structure.

    Step by step

    1. Create result, an empty string[] that will collect the surviving lines.
    2. Create count and start it at 0. Zero means that no run has started.
    3. Create prev, typed string | null and set to null, so it can say "no line yet".
    4. Loop over the positions of lines with i.
    5. Test for a continuing run: count > 0 and lines[i] === prev. Both must hold. The first condition matters for an empty line at the start, as shown in the edge cases below.
    6. In the if branch, add 1 to count.
    7. In the else branch, a different line has arrived, so the previous run is over. Check whether its count is 1. At the very first line count is 0, so nothing is pushed.
    8. Push prev when that check passes.
    9. Start the next run: set prev to lines[i].
    10. Set count to 1, because the new run has one line so far.
    11. After the loop, test count === 1 again, because the last run was never closed by a following line.
    12. Push prev for that last run if it is alone.
    13. Return result.join("\n"). join puts the separator only between elements, so there is no trailing newline, and an empty result gives "".

    The solution in TypeScript

    class Solution {
        uniqOnce(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 === 1) {
                        result.push(prev);
                    }
                    prev = lines[i];
                    count = 1;
                }
            }
            if (count === 1) {
                result.push(prev);
            }
            return result.join("\n");
        }
    }
    

    Language details

    • string | null is a union type: prev holds either text or null. Types are erased when TypeScript compiles to JavaScript, so at run time prev is simply a string or null.
    • === compares strings by content, so two separate string values with the same characters are equal.
    • The two if (count === 1) tests are the same on purpose: one closes a run when a different line arrives, the other closes the final run.

    Complexity

    The loop visits each line once and does constant work per line, so the time is O(n) for n lines (plus the cost of comparing strings and of the final join, which is proportional to the total text). The extra space is the result array, which holds at most n lines.

    Edge cases and common mistakes

    • Forgetting the last run. Without the check after the loop, ["a", "a", "b"] would return an empty string instead of "b", and ["x"] would lose its only line.
    • Non-adjacent repeats. ["a", "b", "a"] gives "a\nb\na": nothing is dropped, because no run is longer than one.
    • Every line repeated. ["a", "a"] gives "", and an empty array also gives "".
    • An empty line first. A line can be the empty string. Because the test is count > 0 && lines[i] === prev, an input like ["", "a", "a", "b"] gives "\nb": the empty line stands alone and is kept.
    • Keeping one copy of a repeated line. This command is not "remove duplicates". A run of length two or more disappears completely.

    Testing

    InputResult
    ["a", "a", "b", "c", "c", "c"]"b"
    ["a", "b", "a"]"a\nb\na"
    ["a", "a", "b"]"b"
    ["a", "b", "b"]"a"
    ["a", "a"]""
    []""
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free