Start learning free

LESSON 384 OF 409 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: uniq v1 — Drop Adjacent Duplicates in C++

Practice

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

    Uniq V1 in C++

    Keep going with C++About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free