Problem overview
This version builds uniq -d. The function uniq_dups takes a Vec<String> of lines and returns only the values that repeat back to back, meaning their run of adjacent equal lines is longer than one. Each such value appears once in the output, with no count, and the values are joined with \n.
For lines = ["a", "a", "b", "c", "c", "c"] the result is "a\nc". The run of "a"s has length 2 and the run of "c"s has length 3, so both survive. The lone "b" is dropped.
Approach: the run tracker from the counting version, with a different filter
This version uses the same idea as the counting one: keep prev, the text of the current run, and count, its length so far. When a different line arrives, the previous run is over and can be judged. The counting version wrote every finished run with its length. This one writes a finished run only if its length is above 1, and writes just the text once, however long the run was.
Two parts of the logic are easy to miss:
- A run is judged when it ends, which is when a different line arrives. The last run never meets one, so it has to be judged again after the loop.
- Repeats that aren't adjacent don't count. In
["a", "b", "a"]the value"a"appears twice, but the two copies are in separate runs of length 1, so the result is empty.
For ["a", "a", "b", "a", "a"], the run of two "a"s ends when "b" arrives and is written. The run of "b" has length 1 and is skipped. The last run of two "a"s is written after the loop. The same value shows up twice in the output, because it forms two separate runs: "a\na".
Step by step
- Create the result vector as a
let mutVec<String>. It will hold one copy of each value that repeated. - Create
countwithlet mutat 0, meaning no run has started. - Create
prevasString::new(), to remember what the current run is made of. - Loop over the positions with
for i in 0..lines.len(). - Branch on continuation. The
ifneedscount > 0andlines[i] == prev. Everything else goes toelse. - Extend the run in the
ifbranch: add 1 tocount. - Test whether the ended run repeated. In the
elsebranch,if count > 1is true for a run of two or more lines. At the very first linecountis 0, which also fails the test. - Keep one copy. Inside that
if,result.push(prev.clone())adds the run's text once. - Start the new run. After the inner
if, setprevtolines[i].clone(), the first line of the new run. - Set
countto 1 for that line. - Judge the open run after the loop with the same test,
if count > 1, outside the loop. - Keep its text with
result.push(prev.clone()). - Join and return with
result.join("\n").
The solution in Rust
impl Solution {
fn uniq_dups(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 > 1 {
result.push(prev.clone());
}
prev = lines[i].clone();
count = 1;
}
}
if count > 1 {
result.push(prev.clone());
}
result.join("\n")
}
}
Rust details worth knowing:
prev.clone().pushtakes ownership of the value it receives. The function still needsprevafterwards, since the final test after the loop reads it, so it pushes a copy.- Reassigning
prev.prev = lines[i].clone();replaces the old string, which is dropped automatically. This is whyprevis declared withmut. - The count's type.
countstarts as a bare0, and the compiler gives it the default integer type,i32. - Ending without
return. The last line,result.join("\n"), has no semicolon, so it is the function's value. Writingreturn result.join("\n");would mean the same.
Complexity
Time: O(L), where L is the total length of all lines. Each line is compared once with prev, and is copied at most once when it starts a run or when a repeated run is written.
Space: O(L) in the worst case, when many runs repeat and the result holds one copy of each.
Edge cases and common mistakes
- No repeats.
["a", "b", "a"]gives"", because no value repeats back to back. - A repeated run at the end.
["b", "a", "a"]gives"a". Without the test after the loop, the final run would never be written. - A value that forms two runs.
["a", "a", "b", "a", "a"]gives"a\na". Each run is judged on its own. - Printing every line of a run. A run of three
"c"s produces a single"c". The push happens once, when the run ends. - Using
count > 0in the tests. That would keep runs of length 1 as well and turn the function into a plain duplicate remover. The threshold has to be 1. - Single and empty input.
["x"]gives"", and an empty vector gives"". - Empty lines.
["", ""]is a run of two empty strings, so the single value written is an empty string, and the joined result is"". It looks the same as having no duplicates.
Testing
Inputs worth trying, with the results the function returns:
["a", "a", "b", "c", "c", "c"]gives"a\nc".["a", "b", "a"]gives"".["a", "a", "b", "a", "a"]gives"a\na".["b", "a", "a"]gives"a".["x"]gives"".
