Problem overview
This version of the uniq tool works like uniq -u. The method uniqOnce(vector<string> lines) returns only the lines whose run of identical neighbours has length exactly one. A line that repeats right after itself is dropped completely, every copy of it. The survivors are joined by \n.
Only adjacent repeats count. With {"a", "a", "b", "c", "c", "c"} the two a lines and the three c lines are dropped, and the lone b survives, so the result is "b". With {"a", "b", "a"} the two a lines are not neighbours, so each is a run of length one and the result is "a\nb\na".
Approach
Since only neighbours matter, one pass is enough. Think of the input as a series of runs: maximal stretches of equal lines. For each run you need to know its text and its length. If the length is 1, the run's text goes into the output; otherwise it is dropped.
The loop therefore tracks the current run with two variables: prev, the text of the run, and count, how many lines it has so far. Each line either continues the run (same text, so count grows) or ends it and starts a new one. A run is only known to be finished when a different line arrives, and that is the moment to decide whether to keep it.
That creates one case the loop cannot handle: the last run never meets a different line, so nothing ends it. The code repeats the check once after the loop for that run. This "flush the last group" step is a common pattern for any loop that processes groups of consecutive items.
The survivors are collected in a vector first and joined afterwards, with a newline before every line except the first, as in the other tools of this project.
Step by step
- Create an empty
vector<string>namedresultfor the lines that stand alone. - Create
int count = 0. Zero means no run has started yet. - Create
string prev = "", the text of the current run. - Loop over the lines with
int ifrom 0 whilei < lines.size(). - Test for a continuing run:
count > 0 && lines[i] == prev, with anelsefor the other case. - In the
ifbranch, increasecount. - In the
elsebranch, check whether the finished run stood alone:if (count == 1). At the very first linecountis 0, so nothing is added. - Inside that check,
push_back(prev)ontoresult. - Still in the
else, start the new run withprev = lines[i]. - Set
count = 1, because the new run has one line so far. - After the loop, repeat the test
if (count == 1), since the last run is still open. - Inside it,
push_back(prev)again. - Create an empty
stringnamedout. C++ has no ready-made join. - Loop over
resultwithint i. - Add
"\n"tooutwheni > 0. - Append
result[i]toout. - Return
outafter the second loop.
The solution in C++
class Solution {
public:
string uniqOnce(vector<string> lines) {
vector<string> result;
int count = 0;
string prev = "";
for (int i = 0; i < lines.size(); i++) {
if (count > 0 && lines[i] == prev) {
count++;
} else {
if (count == 1) {
result.push_back(prev);
}
prev = lines[i];
count = 1;
}
}
if (count == 1) {
result.push_back(prev);
}
string out;
for (int i = 0; i < result.size(); i++) {
if (i > 0) out += "\n";
out += result[i];
}
return out;
}
};
Some details of the C++ code:
- Comparing strings with
==. Forstd::stringit compares contents, so equal text in different variables is equal. - Short-circuit
&&. Incount > 0 && lines[i] == prevthe second part is only evaluated if the first is true. The test makes the meaning explicit: a run must exist before a line can continue it. - The names
prevandout.prevholds the run's text, not the previous index. It changes only when a new run starts. - Unsigned sizes.
lines.size()andresult.size()are unsigned. Compared with theintindex they work because the index is never negative. - The input is a copy. The vector is passed by value, so the function can read it freely without affecting the caller's vector. For a large input a
constreference would avoid the copy.
Complexity
The first loop visits each line once and compares it with prev, which costs up to the length of the line. The second loop joins the survivors. The time is proportional to the total size of the input text. The extra space is the vector of survivors and the output string, each at most the size of the input.
Edge cases and common mistakes
- Forgetting the last run. Without the check after the loop, a lone last line is lost. With
{"q"}the loop only starts the run, and the result is empty instead of"q". - Everything repeated.
{"x", "x"}returns"". - Non-adjacent repeats.
{"a", "b", "a"}keeps all three lines, because the lesson counts only neighbours. - Empty lines. An empty string is a line like any other.
{"", "", "k"}returns"k", since the two empty lines form a run of two.{"", "z"}returns"\nz", because the lone empty line survives and the result starts with its separator. - Empty input. No lines, no runs, result
"". - Keeping one copy of repeated lines. That is plain
uniq. Here a repeated line disappears entirely.
Testing
| lines | result |
|---|---|
{"a", "a", "b", "c", "c", "c"} | "b" |
{"a", "b", "a"} | "a\nb\na" |
{"x", "x"} | "" |
{"", "", "k"} | "k" |
{"", "z"} | "\nz" |
{"q"} | "q" |
{} | "" |
