Start learning free

LESSON 615 OF 671 · PROJECTS: COMMAND-LINE TOOLS

uniq in JavaScript: 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)

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. Compare against the LAST element of result, not against all previous elements.

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


The full solution:
class Solution {
    uniq(lines) {
        let result = [];
        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

    JAVASCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Uniq V1 in JavaScript, explained

    Problem overview

    The method uniq(lines) is a small version of the Unix uniq command. It receives an array of strings, removes lines that repeat the line just before them, and returns the surviving lines joined by "\n". Only adjacent duplicates are removed: from each run of equal consecutive lines, the first one stays.

    For ["a", "a", "b", "c", "c", "c", "a"] the result is "a\nb\nc\na". The final "a" survives because it is not next to the earlier "a"s; a different line sits between them.

    Approach: compare each line with the last one kept

    A line is a duplicate when it equals the line right before it in the output. So keep an array of survivors, and for each incoming line compare it with the last item of that array. If it is different, keep it; if it is the same, skip it.

    The first line is a special case: nothing has been kept yet, so there is no last item to compare with. The condition handles that by asking first whether the result is empty, and only then comparing with the last item. In JavaScript the second half of an || is skipped when the first half is already true, so result[result.length - 1] is never evaluated on an empty array.

    This approach does not need to sort the lines or remember every line seen, which is why only adjacent duplicates are removed. A set of seen lines would remove all duplicates, which is a different task.

    Step by step

    1. Create result as an empty array. It holds the lines to keep.
    2. Loop over the positions with for (let i = 0; i < lines.length; i++).
    3. Write the keep test: result.length === 0 || lines[i] !== result[result.length - 1]. The last item of an array sits at index length - 1, and the empty check comes first for the reason above.
    4. Push lines[i] onto result inside the if.
    5. Return result.join("\n") after the loop. The separator goes only between lines, so there is no newline after the last one.

    The solution in JavaScript

    class Solution {
        uniq(lines) {
            let result = [];
            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:

    • !== is the strict "not equal": for strings it compares the characters and never converts types.
    • JavaScript has no negative array indexing, so result[-1] would be undefined. That is why the last item is written as result[result.length - 1].
    • Comparing against the last kept line is the same as comparing against the previous input line, because a skipped line was equal to the last kept one.

    Complexity

    Each line is compared once with one other line, so the time is proportional to the total text size (string comparison looks at characters). The result array may hold every line, so extra space is O(L) references for L lines.

    Edge cases and common mistakes

    • Empty array. The result is "".
    • Non-adjacent duplicates stay. Both "a"s at the ends of the example survive.
    • Empty-string lines. ["", "", "x"] gives "\nx": one empty line is kept, then "x". An empty line is a real line.
    • Using a set. That removes duplicates anywhere, not only next to each other.

    Testing

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