Start learning free

LESSON 375 OF 409 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: head v4 — Negative n drops the tail in C++

Practice

Same signature as v2/v3, but now n may be negative. Real head -n -K prints all lines except the last K. So when n < 0 return all lines except the last |n|; when n ≥ 0 behave exactly like v3 (return the first n, capped at the input length). If |n| is at least the number of lines, nothing is left, so return the empty string.

Function signature:

string head(vector<string> lines, int n)

Example (negative n):

Input: lines = ["a", "b", "c", "d", "e"], n = -2

Output: "a\nb\nc"

When printed:
a
b
c

Branch on the sign of n: when n < 0, the end index is (int)lines.size() + n (with a max(0, ...) floor); otherwise it's min((int)lines.size(), n).

int end;
if (n < 0) {
    end = max(0, (int)lines.size() + n);
} else {
    end = min((int)lines.size(), n);
}


The full solution:
class Solution {
public:
    string head(vector<string> lines, int n) {
        int end;
        if (n < 0) {
            end = max(0, (int)lines.size() + n);
        } else {
            end = min((int)lines.size(), n);
        }
        string result;
        for (int i = 0; i < end; i++) {
            if (i > 0) result += "\n";
            result += lines[i];
        }
        return result;
    }
};

STEP 1 OF 9
    Ctrl + Enter to check

    Head V4 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