Problem overview
This version of the uniq tool mirrors uniq -u. The function uniq_once takes a Vec<String> of lines and returns a single String holding only the lines that did not repeat back-to-back, joined by \n. Earlier versions of the tool collapsed or counted runs of equal lines. This one keeps a line only when its run has length exactly one.
The word "adjacent" matters. In ["a", "a", "b", "c", "c", "c"] the runs are a, a (length 2), b (length 1) and c, c, c (length 3), so the result is "b". A line that appears twice but not side by side counts as two separate runs of length one. For ["a", "b", "a"] the result is "a\nb\na", because every run has length one.
Approach: measure each run, keep the ones of length one
You could count how often each line occurs in a HashMap, but that would count repeats anywhere in the input, not only neighbours. The task is about runs, so the better tool is a single pass that remembers the current run: its text (prev) and its length so far (count).
For each line there are two cases:
- The line equals
prevand a run is going: the run grows, socountgoes up by one. - The line is different: the previous run has just ended. Its length is final, so this is the moment to decide whether it survives. Then a new run starts with this line, with
countset to 1.
The loop only discovers that a run ended when a different line arrives, so the very last run is never flushed inside the loop. It needs the same check after the loop. The work is one pass, so it runs in linear time.
Step by step
- Create
result, aVec<String>, to collect the surviving lines. It islet mutbecause it grows. - Create
count, starting at 0. Zero means that no run has started yet. - Create
prevas an emptyString. It holds the text of the current run. - Loop over the positions of
lineswith0..lines.len(). - Test for a continuing run:
count > 0and the line equalsprev. Thecount > 0part matters for the first line, as explained below. - In the
ifbranch, add 1 tocount. - In the
elsebranch, a different line has arrived, so first check whether the ended run hadcount == 1. - If so, push a copy of
prevontoresult. - Start the new run by storing a copy of the current line in
prev. - Set
countto 1, since the new run has one line so far. - After the loop, test
count == 1again. The last run has not been judged yet. - Push
previf that last run was a single line. - Join
resultwith"\n", which puts the separator only between lines.
The solution in Rust
impl Solution {
fn uniq_once(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());
}
return result.join("\n");
}
}
Rust details worth noticing:
- Why
clone().lines[i]is aStringowned by the vector, and you can't move it out of an index..clone()makes an independent copy forprev. Pushingprev.clone()likewise leavesprevusable afterwards. - Comparing strings.
lines[i] == prevcompares the contents of twoStringvalues, not their addresses. - The type of
count. It starts as the literal0and is compared with1, so Rust infers a default integer type (i32). A run can't be long enough to overflow it in any realistic input. joinon a vector of strings. It builds oneStringwith the separator between neighbours only, so there is no trailing newline. An emptyresultgives the empty string.- The
&&short-circuit. Ifcount > 0is false, the comparison is skipped.
Complexity
Time: O(total length of the lines). Each line is visited once. Comparing it with prev and cloning it cost time proportional to its length. In terms of the number of lines n that is O(n) line operations.
Space: O(total length of the lines). result holds copies of the surviving lines, and prev holds one more.
Edge cases and common mistakes
- Forgetting the last run. Without the check after the loop,
["a", "b"]would lose"b", because no line follows it to end its run. - Dropping
count > 0from the condition. Then an empty first line,"", would equal the initial emptyprevand be treated as continuing a run that never started. Withcount > 0, the first line always starts a run. For["", "", "z"]the two empty lines form a run of length 2 and are dropped. - Treating repeats as global.
["a", "b", "a"]keeps all three lines, because no two equal lines are neighbours. - Empty input. The loop never runs,
countstays 0 and the result is the empty string. - Everything repeated.
["x", "x", "x"]gives the empty string. - Judging a run too early. Testing
count == 1when a line first matchesprevwould see a run of length one before it had a chance to grow.
Testing
["a", "a", "b", "c", "c", "c"]gives"b".["a", "b", "a"]gives"a\nb\na".["x", "x", "x"]gives"".[]gives"".["", "", "z"]gives"z".["a", "b", "c"]gives"a\nb\nc".["q"]gives"q".
