Start learning free

LESSON 391 OF 414 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: uniq v3 — Duplicates Only in Rust

Practice

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:

fn uniq_dups(lines: Vec<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.


Track prev and count. When the line changes (or after the loop), flush prev only if count > 1. After collecting the survivors, join them with "\n" using Vec::join.

if count > 1 {
    result.push(prev.clone());
}


The full solution:
impl Solution {
    fn uniq_dups(lines: Vec<String>) -> String {
        let mut result: Vec<String> = Vec::new();
        let mut count = 0;
        let mut prev = String::new();
        for i in 0..lines.len() {
            if count > 0 && lines[i] == prev {
                count += 1;
            } else {
                if count > 1 {
                    result.push(prev.clone());
                }
                prev = lines[i].clone();
                count = 1;
            }
        }
        if count > 1 {
            result.push(prev.clone());
        }
        result.join("\n")
    }
}

STEP 1 OF 13
    Ctrl + Enter to check

    Uniq V3 in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free