Start learning free

LESSON 390 OF 414 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: uniq v2 — Count Adjacent Runs in Rust

Practice

Build a version of the Unix uniq -c command. Given a list of lines, collapse each run of adjacent duplicates into a single output line that shows the run's count followed by the value.

Each output line is formatted as format!("{:>7} {}", count, value): a 7-character right-aligned count, a single space, then the line value. Join all output lines with \n.

Function signature:

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

Example:

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

Output (when printed):
      2 a
      1 b
      3 c

The first run is two "a"s, then a single "b", then three "c"s — three output lines.


Track prev and count. When a NEW value arrives (or you reach the end), flush the previous run. Use format!("{:>7} {}", count, prev) to right-align the count and concat the line.

if count > 0 {
    result.push(format!("{:>7} {}", count, prev));
}
Don't forget to flush after the loop ends. A Vec<String> has a built-in .join("\n").

The full solution:
impl Solution {
    fn uniq_count(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 > 0 {
                    result.push(format!("{:>7} {}", count, prev));
                }
                prev = lines[i].clone();
                count = 1;
            }
        }
        if count > 0 {
            result.push(format!("{:>7} {}", count, prev));
        }
        return result.join("\n");
    }
}

STEP 1 OF 13
    Ctrl + Enter to check

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