Start learning free

LESSON 17 OF 70 · PROJECTS: COMMAND-LINE TOOLS

uniq in TypeScript: Dropping Adjacent Duplicate Lines

Practice Read the full explanation

Build a tiny version of the Unix uniq command. Given a list of lines, drop adjacent duplicate lines (keep only the first occurrence in each consecutive run) and return the surviving lines joined by newline characters (\n).

Function signature:

uniq(lines: string[]): string

Example:

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

Output: "a\nb\nc\na"

When printed:
a
b
c
a

Notice that the trailing "a" survives because it is not adjacent to the first run of "a"s — only consecutive duplicates are removed.


Walk the input array and push a line into your result only if it differs from the line you most recently pushed (result[result.length - 1]). Then join the survivors with result.join("\n").

if (result.length === 0 || lines[i] !== result[result.length - 1]) {
    result.push(lines[i]);
}


The full solution:
class Solution {
    uniq(lines: string[]): string {
        let result: string[] = [];
        for (let i = 0; i < lines.length; i++) {
            if (result.length === 0 || lines[i] !== result[result.length - 1]) {
                result.push(lines[i]);
            }
        }
        return result.join("\n");
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    TYPESCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Uniq V1 in TypeScript, explained

    Problem overview

    This project lesson builds a tiny uniq. The method uniq(lines: string[]): string removes adjacent duplicate lines, keeping the first line of each consecutive run, and returns the surviving lines joined by newline characters.

    For ["a", "a", "b", "c", "c", "c", "a"] the result is "a\nb\nc\na". Printed:

    a
    b
    c
    a

    The last "a" survives because it is not next to the first run of "a"s. Only consecutive duplicates are removed, so this is different from removing every repeated value.

    Approach: compare with the last line kept

    A set of seen values would be the wrong tool, because it would also remove the final "a". The rule only needs to know what the previous surviving line was. Because every line of a run is equal, the last item of the result is always the value of the run being read. So the rule becomes: keep a line if the result is empty, or if the line differs from the last item of the result.

    The order of the two tests in the condition matters. For the first line the result is empty and has no last item to compare with, so the emptiness check comes first and stops the second one from running.

    Step by step

    1. Create the result: an empty string[] named result, which will hold the lines to keep.
    2. Loop by position with i from 0 while i < lines.length. lines[i] is the current line.
    3. Decide. The if is true when result.length === 0, or when lines[i] differs from result[result.length - 1]. The last item of an array sits at index length - 1.
    4. Keep the line. result.push(lines[i]) adds it. A line equal to the one kept just before never gets here.
    5. Join and return. result.join("\n") puts a newline between each two lines and none after the last.

    The solution in TypeScript

    class Solution {
        uniq(lines: string[]): string {
            let result: string[] = [];
            for (let i = 0; i < lines.length; i++) {
                if (result.length === 0 || lines[i] !== result[result.length - 1]) {
                    result.push(lines[i]);
                }
            }
            return result.join("\n");
        }
    }

    Language details:

    • || short-circuits: when result.length === 0 is true, the right side is not evaluated. On an empty array the right side would read result[-1], which gives undefined rather than an error, but the emptiness check says what is meant.
    • !== and === compare strings by content, and no type conversion happens.
    • The array index result.length - 1 is the last element. TypeScript arrays have no negative indexing, so result[-1] is not the last element.
    • Blank lines are ordinary strings. ["", "", "a"] becomes "\na": one empty line survives, followed by a.

    Complexity

    The loop visits each line once, and each comparison and push takes time proportional to the line length at most, so the running time is O(n) in the total size of the input. The result array can hold every line, so the extra space is O(n) in the worst case, when no two neighbours are equal.

    Edge cases and common mistakes

    • Empty input. [] gives "". A single line gives that line.
    • Non-adjacent duplicates stay. The trailing "a" in the example is kept. A Set-based solution would remove it and fail.
    • A trailing newline. The result should have none; join puts the separator between lines only.
    • Case. "a" and "A" are different lines here.

    Testing

    linesResult
    ["a", "a", "b", "c", "c", "c", "a"]"a\nb\nc\na"
    []""
    ["x"]"x"
    ["", "", "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