Problem · Queue

Tail N Lines

EasyConfluentFULLTIMEOA

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.

Examples
01 · Example 1
lines = ["a","b","c","d","e"]
n = 2
return = ["d","e"]
The file has 5 lines. The last 2 lines are "d" and "e".
02 · Example 2
lines = ["a","b","c"]
n = 5
return = ["a","b","c"]
n=5 exceeds the total number of lines (3), so all lines are returned.
More Confluent problems
drafts saved locally
public String[] tail(String[] lines, int n) {
  // write your code here
}
lines["a","b","c","d","e"]
n2
expected["d", "e"]
sign in to submit