Start learning free

LESSON 6 OF 69 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool head v2 in C++: First n Lines with a Loop Bound

Practice Read the full explanation

Extend your head command to take an integer n and return the first n lines of lines, joined by newline characters (\n). For this version you may assume 0 ≤ n ≤ lines.size(). If n is 0 the result is the empty string.

Function signature:

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

Example:

Input: lines = ["alpha", "beta", "gamma", "delta", "epsilon"], n = 3

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

Loop from 0 to n - 1, accumulating each line. Insert a "\n" before every line except the first.

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


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

STEP 1 OF 5
    Ctrl + Enter to check

    C++ · PROJECTS: COMMAND-LINE TOOLS

    Head V2 in C++, explained

    Problem overview

    The first version of head always kept 10 lines. This version takes the count as a parameter: head(vector<string> lines, int n) returns the first n lines joined by newline characters, with no newline after the last. For this lesson, n is always between 0 and lines.size(), so it never asks for more lines than exist. When n is 0, the result is the empty string.

    For ["alpha", "beta", "gamma", "delta", "epsilon"] and n = 3, the result is "alpha\nbeta\ngamma". With n = 0 it is "", and with n equal to the number of lines every line is kept.

    Approach: let n bound the loop

    The change from the previous version is small: the fixed 10 becomes the parameter n. The loop runs while i < n, so i takes the values 0 to n - 1, which are the positions of the lines to keep. The joining rule is unchanged: put a newline before every line except the first, so newlines only appear between lines.

    Because the lesson promises n <= lines.size(), there is nothing to clamp, and the loop can use n directly. That promise is the whole reason this version is so short. Without it, lines[i] could ask for a position that doesn't exist. This version relies on the guarantee, and the next one builds on it.

    Step by step

    1. Create an empty string named result. It grows by one line per pass.
    2. Loop with i from 0 while i < n. The counter visits exactly the positions of the first n lines.
    3. Add the separator. When i > 0, append "\n". The first line has nothing before it to separate from.
    4. Append lines[i] to result.
    5. Return result after the loop. For n = 0, the loop never runs and result is still empty.

    The solution in C++

    class Solution {
    public:
        string head(vector<string> lines, int n) {
            string result;
            for (int i = 0; i < n; i++) {
                if (i > 0) result += "\n";
                result += lines[i];
            }
            return result;
        }
    };
    

    The C++ details worth a closer look:

    • No bounds check on []. lines[i] with a position past the end is undefined behaviour: the program may crash, print garbage or seem to work. The code is correct only because n never exceeds the number of lines. The at method, lines.at(i), checks the position and throws std::out_of_range instead, which is easier to debug.
    • A signed loop counter. i and n are both int, so i < n compares two signed numbers. The size() comparison from earlier versions is not needed here.
    • The condition i > 0. It is false only on the first pass. That is the compact way to write "all but the first".

    Complexity

    Time: O(n + k) where k is the total length of the kept lines. The loop runs n times, and each pass appends one line, which costs time proportional to its length. Because the vector is passed by value, the call also copies every line of the input.

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

    Edge cases and common mistakes

    • n = 0. The loop is skipped and the result is "", even when there are lines.
    • n = 1. The result is the first line alone, with no newline: ["alpha", "beta"] with n = 1 gives "alpha".
    • n equal to the size. Every line is kept: ["alpha", "beta"] with n = 2 gives "alpha\nbeta".
    • Off by one. A loop condition of i <= n returns n + 1 lines, and reads past the end when n equals the size.
    • A trailing newline. The separator goes before a line, not after it, so the result never ends with \n.
    • Calling it with a larger n. This version does not handle n above the number of lines: the loop would read positions that do not exist. The lesson excludes that case.

    Testing

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

    • ["alpha", "beta", "gamma", "delta", "epsilon"] with n = 3 gives "alpha\nbeta\ngamma".
    • ["alpha", "beta"] with n = 0 gives "".
    • ["alpha", "beta"] with n = 1 gives "alpha".
    • ["alpha", "beta"] with n = 2 gives "alpha\nbeta".
    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