Start learning free

LESSON 18 OF 69 · PROJECTS: COMMAND-LINE TOOLS

uniq -c in Rust: Counting Runs of Adjacent Duplicates

Practice Read the full explanation

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

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Uniq V2 in Rust, explained

    Problem overview

    This version builds uniq -c. The function uniq_count takes a Vec<String> of lines and collapses each run of adjacent equal lines into one output line that starts with the run's length. Each output line is format!("{:>7} {}", count, value): the count right-aligned in 7 characters, one space, then the line. The output lines are joined with \n.

    For lines = ["a", "a", "b", "c", "c", "c"], there are three runs: two "a"s, one "b" and three "c"s. Printed, the result is:

          2 a
          1 b
          3 c
    

    The previous version only decided whether to keep a line. Now the function has to know how long each run was, so it must keep a count while it reads.

    Approach: track the current run

    The function remembers two things about the run it is in: prev, the text the run consists of, and count, how many lines it has so far. A count of 0 means no run has started yet. For each line there are two cases:

    • The line equals prev and a run is going. The run grows: add 1 to count.
    • Otherwise a new run begins. If a run was going, it has just ended, so write its output line now. Then start the new run: prev becomes the current line and count becomes 1.

    A run is only written when a different line arrives after it, and the last run never meets such a line. When the loop ends, that run is still open, so the same output line has to be written once more after the loop, again only if a run exists. Forgetting this step is the classic bug in run-length code: the last group is lost.

    The test count > 0 in the first condition says "a run exists". At the start prev is an empty string, which is also a possible line, so prev alone can't tell whether a run has started. count can: it is 0 only before the first line.

    Step by step

    1. Create the result vector as a let mut Vec<String>. It will hold one output line for each run.
    2. Create count with let mut and start it at 0, meaning no run yet.
    3. Create prev with let mut as String::new(), an empty string. It remembers what the current run is made of.
    4. Loop over the positions with for i in 0..lines.len().
    5. Branch on whether the line continues the run. The if needs both count > 0 and lines[i] == prev. Its else handles every other case.
    6. Extend the run. In the if branch, add 1 to count.
    7. Test whether a run just ended. In the else branch, an inner if count > 0 is true when a run was going. Before the very first line, count is 0, so nothing is written.
    8. Write the finished run. Inside the inner if, push format!("{:>7} {}", count, prev). Each {} takes the next value, and :>7 pads the number on the left with spaces to width 7.
    9. Start the new run. Still in the else branch, after the inner if, set prev to a copy of the current line with lines[i].clone(). The line that ended the old run is the first line of the new one.
    10. Set count to 1, since the new run has one line so far.
    11. Test for an open run after the loop. An if count > 0 outside the loop is true whenever the input wasn't empty.
    12. Write the last run with the same format! push as inside the loop.
    13. Join and return with result.join("\n").

    The solution in Rust

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

    Rust details worth knowing:

    • The format spec. In {:>7}, the > means right-aligned and 7 is the minimum width. A shorter value is padded with spaces on the left. A longer one is not cut: with a run of 12 lines the output is " 12 q", five spaces and the digits 12 making up 7 characters.
    • Inferred integer type. count starts as a bare 0. Nothing else fixes its type, so the compiler picks the default, i32. That is plenty for a count of lines here.
    • Comparing and copying. lines[i] == prev compares the two strings' contents. prev = lines[i].clone() makes prev own a copy, because a line can't be moved out of the vector by indexing.
    • Reusing the old value. The first format! runs before prev is replaced, so it still sees the finished run's text. The order of the three statements in the else branch is what makes the code correct.

    Complexity

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

    Space: O(L) in the worst case, when every run has length 1 and the result holds one formatted line for each input line.

    Edge cases and common mistakes

    • Forgetting the last run. Without the if after the loop, ["a", "a", "b", "c", "c", "c"] would lose its final run of "c"s.
    • Empty list. The loop doesn't run and count stays 0, so nothing is pushed after it either. The result is "".
    • Non-adjacent repeats are separate runs. ["a", "b", "a"] gives three lines, each with a count of 1: " 1 a\n 1 b\n 1 a".
    • Empty lines. ["", ""] is one run of two empty strings, and its output line is the count padded to 7 characters, a space and nothing: " 2 ". The trailing space is part of the format.
    • An empty first line. ["", "x"] gives " 1 \n 1 x". The first empty line starts a run of its own, and "x" starts another.
    • Wrong width. The format is {:>7}, with a single space after it. Changing either gives different output.
    • Resetting too early. Setting prev and count before writing the old run's line would write the wrong text and number.

    Testing

    Inputs worth trying, with the results the function returns:

    • ["a", "a", "b", "c", "c", "c"] gives " 2 a\n 1 b\n 3 c".
    • ["z"] gives " 1 z".
    • Twelve copies of "q" give " 12 q".
    • ["a", "b", "a"] gives " 1 a\n 1 b\n 1 a".
    • 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