Start learning free

LESSON 19 OF 69 · PROJECTS: COMMAND-LINE TOOLS

uniq -d in Rust: Printing Only Lines That Repeat

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:

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

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Uniq V3 in Rust, explained

    Problem overview

    This version builds uniq -d. The function uniq_dups takes a Vec<String> of lines and returns only the values that repeat back to back, meaning their run of adjacent equal lines is longer than one. Each such value appears once in the output, with no count, and the values are joined with \n.

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

    Approach: the run tracker from the counting version, with a different filter

    This version uses the same idea as the counting one: keep prev, the text of the current run, and count, its length so far. When a different line arrives, the previous run is over and can be judged. The counting version wrote every finished run with its length. This one writes a finished run only if its length is above 1, and writes just the text once, however long the run was.

    Two parts of the logic are easy to miss:

    • A run is judged when it ends, which is when a different line arrives. The last run never meets one, so it has to be judged again after the loop.
    • Repeats that aren't adjacent don't count. In ["a", "b", "a"] the value "a" appears twice, but the two copies are in separate runs of length 1, so the result is empty.

    For ["a", "a", "b", "a", "a"], the run of two "a"s ends when "b" arrives and is written. The run of "b" has length 1 and is skipped. The last run of two "a"s is written after the loop. The same value shows up twice in the output, because it forms two separate runs: "a\na".

    Step by step

    1. Create the result vector as a let mut Vec<String>. It will hold one copy of each value that repeated.
    2. Create count with let mut at 0, meaning no run has started.
    3. Create prev as String::new(), to remember what the current run is made of.
    4. Loop over the positions with for i in 0..lines.len().
    5. Branch on continuation. The if needs count > 0 and lines[i] == prev. Everything else goes to else.
    6. Extend the run in the if branch: add 1 to count.
    7. Test whether the ended run repeated. In the else branch, if count > 1 is true for a run of two or more lines. At the very first line count is 0, which also fails the test.
    8. Keep one copy. Inside that if, result.push(prev.clone()) adds the run's text once.
    9. Start the new run. After the inner if, set prev to lines[i].clone(), the first line of the new run.
    10. Set count to 1 for that line.
    11. Judge the open run after the loop with the same test, if count > 1, outside the loop.
    12. Keep its text with result.push(prev.clone()).
    13. Join and return with result.join("\n").

    The solution in Rust

    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")
        }
    }
    

    Rust details worth knowing:

    • prev.clone(). push takes ownership of the value it receives. The function still needs prev afterwards, since the final test after the loop reads it, so it pushes a copy.
    • Reassigning prev. prev = lines[i].clone(); replaces the old string, which is dropped automatically. This is why prev is declared with mut.
    • The count's type. count starts as a bare 0, and the compiler gives it the default integer type, i32.
    • Ending without return. The last line, result.join("\n"), has no semicolon, so it is the function's value. Writing return result.join("\n"); would mean the same.

    Complexity

    Time: O(L), where L is the total length of all lines. Each line is compared once with prev, and is copied at most once when it starts a run or when a repeated run is written.

    Space: O(L) in the worst case, when many runs repeat and the result holds one copy of each.

    Edge cases and common mistakes

    • No repeats. ["a", "b", "a"] gives "", because no value repeats back to back.
    • A repeated run at the end. ["b", "a", "a"] gives "a". Without the test after the loop, the final run would never be written.
    • A value that forms two runs. ["a", "a", "b", "a", "a"] gives "a\na". Each run is judged on its own.
    • Printing every line of a run. A run of three "c"s produces a single "c". The push happens once, when the run ends.
    • Using count > 0 in the tests. That would keep runs of length 1 as well and turn the function into a plain duplicate remover. The threshold has to be 1.
    • Single and empty input. ["x"] gives "", and an empty vector gives "".
    • Empty lines. ["", ""] is a run of two empty strings, so the single value written is an empty string, and the joined result is "". It looks the same as having no duplicates.

    Testing

    Inputs worth trying, with the results the function returns:

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