Start learning free

LESSON 7 OF 69 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool head v3 in C++: Cap n at lines.size() with min

Practice Read the full explanation

Same signature as v2, but now n may be larger than the number of lines. If n > lines.size() simply return all the lines (don't crash, don't pad). For this version assume n ≥ 0. If n is 0, or there are no lines, the result is the empty string.

Function signature:

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

Example:

Input: lines = ["alpha", "beta", "gamma"], n = 10

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

Indexing lines[i] past the end is undefined behavior in C++, so clamp n with min((int)lines.size(), n) before the loop.

int end = min((int)lines.size(), n);
for (int i = 0; i < end; i++) {
    if (i > 0) result += "\n";
    result += lines[i];
}


The full solution:
class Solution {
public:
    string head(vector<string> lines, int n) {
        int 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 6
    Ctrl + Enter to check

    C++ · PROJECTS: COMMAND-LINE TOOLS

    Head V3 in C++, explained

    Problem overview

    The signature stays head(vector<string> lines, int n), but n may now be larger than the number of lines. In that case the function returns all the lines: no crash and no padding. As before, the lines are joined by newline characters with none after the last. n is never negative here. When n is 0, or when there are no lines, the result is the empty string.

    For ["alpha", "beta", "gamma"] and n = 10, the result is "alpha\nbeta\ngamma", which is the same as for n = 3. For an empty vector and n = 5 the result is "".

    Approach: clamp n before the loop

    The previous version looped up to n and relied on n never exceeding the number of lines. With a big n, the loop would read positions that don't exist, which is undefined behaviour in C++.

    The fix is to compute how many lines can really be kept: the smaller of n and the number of lines. That number, end, bounds the loop instead of n. The rest of the function is unchanged. It is the same loop with a newline before every line except the first.

    This is also the same clamp that the first version used with the fixed number 10. Here the limit is the parameter n instead.

    Step by step

    1. Create int end as the smaller of the number of lines and n: min((int)lines.size(), n). A large n can no longer take the loop past the vector.
    2. Create an empty string named result.
    3. Loop with i from 0 while i < end. The bound is end, not n, because n may be bigger than the vector.
    4. Add the separator. When i > 0, append "\n".
    5. Append lines[i] to result.
    6. Return result after the loop. It holds every kept line.

    The solution in C++

    class Solution {
    public:
        string head(vector<string> lines, int n) {
            int 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:

    • The cast is required. min takes two arguments of the same type. lines.size() is unsigned and n is an int, so min(lines.size(), n) fails to compile. (int)lines.size() makes both int.
    • The cast is safe here. A vector of lines for this lesson is far smaller than the largest int, so the conversion doesn't lose anything.
    • Why not compare n with the size directly? Mixing int and unsigned in a comparison converts the int to unsigned. A negative number would turn into a huge value. This lesson never passes a negative n, but converting the size to int instead is the habit that keeps negative values meaningful.
    • Clamping instead of branching. Without min, you would write an if for the case n > lines.size(). One expression handles both cases and leaves the loop untouched.

    Complexity

    Time: O(m + k) where m is the number of kept lines and k their total length. The loop runs end times and each pass appends one line. The vector is passed by value, so the call also copies the whole input.

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

    Edge cases and common mistakes

    • n larger than the size. ["alpha", "beta", "gamma"] with n = 10 returns all three lines, not extra empty ones.
    • n equal to the size. The same result, because the minimum of two equal numbers is that number.
    • Empty vector. end is 0 for every n, so [] with n = 5 gives "".
    • n = 0. end is 0 and the result is "".
    • Looping to n. This is the trap of the previous version: with n = 10 and 3 lines, the positions 3 to 9 don't exist, and reading them is undefined behaviour.
    • Padding. Nothing is added when n is bigger than the input. The output never has more lines than the input.
    • Negative n. This version is written for n >= 0. With a negative n, min gives end a negative value and the loop does nothing, so the result is "".

    Testing

    Each result is the function's output, with newlines written as \n:

    • ["alpha", "beta", "gamma"] with n = 10 gives "alpha\nbeta\ngamma".
    • ["alpha", "beta", "gamma"] with n = 3 gives "alpha\nbeta\ngamma".
    • [] with n = 5 gives "".
    • ["a", "b"] with n = 0 gives "".
    • ["a", "b"] with n = -1 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