Extend your head command to take an integer n and return the first n lines of lines, joined by newline characters (\n). For this version you may assume 0 ≤ n ≤ lines.size(). If n is 0 the result is the empty string.
Function signature:
public String head(List<String> lines, int n)
Example:
Input: lines = ["alpha", "beta", "gamma", "delta", "epsilon"], n = 3 Output: "alpha\nbeta\ngamma" When printed: alpha beta gamma
Use
List.subList(0, n) for the first n elements, then String.join("\n", ...). Since the problem guarantees n ≤ lines.size(), no min needed.
Combine the two calls into one:
return String.join("\n", lines.subList(0, n));
The full solution:
class Solution {
public String head(List<String> lines, int n) {
return String.join("\n", lines.subList(0, n));
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
