Problem · Array

Stateful Paginated Fetch N

Learn this problem
MediumLyft logoLyftFULLTIMEPHONE SCREEN

Problem statement

Simulate repeated calls to a stateful fetch_n reader over an immutable token-paginated source.

The source is described by parallel arrays:

  • pageTokens[i] identifies one page.
  • pageItems[i] is that page's ordered item list.
  • nextTokens[i] is the next page token, or the empty string when the source ends.

startToken is the first token, or the empty string for an already exhausted source. Tokens are unique, every non-empty next token names a supplied page, and following tokens from startToken reaches the empty string without revisiting a page. A page may contain no items.

Process every positive value requests[j] as one call on the same reader. That call returns up to requests[j] remaining items in source order. Buffer fetched items that the call does not return, skip empty pages, and continue from the preserved buffer and token on the next call. Calls after exhaustion return an empty array.

Return one item array per request, in request order.

Reliability follow-up

Judged page fetches succeed exactly once. Be prepared to explain bounded retries, idempotent token fetches, timeout handling, and why a failed fetch must not advance committed reader state.

Function

fetchBatches(startToken: String, pageTokens: String[], pageItems: String[][], nextTokens: String[], requests: int[]) → String[][]

Examples

Example 1

startToken = "p1"pageTokens = ["p1","p2","p3"]pageItems = [["A","B","C"],["D"],["E","F"]]nextTokens = ["p2","p3",""]requests = [2,3,4]return = [["A","B"],["C","D","E"],["F"]]

The first call buffers C. The second call consumes that buffer and continues through pages p2 and p3. Only F remains for the final call.

Example 2

startToken = "a"pageTokens = ["a","b","c"]pageItems = [[],["x","y"],[]]nextTokens = ["b","c",""]requests = [1,2,1]return = [["x"],["y"],[]]

The reader skips the empty first page, buffers y after returning x, and eventually skips the empty terminal page before reporting exhaustion.

Constraints

  • pageTokens.length, pageItems.length, and nextTokens.length are equal.
  • Page tokens are unique, and every non-empty next token names a supplied page.
  • The chain from startToken is acyclic and ends at the empty token.
  • Every value in requests is positive.

More Lyft problems

drafts saved locally
public String[][] fetchBatches(String startToken, String[] pageTokens, String[][] pageItems, String[] nextTokens, int[] requests) {
    // Write your code here.
}
startToken"p1"
pageTokens["p1","p2","p3"]
pageItems[["A","B","C"],["D"],["E","F"]]
nextTokens["p2","p3",""]
requests[2,3,4]
expected[["A", "B", "C", "D", "E", "F"]]
checking account