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));
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
