Start learning free

LESSON 389 OF 414 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: uniq v1 — Drop Adjacent Duplicates in Rust

Practice

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

    Uniq V1 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