Start learning free

LESSON 17 OF 69 · PROJECTS: COMMAND-LINE TOOLS

uniq in Rust: Removing 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:

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

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.


Build a Vec<String> result and push the current line only if result is empty or the line differs from result[result.len() - 1]. Then join the survivors with result.join("\n").

if result.is_empty() || lines[i] != result[result.len() - 1] {
    result.push(lines[i].clone());
}


The full solution:
impl Solution {
    fn uniq(lines: Vec<String>) -> String {
        let mut result: Vec<String> = Vec::new();
        for i in 0..lines.len() {
            if result.is_empty() || lines[i] != result[result.len() - 1] {
                result.push(lines[i].clone());
            }
        }
        return result.join("\n");
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Uniq V1 in Rust, explained

    Problem overview

    This is a small version of the Unix uniq command. The function uniq takes a Vec<String> of lines and drops adjacent duplicates: in each run of equal consecutive lines only the first is kept. The surviving lines are joined with \n into one String.

    For lines = ["a", "a", "b", "c", "c", "c", "a"], the result is "a\nb\nc\na". The final "a" survives because it isn't next to the first run of "a"s. Only lines that touch are merged, so the function is not the same as removing every repeated value.

    Approach: compare each line with the last one kept

    A line is a duplicate when it equals the line right before it. Since duplicates are dropped, the line right before it in the input is the same as the last line that was kept, so the function can compare against the end of the result it is building. That needs no extra variable.

    The first line is the exception: nothing has been kept yet, so there is no last item to compare with. It is always kept. The condition therefore has two parts joined with ||: the result is empty, or the current line differs from the last kept line. The empty check comes first because || stops as soon as its left side is true, so the code that reads the last item runs only when there is one.

    Take ["a", "b", "a"]. The first "a" is kept because the result is empty. "b" differs from the last kept "a", so it is kept. The last "a" differs from the last kept "b", so it is kept as well, and the output is "a\nb\na".

    Step by step

    1. Create the result vector. A Vec<String> made with Vec::new() and declared with let mut, since lines will be added to it.
    2. Loop over the positions. for i in 0..lines.len() gives i every value from 0 up to, but not including, the number of lines. lines[i] is the line at that position.
    3. Decide whether to keep the line. The if is true when result.is_empty(), or when lines[i] differs from result[result.len() - 1], the last item of result.
    4. Keep it. result.push(lines[i].clone()) adds a copy. The vector needs its own text, and a line that equals the one kept just before never reaches this statement.
    5. Join and return. result.join("\n") glues the lines together with a newline between each two. The argument goes between the items, so no newline follows the last line.

    The solution in Rust

    impl Solution {
        fn uniq(lines: Vec<String>) -> String {
            let mut result: Vec<String> = Vec::new();
            for i in 0..lines.len() {
                if result.is_empty() || lines[i] != result[result.len() - 1] {
                    result.push(lines[i].clone());
                }
            }
            return result.join("\n");
        }
    }
    

    Rust details worth knowing:

    • Short-circuit protects the subtraction. result.len() - 1 is a usize subtraction. When result is empty it would underflow: it panics in a debug build, and in an optimized build it wraps to a huge index that then panics on the indexing. result.is_empty() || in front guarantees the right side runs only when the vector has at least one item.
    • Comparing strings. != on two Strings compares their contents. Indexing with lines[i] doesn't move the string out of the vector here, because the comparison only borrows it.
    • clone(). push takes ownership, and lines[i] can't be moved out of a vector by indexing. Cloning gives the result its own copy of the text.
    • last() as an alternative. result.last() returns an Option and avoids the arithmetic. The lesson uses the index form to keep the steps simple.

    Complexity

    Time: O(L), where L is the total length of all lines. Each line is compared once with the last kept line, and a comparison costs at most the length of the shorter text. Copying and joining the kept lines is linear too.

    Space: O(L) in the worst case, when no line is a duplicate and every line is copied into the result.

    Edge cases and common mistakes

    • Empty list. The loop doesn't run, and the result is "".
    • One run only. ["x", "x", "x"] gives "x".
    • Non-adjacent repeats stay. ["a", "b", "a"] gives "a\nb\na". Using a set to drop all repeats would be a different, wrong answer.
    • Case counts. ["a", "A"] gives "a\nA", because "a" and "A" are different strings.
    • Empty strings are lines. ["", ""] collapses to a single empty line, so the result is "". It looks the same as the result for an empty list, since an empty string joined with nothing is still empty.
    • Swapping the two conditions. Putting the comparison before result.is_empty() reads result[result.len() - 1] on an empty vector, which fails.
    • Comparing with the wrong line. Comparing against lines[i - 1] works too, but it needs its own guard for i == 0. Comparing with the last kept line is simpler.

    Testing

    Inputs worth trying, with the results the function returns:

    • ["a", "a", "b", "c", "c", "c", "a"] gives "a\nb\nc\na".
    • ["x", "x", "x"] gives "x".
    • ["a", "b", "a"] gives "a\nb\na".
    • ["a", "A"] gives "a\nA".
    • ["", ""] gives "".
    • An empty vector 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