Start learning free

LESSON 17 OF 69 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool uniq v1 in C++: Drop Adjacent Duplicates with back()

Practice Read the full explanation

Build a tiny version of the Unix uniq command. Given a list of lines, drop adjacent duplicate lines (keep only the first occurrence in each consecutive run) and return the surviving lines joined by newline characters (\n).

Function signature:

string uniq(vector<string> lines)

Example:

Input: lines = ["a", "a", "b", "c", "c", "c", "a"]

Output: "a\nb\nc\na"

When printed:
a
b
c
a

Notice that the trailing "a" survives because it is not adjacent to the first run of "a"s — only consecutive duplicates are removed.


Build a vector<string> result. Push the current line only if result is empty or the line differs from result.back(). Then concatenate everything with "\n" separators.

if (result.empty() || lines[i] != result.back()) {
    result.push_back(lines[i]);
}


The full solution:
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;
    }
};

STEP 1 OF 9
    Ctrl + Enter to check

    C++ · PROJECTS: COMMAND-LINE TOOLS

    Uniq V1 in C++, explained

    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

    1. Create an empty vector<string> named result for the lines to keep. It grows as lines are added.
    2. Loop over the lines with i from 0 while i < lines.size().
    3. 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.
    4. Add the line with push_back inside the if. A line equal to the last kept one never gets here.
    5. Create an empty string named out after the loop. The kept lines are added to its end.
    6. Loop over result with i from 0 while i < result.size(). This i counts positions in result, not in lines.
    7. Add "\n" to out when i > 0. A newline goes between two lines, so the first one needs none.
    8. Add result[i] to out.
    9. Return out after 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. When result is empty, result.empty() is true, so result.back() never runs. Calling back() 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_back copies the string. The vector gets its own copy of lines[i], and the input is not modified.
    • Two separate indexes named i. Each for declares its own i, and the first one is gone when the loop ends, so the second loop can reuse the name.
    • Joining with +=. out += "\n" and out += 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, and out is 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 empty result is 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] with lines[i - 1] works for i > 0 but reads outside the vector at i = 0. Comparing with result.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 "".
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free