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
prevand a run is going. The run grows: add 1 tocount. - 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:
prevbecomes the current line andcountbecomes 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
- Create the result vector as a
let mutVec<String>. It will hold one output line for each run. - Create
countwithlet mutand start it at 0, meaning no run yet. - Create
prevwithlet mutasString::new(), an empty string. It remembers what the current run is made of. - Loop over the positions with
for i in 0..lines.len(). - Branch on whether the line continues the run. The
ifneeds bothcount > 0andlines[i] == prev. Itselsehandles every other case. - Extend the run. In the
ifbranch, add 1 tocount. - Test whether a run just ended. In the
elsebranch, an innerif count > 0is true when a run was going. Before the very first line,countis 0, so nothing is written. - Write the finished run. Inside the inner
if, pushformat!("{:>7} {}", count, prev). Each{}takes the next value, and:>7pads the number on the left with spaces to width 7. - Start the new run. Still in the
elsebranch, after the innerif, setprevto a copy of the current line withlines[i].clone(). The line that ended the old run is the first line of the new one. - Set
countto 1, since the new run has one line so far. - Test for an open run after the loop. An
if count > 0outside the loop is true whenever the input wasn't empty. - Write the last run with the same
format!push as inside the loop. - 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 and7is 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 digits12making up 7 characters. - Inferred integer type.
countstarts as a bare0. 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] == prevcompares the two strings' contents.prev = lines[i].clone()makesprevown a copy, because a line can't be moved out of the vector by indexing. - Reusing the old value. The first
format!runs beforeprevis replaced, so it still sees the finished run's text. The order of the three statements in theelsebranch 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
ifafter the loop,["a", "a", "b", "c", "c", "c"]would lose its final run of"c"s. - Empty list. The loop doesn't run and
countstays 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
prevandcountbefore 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
"".
