FastPrepFastPrep
Problem Brief

Implement tail -n

FULLTIMEOA

You are given a string fileContents that represents the contents of a text file. Lines are separated by newline characters .

Return the last n lines of the file in their original order. If the file has fewer than n lines, return the entire contents. If n = 0, return an empty string.

Function Description

Complete the function tailLastNLines in the editor below.

tailLastNLines has the following parameters:

  1. int n: the number of trailing lines to keep
  2. String fileContents: the full file contents

Returns

String[]: the last n lines in order, without adding extra formatting.

1Example 1

Input
n = 2, fileContents = "a\nb\nc\n"
Output
["b", "c"]
Explanation

The last two lines are b and c.

2Example 2

Input
n = 0, fileContents = "a\nb\nc"
Output
[]
Explanation

Keeping zero trailing lines returns an empty array.

Constraints

Limits and guarantees your solution can rely on.

  • 0 <= n
  • fileContents may be large, so an efficient solution should avoid unnecessary copies.
public String[] tailLastNLines(int n, String fileContents) {
    // write your code here
}
Input

n

2

fileContents

"a\nb\nc\n"

Output

["b", "c"]

Sign in to submit your solution.