Start learning free

LESSON 8 OF 69 · PROJECTS: COMMAND-LINE TOOLS

head -n -K in C#: Dropping the Last K Lines

Practice Read the full explanation

Same signature as v2/v3, but now n may be negative. Real head -n -K prints all lines except the last K. So when n < 0 return all lines except the last |n|; when n ≥ 0 behave exactly like v3 (return the first n, capped at the input length). If |n| is at least the number of lines, nothing is left, so return the empty string.

Function signature:

public string Head(List<string> lines, int n)

Example (negative n):

Input: lines = ["a", "b", "c", "d", "e"], n = -2

Output: "a\nb\nc"

When printed:
a
b
c

C# doesn't auto-handle negative indices. Branch on the sign of n: when n < 0, the end index is lines.Count + n; otherwise it's Math.Min(n, lines.Count). Don't forget Math.Max(0, ...) for the negative branch in case |n| exceeds the list length.

int end;
if (n < 0) {
    end = Math.Max(0, lines.Count + n);
} else {
    end = Math.Min(n, lines.Count);
}
return string.Join("\n", lines.GetRange(0, end));


The full solution:
class Solution {
    public string Head(List<string> lines, int n) {
        int end;
        if (n < 0) {
            end = Math.Max(0, lines.Count + n);
        } else {
            end = Math.Min(n, lines.Count);
        }
        return string.Join("\n", lines.GetRange(0, end));
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    C# · PROJECTS: COMMAND-LINE TOOLS

    Head V4 in C#, explained

    Problem overview

    This version of Head(List<string> lines, int n) accepts a negative n, like the real head -n -K, which prints all lines except the last K. So for n < 0 the method returns all lines except the last |n|. For n >= 0 it behaves as in the previous version: the first n lines, capped at the length of the input. If |n| is at least the number of lines, nothing is left and the result is "".

    For ["a", "b", "c", "d", "e"] with n = -2 the result is "a\nb\nc": the last two lines are dropped.

    Approach

    Both cases can be described the same way: keep the first end lines, where end is a count. Only the calculation of end differs.

    • For n >= 0, end is Math.Min(n, lines.Count): the first n lines, but never more than exist.
    • For n < 0, you keep everything except the last |n| lines. With lines.Count lines, that is lines.Count - |n|, which is lines.Count + n because n is negative. Five lines and n = -2 keep 5 + (-2) = 3 lines.

    If |n| is as large as the list or larger, lines.Count + n is zero or below. A count can't be negative, so it is lifted to 0 with Math.Max(0, ...), and the result is empty.

    Once end is known, one line finishes the job for both signs: string.Join("\n", lines.GetRange(0, end)).

    Step by step

    1. Declare int end; without a value. C# lets you declare a variable and assign it later, as long as every path through the code assigns it before it is used. Both branches below do.
    2. Write an if/else that separates n < 0 from every other n.
    3. In the if: set end = Math.Max(0, lines.Count + n);. Math.Max returns the larger of two numbers, so a negative count becomes 0.
    4. In the else: set end = Math.Min(n, lines.Count);, the clamp from the previous version.
    5. Return the joined range: string.Join("\n", lines.GetRange(0, end)). Since both branches set end, this line works for either sign.

    The solution in C#

    class Solution {
        public string Head(List<string> lines, int n) {
            int end;
            if (n < 0) {
                end = Math.Max(0, lines.Count + n);
            } else {
                end = Math.Min(n, lines.Count);
            }
            return string.Join("\n", lines.GetRange(0, end));
        }
    }
    

    C# details worth knowing:

    • Negative indices don't exist. Some languages let you write lines[-2] or slice with a negative bound. In C#, an index or count below 0 throws, so a negative n has to be converted by hand into a position from the start: lines.Count + n.
    • Definite assignment. The compiler checks that end has a value on every path before the return. If the else were missing, the line using end would be a compile error ("use of unassigned local variable").
    • Math.Max and Math.Min are mirrors. Min keeps a count from going above the size of the list. Max keeps it from going below 0.
    • The arithmetic can't overflow in practice. lines.Count + n adds a non-negative count and a negative number, so the sum stays inside the range of int. It works even with n = int.MinValue, which gives "".

    Complexity

    Time: O(k + length of the kept lines), where k is the number of lines kept. GetRange copies k references and Join copies the kept text once.

    Space: O(k + length of the kept lines). The sub-list and the result string.

    Edge cases and common mistakes

    • |n| equal to the list size. Five lines and n = -5 give 5 + (-5) = 0 kept lines, so "".
    • |n| larger than the list. n = -9 on five lines would give -4 without the Math.Max, and GetRange(0, -4) would throw. With it the result is "".
    • n = -1. Only the last line is dropped: for ["alpha", "beta", "gamma", "delta", "epsilon"] the result is "alpha\nbeta\ngamma\ndelta".
    • n = 0. It takes the non-negative branch and keeps 0 lines, so the result is "". It does not mean "drop zero lines".
    • Large positive n. Math.Min caps it: n = 10 on five lines returns all five.
    • An empty list. Both n = -3 and n = 3 return "".
    • Subtracting instead of adding. Because n is already negative, lines.Count - n would add |n| and ask for more lines than exist.

    Testing

    • ["a", "b", "c", "d", "e"] with n = -2 gives "a\nb\nc".
    • The lines "alpha", "beta", "gamma", "delta", "epsilon" with n = -1 give "alpha\nbeta\ngamma\ndelta".
    • The same five lines with n = -4 give "alpha".
    • The same lines with n = -5 and with n = -9 give "".
    • The same lines with n = 3 give "alpha\nbeta\ngamma", and with n = 10 all five lines.
    • The same lines with n = 0 give "".
    • An empty list with n = -3 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