Start learning free

LESSON 7 OF 70 · PROJECTS: COMMAND-LINE TOOLS

head in TypeScript: When n Is Larger Than the Input

Practice Read the full explanation

Same signature as v2, but now n may be larger than the number of lines. If n > lines.length 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:

head(lines: string[], n: number): string

Example:

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

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

TypeScript's slice already handles the over-cap case. lines.slice(0, n) with n bigger than lines.length just returns all elements — no extra logic needed.

The full solution is identical to v2:
class Solution {
    head(lines: string[], n: number): string {
        return lines.slice(0, n).join("\n");
    }
}

STEP 1 OF 1
    Ctrl + Enter to check

    TYPESCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Head V3 in TypeScript, explained

    Problem overview

    Version 3 of head keeps the signature head(lines: string[], n: number): string but lifts the earlier guarantee: n may now be larger than the number of lines. In that case the function returns all the lines. It must not crash and must not pad the result. The input still has n >= 0, and when n is 0 or there are no lines the result is "".

    For ["alpha", "beta", "gamma"] and n = 10, the result is "alpha\nbeta\ngamma".

    Approach: let slice do the capping

    In many languages this version needs an explicit cap, such as min(n, lines.length), because reading past the end of an array is an error. In TypeScript the code from the previous version already works. slice(start, end) never reads past the end: if end is larger than the array's length, it simply stops at the last item.

    So the lesson's point is why the same line still works, not what to add. For five lines and n = 8, slice(0, 8) returns the items at indexes 0 to 4, all five. join("\n") then glues them with newlines and adds nothing for the missing three.

    A loop that always runs n times behaves differently. Reading lines[i] past the end of an array gives undefined instead of an error, and pushing those values and joining them leaves empty pieces. For the three lines ["alpha", "beta", "gamma"] and n = 5, such a loop returns "alpha\nbeta\ngamma\n\n", with two stray newlines at the end. That is the padding the task forbids.

    Step by step

    1. Return lines.slice(0, n).join("\n"). It is identical to the version before. Check it against a large n and you'll see the slice stops at the end of the array.

    The solution in TypeScript

    class Solution {
        head(lines: string[], n: number): string {
            return lines.slice(0, n).join("\n");
        }
    }
    
    • Indexing is different. lines[7] on a five-item array gives undefined rather than an error, and joining such a value would produce an empty piece. slice doesn't index past the end at all; it returns only the items that exist, so the result has no empty pieces.
    • Because the result is a new array, it can be shorter than n. Nothing is added to reach n.
    • If you wanted to be explicit, lines.slice(0, Math.min(n, lines.length)) returns the same result. The extra Math.min does nothing that slice doesn't already do.

    Complexity

    Time and space are proportional to the number of lines returned, which is the smaller of n and lines.length. A huge n costs nothing extra, since slice only copies items that exist.

    Edge cases and common mistakes

    • n larger than the length. The result is every line, joined: ["alpha", "beta", "gamma"] with n = 10 gives "alpha\nbeta\ngamma".
    • Empty list with a positive n. head([], 4) gives "", and no padding is added.
    • n = 0. The result is "".
    • Padding by mistake. A loop that reads lines[i] for every i below n adds an empty piece for each missing line, as shown above. Slicing avoids the problem.
    • Exact fit. n equal to the length returns all lines, the same as any larger value.

    Testing

    InputResult
    ["alpha", "beta", "gamma"], n = 10"alpha\nbeta\ngamma"
    ["alpha", "beta", "gamma", "delta", "epsilon"], n = 8"alpha\nbeta\ngamma\ndelta\nepsilon"
    [], n = 4""
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free