Start learning free

LESSON 617 OF 671 · PROJECTS: COMMAND-LINE TOOLS

uniq -d in JavaScript: Printing Only Repeated Lines

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)

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

    JAVASCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Uniq V3 in JavaScript, explained

    Problem overview

    The method uniqDups(lines) is the -d flag of the Unix uniq command. It keeps only the lines that repeat back to back: for every run of adjacent equal lines longer than one, it outputs the value once, with no count. The values are joined by "\n".

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

    Approach: the run tracker, with a different decision

    The previous version kept two variables for the current run, prev (its line) and count (its length so far), and wrote an output line each time a run ended. This version uses the same machinery. Only what happens when a run ends changes: instead of writing every run with its count, write the line only if the run was longer than one, and write just the value.

    The run ends when a different line arrives, so the decision happens in the else branch, using count > 1. At the very first line count is 0, and 0 is not above 1, so nothing is written for a run that never existed. No separate "was there a run" check is needed.

    As before, the last run is never ended by a different line. After the loop, the same test must be applied once more, or a repeated line at the end of the input would be lost.

    Step by step

    1. Create result as an empty array. It holds one copy of each repeated line.
    2. Create count at 0, where 0 means no run has started.
    3. Create prev as null, the line of the current run.
    4. Loop over the positions with for (let i = 0; i < lines.length; i++).
    5. Branch on count > 0 && lines[i] === prev: a run exists and this line extends it.
    6. In the if, do count++.
    7. In the else, a different line has arrived and the old run is over. Test count > 1 to ask whether it was repeated.
    8. Push prev inside that test. One copy is enough, however long the run was.
    9. Start the next run by setting prev = lines[i].
    10. Set count = 1: the new run has one line so far.
    11. After the loop, test count > 1 again for the last run, which is still open.
    12. Push prev inside that test.
    13. Return result.join("\n").

    Tracing the example

    For ["a", "a", "b", "c", "c", "c"], the state after each pass of the loop is:

    ilineprev aftercount aftervalues written so far
    0"a""a"10
    1"a""a"20
    2"b""b"11
    3"c""c"11
    4"c""c"21
    5"c""c"31

    When "b" arrives, the run of "a" has count 2, so "a" is written. When the first "c" arrives, the run of "b" has count 1 and is skipped. The run of "c" is still open at the end with count 3, and the check after the loop writes it, giving "a\nc".

    The solution in JavaScript

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

    • prev starts as null and is only pushed when count > 1, which can only happen after prev has been given a real line.
    • result.push(prev) adds the string itself, not a copy with a count, so the output contains just values.
    • The two checks count > 1 are the same test written twice: once for runs ended inside the loop, once for the final run after it.

    Comparing with the counting version

    The structure of the loop is identical to the previous version, and only the action taken at the end of a run differs. That is a useful habit: when a new requirement arrives, first ask which part of the working code actually has to change. Here the answer is one condition (count > 1) and one pushed value (prev instead of a formatted line), so the rest is reused as it is, including the final check after the loop.

    If you wanted every repeated value only once, even across separate runs, you would need a different tool, such as a set of values already reported. This lesson reports each run on its own, as the "a\na" example below shows.

    Complexity

    The function reads each line once and compares it with prev, so time is proportional to the total text size. The result holds at most one entry per run, so extra space is at most proportional to the number of lines.

    Edge cases and common mistakes

    • Forgetting the final test. For ["x", "x"], the loop never ends the run, and without the last check the result would be "" instead of "x".
    • Pushing on every line of a run. A run of 3 must give one value, not three.
    • Using count > 0 instead of count > 1. That would keep single lines too and act like the first version.
    • Non-adjacent repeats do not count. ["a", "b", "a"] gives "", since no line repeats next to itself.
    • Same value in two separate runs. ["a", "a", "b", "a", "a"] gives "a\na", because each run is reported on its own.

    Testing

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