Problem overview
The function uniq takes a vector<string> of lines and removes adjacent duplicates: in every run of identical consecutive lines, only the first is kept. It returns the surviving lines joined by newline characters, with no newline after the last one.
For ["a", "a", "b", "c", "c", "c", "a"] the result is "a\nb\nc\na". The final "a" is kept because it is not next to the first run of "a": only consecutive repeats are removed, not repeats anywhere in the input.
Approach: compare each line with the last one kept
A set would remove every repeat anywhere, which is the wrong rule here. All that is needed is to remember the most recent kept line. When a new line equals it, the new line is a repeat in the same run and is skipped. When it differs, a new run has begun, and the line is kept.
The last kept line is the last item of the result vector, and back() returns it. Because the previous line of a run is always the last kept line, comparing with result.back() gives the same answer as comparing with the previous input line.
There is one special case: the very first line has nothing before it, and an empty vector has no last item. The test therefore checks result.empty() first, and the comparison runs only when the vector has something in it.
The second half of the function turns the vector into one string. C++ has no ready-made join for strings, so a loop adds a newline before every item except the first and then the item itself.
Step by step
- Create an empty
vector<string>namedresultfor the lines to keep. It grows as lines are added. - Loop over the lines with
ifrom 0 whilei < lines.size(). - Test
result.empty() || lines[i] != result.back(). The line is kept if nothing has been kept yet, or if it differs from the last kept line. - Add the line with
push_backinside theif. A line equal to the last kept one never gets here. - Create an empty
stringnamedoutafter the loop. The kept lines are added to its end. - Loop over
resultwithifrom 0 whilei < result.size(). Thisicounts positions inresult, not inlines. - Add
"\n"tooutwheni > 0. A newline goes between two lines, so the first one needs none. - Add
result[i]toout. - Return
outafter the second loop.
The solution in C++
class Solution {
public:
string uniq(vector<string> lines) {
vector<string> result;
for (int i = 0; i < lines.size(); i++) {
if (result.empty() || lines[i] != result.back()) {
result.push_back(lines[i]);
}
}
string out;
for (int i = 0; i < result.size(); i++) {
if (i > 0) out += "\n";
out += result[i];
}
return out;
}
};
The C++ details worth a closer look:
- The order of
||matters. The operator stops as soon as its left side is true. Whenresultis empty,result.empty()is true, soresult.back()never runs. Callingback()on an empty vector is undefined behaviour, so the two operands can't be swapped. !=on strings compares contents. The comparison is exact, so"a"and"A"are different lines, and an empty string is a perfectly good line to compare.push_backcopies the string. The vector gets its own copy oflines[i], and the input is not modified.- Two separate indexes named
i. Eachfordeclares its owni, and the first one is gone when the loop ends, so the second loop can reuse the name. - Joining with
+=.out += "\n"andout += result[i]append to the end of the string. The separator goes in before every item but the first, so there is no newline at the end.
Complexity
Time: O(total length). Each line is compared once with the last kept line, and a comparison costs at most the length of the shorter string. Each kept line is then copied into the vector and into the output string.
Space: O(total length). The result vector and the out string each hold copies of the kept lines, and the by-value parameter copies the input.
Edge cases and common mistakes
- Empty input.
[]gives"". Both loops run zero times, andoutis returned empty. - A single line.
["x"]gives"x". - Blank lines are lines.
["", "", "a"]gives"\na". The two empty lines form one run, so one empty line survives, and then"a"follows after a newline. The check for an emptyresultis what lets the first empty line in. - Case matters.
["a", "A", "a"]gives"a\nA\na", because every neighbour differs. - Repeats that are not adjacent. The final
"a"in the main example stays. A rule that removed every repeat anywhere would drop it. - Comparing with the wrong item. Comparing
lines[i]withlines[i - 1]works fori > 0but reads outside the vector ati = 0. Comparing withresult.back()and checking for empty first avoids the problem. - A trailing newline. Adding
"\n"after each item instead of before all but the first leaves one at the end that the expected result doesn't have.
Testing
["a", "a", "b", "c", "c", "c", "a"]gives"a\nb\nc\na".["", "", "a"]gives"\na".["a", "A", "a"]gives"a\nA\na".["x"]gives"x".[]gives"".
