Start learning free

LESSON 599 OF 667 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: head v1 — First 10 Lines

Practice

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