Start learning free

LESSON 20 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Uniq V4 in Rust: Only the Unique Lines (-u)

Practice Read the full explanation

Build a version of the Unix uniq -u command. Given a list of lines, output only the values whose adjacent run length is exactly one — i.e. lines that did NOT repeat back-to-back. Surviving values are joined by \n.

Function signature:

fn uniq_once(lines: Vec<String>) -> String

Example:

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

Output: "b"

When printed:
b

The two "a"s and the three "c"s are dropped because their runs are longer than 1. Only the lone "b" survives.


Track a String named prev and an integer count. When the line changes (or after the loop), flush prev only if count == 1.

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


The full solution:
impl Solution {
    fn uniq_once(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());
        }
        return result.join("\n");
    }
}

STEP 1 OF 13
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Uniq V4 in Rust, explained

    Problem overview

    This version of the uniq tool mirrors uniq -u. The function uniq_once takes a Vec<String> of lines and returns a single String holding only the lines that did not repeat back-to-back, joined by \n. Earlier versions of the tool collapsed or counted runs of equal lines. This one keeps a line only when its run has length exactly one.

    The word "adjacent" matters. In ["a", "a", "b", "c", "c", "c"] the runs are a, a (length 2), b (length 1) and c, c, c (length 3), so the result is "b". A line that appears twice but not side by side counts as two separate runs of length one. For ["a", "b", "a"] the result is "a\nb\na", because every run has length one.

    Approach: measure each run, keep the ones of length one

    You could count how often each line occurs in a HashMap, but that would count repeats anywhere in the input, not only neighbours. The task is about runs, so the better tool is a single pass that remembers the current run: its text (prev) and its length so far (count).

    For each line there are two cases:

    • The line equals prev and a run is going: the run grows, so count goes up by one.
    • The line is different: the previous run has just ended. Its length is final, so this is the moment to decide whether it survives. Then a new run starts with this line, with count set to 1.

    The loop only discovers that a run ended when a different line arrives, so the very last run is never flushed inside the loop. It needs the same check after the loop. The work is one pass, so it runs in linear time.

    Step by step

    1. Create result, a Vec<String>, to collect the surviving lines. It is let mut because it grows.
    2. Create count, starting at 0. Zero means that no run has started yet.
    3. Create prev as an empty String. It holds the text of the current run.
    4. Loop over the positions of lines with 0..lines.len().
    5. Test for a continuing run: count > 0 and the line equals prev. The count > 0 part matters for the first line, as explained below.
    6. In the if branch, add 1 to count.
    7. In the else branch, a different line has arrived, so first check whether the ended run had count == 1.
    8. If so, push a copy of prev onto result.
    9. Start the new run by storing a copy of the current line in prev.
    10. Set count to 1, since the new run has one line so far.
    11. After the loop, test count == 1 again. The last run has not been judged yet.
    12. Push prev if that last run was a single line.
    13. Join result with "\n", which puts the separator only between lines.

    The solution in Rust

    impl Solution {
        fn uniq_once(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());
            }
            return result.join("\n");
        }
    }
    

    Rust details worth noticing:

    • Why clone(). lines[i] is a String owned by the vector, and you can't move it out of an index. .clone() makes an independent copy for prev. Pushing prev.clone() likewise leaves prev usable afterwards.
    • Comparing strings. lines[i] == prev compares the contents of two String values, not their addresses.
    • The type of count. It starts as the literal 0 and is compared with 1, so Rust infers a default integer type (i32). A run can't be long enough to overflow it in any realistic input.
    • join on a vector of strings. It builds one String with the separator between neighbours only, so there is no trailing newline. An empty result gives the empty string.
    • The && short-circuit. If count > 0 is false, the comparison is skipped.

    Complexity

    Time: O(total length of the lines). Each line is visited once. Comparing it with prev and cloning it cost time proportional to its length. In terms of the number of lines n that is O(n) line operations.

    Space: O(total length of the lines). result holds copies of the surviving lines, and prev holds one more.

    Edge cases and common mistakes

    • Forgetting the last run. Without the check after the loop, ["a", "b"] would lose "b", because no line follows it to end its run.
    • Dropping count > 0 from the condition. Then an empty first line, "", would equal the initial empty prev and be treated as continuing a run that never started. With count > 0, the first line always starts a run. For ["", "", "z"] the two empty lines form a run of length 2 and are dropped.
    • Treating repeats as global. ["a", "b", "a"] keeps all three lines, because no two equal lines are neighbours.
    • Empty input. The loop never runs, count stays 0 and the result is the empty string.
    • Everything repeated. ["x", "x", "x"] gives the empty string.
    • Judging a run too early. Testing count == 1 when a line first matches prev would see a run of length one before it had a chance to grow.

    Testing

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