FastPrepFastPrep
Problem Brief

Tail N Lines

FULLTIMEOA

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.

1Example 1

Input
lines = ["a","b","c","d","e"], n = 2
Output
["d","e"]
Explanation
The file has 5 lines. The last 2 lines are "d" and "e".

2Example 2

Input
lines = ["a","b","c"], n = 5
Output
["a","b","c"]
Explanation
n=5 exceeds the total number of lines (3), so all lines are returned.
public String[] tail(String[] lines, int n) {
  // write your code here
}
Input

lines

["a","b","c","d","e"]

n

2

Output

["d", "e"]

Sign in to submit your solution.