Start learning free

LESSON 8 OF 69 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool head v4 in C++: Negative n Drops the Tail with max and min

Practice Read the full explanation

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

    C++ · PROJECTS: COMMAND-LINE TOOLS

    Head V4 in C++, explained

    Problem overview

    With a negative n, the real head -n -K prints every line except the last K. This version of head(vector<string> lines, int n) supports that. For n < 0 it returns all lines except the last |n|. For n >= 0 it behaves as in the previous version: the first n lines, capped at the input length. If |n| is at least the number of lines, nothing is left, and the result is the empty string. Lines are joined by newlines, with none after the last.

    For ["a", "b", "c", "d", "e"] and n = -2, the result is "a\nb\nc": the last two lines, d and e, are dropped. With n = -1 the result is "a\nb\nc\nd", and with n = -5 or n = -9 it is "".

    Approach: one end position for both signs of n

    Both cases keep a prefix of the vector: the lines from position 0 up to, but not including, some position end. Only the way end is computed differs.

    • For n >= 0, end is the smaller of n and the number of lines, as before.
    • For n < 0, end is the number of lines plus n, which walks back from the end by |n| positions. With 5 lines and n = -2 that gives 3, so the first three lines are kept. If |n| is as large as the list, the sum would be zero or below, so it is raised to 0 with max.

    Once end is right, the loop is the one from the earlier versions, with a newline before every line except the first. Computing end separately keeps the loop free of special cases.

    Step by step

    1. Declare int end without a value. C++ lets you declare a variable first and assign it later, and the next steps assign it in both branches.
    2. Write the if/else that separates n < 0 from every other n.
    3. Negative branch. Set end to max(0, (int)lines.size() + n). The cast to int matters: adding a negative n to an unsigned size wraps around instead of subtracting.
    4. Non-negative branch. Set end to min((int)lines.size(), n), the same cap as in the previous version.
    5. Create an empty string named result.
    6. Loop with i from 0 while i < end. end is already right for either sign of n.
    7. Add the separator. When i > 0, append "\n".
    8. Append lines[i] to result.
    9. Return result after the loop.

    The solution in C++

    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;
        }
    };
    

    The C++ details worth a closer look:

    • Unsigned arithmetic wraps. With 5 lines and n = -9, the expression lines.size() + n without a cast converts n to an unsigned number first, and the result is 18446744073709551612, a huge value. With the cast, (int)lines.size() + n is -4, and max(0, -4) brings it back to 0.
    • The cast also keeps max compiling. max(0, lines.size() + n) mixes an int and an unsigned type, and the compiler reports that no matching max exists. Casting makes both arguments int.
    • Same rule for min. min and max need two arguments of one type, which is why both branches cast the size.
    • Declaring before assigning. int end; has no value until one of the branches runs. Both branches assign it, so it is always set before the loop reads it. A branch that forgot to assign it would leave the loop reading an unspecified value.
    • The same pitfall elsewhere. On an empty vector, lines.size() - 1 is 18446744073709551615 while (int)lines.size() - 1 is -1. Converting the size to int before doing arithmetic with signed values is the safe habit.

    Complexity

    Time: O(m + k) where m is the number of kept lines and k their total length. Computing end is constant time and the loop runs end times. The vector is passed by value, so the call also copies the input.

    Space: O(k) for the result, plus the copy of the input.

    Edge cases and common mistakes

    • |n| equals the number of lines. ["a", "b", "c", "d", "e"] with n = -5 gives "": end is exactly 0.
    • |n| larger than the number of lines. With n = -9 the sum is -4, and max raises it to 0. The result is "" and not an error.
    • n = -1. Only the last line is dropped: "a\nb\nc\nd".
    • n = 0. It takes the non-negative branch, end is 0, and the result is "". Zero keeps no lines, which is not the same as "drop zero lines".
    • Large positive n. With n = 9 and 5 lines, min caps end at 5, and every line is kept.
    • Empty vector. The result is "" for any n: for n = -3 the sum is -3 and max makes it 0.
    • Skipping the max. A negative end would make the loop condition false immediately, so the result would still be empty. But in the middle of other code, such an end would be a trap, which is why the lesson clamps it.

    Testing

    Each result is the function's output, with newlines written as \n. The input is ["a", "b", "c", "d", "e"] unless stated:

    • n = -2 gives "a\nb\nc".
    • n = -1 gives "a\nb\nc\nd".
    • n = -5 gives "".
    • n = -9 gives "".
    • n = 0 gives "".
    • n = 3 gives "a\nb\nc".
    • n = 9 gives "a\nb\nc\nd\ne".
    • An empty vector with n = -3 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