Replicate the functionality of the Unix tail command. Given a list of strings lines representing the lines of a large file and an integer n, return the last n lines of the file.
The solution should be efficient and simulate reading a file without loading the entire content into memory at once. Use a buffer-based approach that only retains the most recent n lines at any point during processing.
Function Signature
def tail(lines: list[str], n: int) -> list[str]:
Rules
-
Treat
lines
as a file that is read once, from the first line to the last.
-
If
n
is greater than or equal to the total number of lines, return all lines.
-
If
n
is 0, return an empty list.
-
The returned lines must be in the same order as in the file.
Constraints
-
1 <= len(lines) <= 10^5
-
0 <= n <= 10^5
-
Each line is a non-empty string of length at most 1000.
Examples
Input: lines = ["Line 1","Line 2","Line 3","Line 4","Line 5","Line 6","Line 7","Line 8","Line 9","Line 10"], n = 3
Output: ["Line 8","Line 9","Line 10"]
The file has 10 lines and the last 3 of them are lines 8, 9 and 10, returned in file order.
Input: lines = ["alpha","beta","gamma"], n = 5
Output: ["alpha","beta","gamma"]
n is larger than the 3 lines in the file, so every line is returned.
Input: lines = ["alpha","beta","gamma"], n = 0
Output: []
Asking for zero lines returns an empty list.