Start learning free

LESSON 5 OF 69 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool head v1 in C++: First 10 Lines with min

Practice Read the full explanation

Build a tiny version of the Unix head command. Given a list of lines, return the first 10 lines joined by newline characters (\n). If the input has fewer than 10 lines, return all of them. If there are no lines at all, return the empty string.

Function signature:

string head(vector<string> lines)

Example:

Input: lines = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"]

Output: "a\nb\nc\nd\ne\nf\ng\nh\ni\nj"

When printed:
a
b
c
d
e
f
g
h
i
j

Compute the end index: min((int)lines.size(), 10). Loop from 0 to end - 1, accumulating each line into a single string with "\n" between them.

Use the standard "skip the first separator" trick: only prepend "\n" when i > 0.
int end = min((int)lines.size(), 10);
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 end = min((int)lines.size(), 10);
        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 V1 in C++, explained

    Problem overview

    The Unix head command prints the beginning of its input, ten lines by default. The function head takes a vector<string> of lines and returns the first 10 of them as one string, joined by newline characters with none after the last. With fewer than 10 lines it returns all of them, and with no lines it returns the empty string.

    For the 13 lines "a" to "m", the result is "a\nb\nc\nd\ne\nf\ng\nh\ni\nj": the letters k, l and m are dropped. With exactly 10 lines the result is the same string, and with the three lines "a", "b" and "c" it is "a\nb\nc".

    Approach: decide how many lines to keep, then join them

    The work splits into two small parts. First, find how many lines to keep: 10, or fewer if the input is shorter. Second, join exactly that many lines with newlines between them, using the same loop as the cat tool: a separator before every line except the first.

    The count is where the care goes. A loop that always runs to 10 would read past the end of a shorter vector, and reading an element that doesn't exist is undefined behaviour in C++: it may crash or silently return garbage. So the loop bound is the smaller of 10 and the number of lines, which min computes.

    Step by step

    1. Create int end as the smaller of the number of lines and 10: min((int)lines.size(), 10). It is the number of lines to keep.
    2. Create an empty string named result. It grows by one line per pass.
    3. Loop over the kept positions with i from 0 while i < end, so i goes through 0 up to end - 1.
    4. Add the separator. When i > 0, append "\n". That puts one newline between each pair of lines and none after the last.
    5. Append lines[i] to result.
    6. Return result after the loop. For an empty input the loop never ran, so it is still the empty string.

    The solution in C++

    class Solution {
    public:
        string head(vector<string> lines) {
            int end = min((int)lines.size(), 10);
            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:

    • Why the cast. lines.size() returns an unsigned type, and 10 is an int. min needs both arguments to have the same type, so min(lines.size(), 10) does not compile. Casting the size with (int) makes both arguments int.
    • min lives in <algorithm>. It is the standard library's std::min. The lesson's file already has the headers and the using namespace std; line, so the plain name works.
    • The variable is called end. It is an ordinary local name here. Unrelated to it, containers have a member function end(), and the two don't clash.
    • Vectors don't check indexes. lines[i] does no bounds check, which is why the loop bound has to be right. Computing end first is what keeps every i a valid position.

    Complexity

    Time: O(k) where k is the total length of the kept lines, which are at most 10. The loop runs at most 10 times, and each pass appends one line. Passing the vector by value copies all of its lines first, which makes the call O(n) in the size of the whole input.

    Space: O(k) for the result, plus the copy of the input that the by-value parameter makes.

    Edge cases and common mistakes

    • Fewer than 10 lines. end is the vector's size, so every line is kept.
    • Exactly 10 lines. Nothing is dropped, and the result is all ten.
    • Empty vector. end is 0, the loop does nothing, and the result is "".
    • Looping to 10 unconditionally. With 3 lines this reads positions 3 to 9, which do not exist.
    • A trailing newline. Appending "\n" after every line, instead of before every line but the first, would leave an extra newline at the end.
    • Using lines.size() in min without a cast. The compiler rejects the mixed types.

    Testing

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

    • The 13 lines "a" to "m" give "a\nb\nc\nd\ne\nf\ng\nh\ni\nj".
    • The first 10 of those lines give the same string.
    • The first 3 of those lines give "a\nb\nc".
    • [] 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