Problem overview
This is a small version of the Unix uniq command. The function uniq takes a Vec<String> of lines and drops adjacent duplicates: in each run of equal consecutive lines only the first is kept. The surviving lines are joined with \n into one String.
For lines = ["a", "a", "b", "c", "c", "c", "a"], the result is "a\nb\nc\na". The final "a" survives because it isn't next to the first run of "a"s. Only lines that touch are merged, so the function is not the same as removing every repeated value.
Approach: compare each line with the last one kept
A line is a duplicate when it equals the line right before it. Since duplicates are dropped, the line right before it in the input is the same as the last line that was kept, so the function can compare against the end of the result it is building. That needs no extra variable.
The first line is the exception: nothing has been kept yet, so there is no last item to compare with. It is always kept. The condition therefore has two parts joined with ||: the result is empty, or the current line differs from the last kept line. The empty check comes first because || stops as soon as its left side is true, so the code that reads the last item runs only when there is one.
Take ["a", "b", "a"]. The first "a" is kept because the result is empty. "b" differs from the last kept "a", so it is kept. The last "a" differs from the last kept "b", so it is kept as well, and the output is "a\nb\na".
Step by step
- Create the result vector. A
Vec<String>made withVec::new()and declared withlet mut, since lines will be added to it. - Loop over the positions.
for i in 0..lines.len()givesievery value from 0 up to, but not including, the number of lines.lines[i]is the line at that position. - Decide whether to keep the line. The
ifis true whenresult.is_empty(), or whenlines[i]differs fromresult[result.len() - 1], the last item ofresult. - Keep it.
result.push(lines[i].clone())adds a copy. The vector needs its own text, and a line that equals the one kept just before never reaches this statement. - Join and return.
result.join("\n")glues the lines together with a newline between each two. The argument goes between the items, so no newline follows the last line.
The solution in Rust
impl Solution {
fn uniq(lines: Vec<String>) -> String {
let mut result: Vec<String> = Vec::new();
for i in 0..lines.len() {
if result.is_empty() || lines[i] != result[result.len() - 1] {
result.push(lines[i].clone());
}
}
return result.join("\n");
}
}
Rust details worth knowing:
- Short-circuit protects the subtraction.
result.len() - 1is ausizesubtraction. Whenresultis empty it would underflow: it panics in a debug build, and in an optimized build it wraps to a huge index that then panics on the indexing.result.is_empty() ||in front guarantees the right side runs only when the vector has at least one item. - Comparing strings.
!=on twoStrings compares their contents. Indexing withlines[i]doesn't move the string out of the vector here, because the comparison only borrows it. clone().pushtakes ownership, andlines[i]can't be moved out of a vector by indexing. Cloning gives the result its own copy of the text.last()as an alternative.result.last()returns anOptionand avoids the arithmetic. The lesson uses the index form to keep the steps simple.
Complexity
Time: O(L), where L is the total length of all lines. Each line is compared once with the last kept line, and a comparison costs at most the length of the shorter text. Copying and joining the kept lines is linear too.
Space: O(L) in the worst case, when no line is a duplicate and every line is copied into the result.
Edge cases and common mistakes
- Empty list. The loop doesn't run, and the result is
"". - One run only.
["x", "x", "x"]gives"x". - Non-adjacent repeats stay.
["a", "b", "a"]gives"a\nb\na". Using a set to drop all repeats would be a different, wrong answer. - Case counts.
["a", "A"]gives"a\nA", because"a"and"A"are different strings. - Empty strings are lines.
["", ""]collapses to a single empty line, so the result is"". It looks the same as the result for an empty list, since an empty string joined with nothing is still empty. - Swapping the two conditions. Putting the comparison before
result.is_empty()readsresult[result.len() - 1]on an empty vector, which fails. - Comparing with the wrong line. Comparing against
lines[i - 1]works too, but it needs its own guard fori == 0. Comparing with the last kept line is simpler.
Testing
Inputs worth trying, with the results the function returns:
["a", "a", "b", "c", "c", "c", "a"]gives"a\nb\nc\na".["x", "x", "x"]gives"x".["a", "b", "a"]gives"a\nb\na".["a", "A"]gives"a\nA".["", ""]gives"".- An empty vector gives
"".
