FastPrepLast X Lines of a File

Last X Lines of a File

Google logoGoogle● EasyNEW GRADPHONE SCREEN
Learn

Problem statement

Given file contents text and a nonnegative integer x, return the last at most x lines.

The backslash-n newline character separates lines. Consecutive newlines create empty lines. A final newline terminates the preceding line and does not create an additional trailing empty line. Empty text contains zero lines. Preserve each returned line exactly.

Function

lastFileLines(text: String, x: int) → String[]

Examples

Example 1

text = "a\nb\nc"x = 2return = ["b","c"]

The final two of the three lines are b and c.

Example 2

text = "a\nb\n"x = 2return = ["a","b"]

The terminal newline closes line b without adding another line.

Example 3

text = ""x = 5return = []

An empty file has no lines.

Constraints

  • 0 <= text.length <= 1000000.
  • 0 <= x <= 1000000.
  • text may contain any characters except carriage return.

More Google problems

See Google hiring insights
public String[] lastFileLines(String text, int x) {
    // Write your code here.
}
text"a\nb\nc"
x2
expected["b", "c"]
Checking account…