Problem · Queue
Tail N Lines
Learn this problemProblem statement
Implement the Unix tail -n command: given an array of strings representing the lines of a file and an integer n, return the last n lines.
If n is greater than or equal to the total number of lines, return all lines.
Follow-up: Optimize for memory and time complexity. A rolling window (circular buffer / deque of size n) achieves O(n) space and O(L) time where L is the total number of lines — avoiding storing the entire file.
Function
tail(lines: String[], n: int) → String[]Examples
Example 1
lines = ["a","b","c","d","e"]n = 2return = ["d","e"]The file has 5 lines. The last 2 lines are "d" and "e".
Example 2
lines = ["a","b","c"]n = 5return = ["a","b","c"]n=5 exceeds the total number of lines (3), so all lines are returned.