Start learning free

LESSON 7 OF 69 · PROJECTS: COMMAND-LINE TOOLS

head -n in C#: Clamping n with Math.Min

Practice Read the full explanation

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

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

Example:

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

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

lines.GetRange(0, n) with n > lines.Count throws. So clamp n with Math.Min(n, lines.Count) first.

int 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 = Math.Min(n, lines.Count);
        return string.Join("\n", lines.GetRange(0, end));
    }
}

STEP 1 OF 2
    Ctrl + Enter to check

    C# · PROJECTS: COMMAND-LINE TOOLS

    Head V3 in C#, explained

    Problem overview

    This version of Head has the same signature as the previous one, Head(List<string> lines, int n), but n can now be larger than the number of lines. In that case the method returns all the lines: it doesn't crash and it doesn't pad. You can assume n >= 0. If n is 0, or there are no lines, the result is an empty string.

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

    Approach

    The previous version could call lines.GetRange(0, n) directly, because n was guaranteed to fit. Now it doesn't. GetRange throws when it is asked for more items than the list holds: with three lines, a count of 10 raises an ArgumentException.

    The fix is to clamp the count before using it: the number of lines to keep is the smaller of n and lines.Count. With 3 lines and n = 10 that is 3. With 3 lines and n = 2 it is 2. With an empty list it is 0, whatever n is, and a range of zero items is valid. After the clamp, the rest is the same as before: take the range and join it.

    Step by step

    1. Compute end as Math.Min(n, lines.Count). It never exceeds the list's size, so the next step can't fail for a large n.
    2. Return the joined range: string.Join("\n", lines.GetRange(0, end)). GetRange(0, end) returns the first end items, and Join places a newline between each two of them.

    The solution in C#

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

    C# details worth knowing:

    • Math.Min picks the smaller of two numbers. Both arguments here are int, so the result is an int, ready to be used as a count.
    • The very large n is safe. Math.Min only compares, so even int.MaxValue works: with three lines it gives "alpha\nbeta\ngamma".
    • GetRange needs a valid count. The second argument is a count, and it must be between 0 and the number of items from the start. The clamp guarantees the upper bound. The lower bound is the lesson's promise that n >= 0: this method leaves it unchecked.
    • end is a name for the count. It is also where the range stops, since the range starts at index 0.

    Complexity

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

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

    Edge cases and common mistakes

    • n larger than the list. Without the clamp, GetRange(0, n) throws an ArgumentException. With it, ["alpha", "beta", "gamma"] and n = 10 return all three lines.
    • n equal to the list size. Math.Min(3, 3) is 3, so all three lines come back.
    • n = 0. end is 0 and the result is "".
    • An empty list. end is 0 whatever n is, so Head(new List<string>(), 4) returns "".
    • Padding. The lesson says not to pad. A request for 10 lines from a 3-line list returns 3 lines, not 3 plus 7 empty ones.
    • Using Math.Max by mistake. It would pick the larger value and ask for too many lines.
    • A negative n. This version assumes n >= 0. Math.Min(-1, 3) is -1, and GetRange(0, -1) throws an ArgumentOutOfRangeException.

    Testing

    • ["alpha", "beta", "gamma"] with n = 10 gives "alpha\nbeta\ngamma".
    • The same list with n = 2 gives "alpha\nbeta".
    • The same list with n = 3 gives "alpha\nbeta\ngamma".
    • The same list with n = 0 gives "".
    • The same list with n = int.MaxValue gives "alpha\nbeta\ngamma".
    • An empty list with n = 4 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