FastPrepFlatten 2D Vector

Flatten 2D Vector

Airbnb logoAirbnb● MediumINTERNPHONE SCREEN

Updated

Problem statement

Design an iterator over a 2D array vec whose rows can have different lengths, including length zero. The iterator returns the values row by row, and from left to right inside each row. It supports two calls:

  • next returns the next value and moves past it.
  • hasNext returns whether another value is left. It does not move the iterator, so calling it many times in a row gives the same answer.

The calls are given in order in operations, and the iterator starts before the first value of vec. Return one string for each call: the value as a decimal number for next, and "true" or "false" for hasNext.

Function

runVector2D(vec: int[][], operations: String[]) → String[]

Examples

Example 1

vec = [[1,2],[3],[4]]operations = ["next","next","next","hasNext","hasNext","next","hasNext"]return = ["1","2","3","true","true","4","false"]

The values come out row by row: 1 and 2 from the first row, then 3, then 4. Calling hasNext twice in a row does not use up 4. After 4, nothing is left, so the last hasNext returns "false".

Example 2

vec = [[],[5],[],[],[6,7],[]]operations = ["hasNext","next","next","hasNext","next","hasNext"]return = ["true","5","6","true","7","false"]

Empty rows hold no values, so they are skipped. The first next returns 5. The second skips the two empty rows after it and returns 6. After 7, only an empty row is left, so hasNext returns "false".

Example 3

vec = [[],[]]operations = ["hasNext","hasNext"]return = ["false","false"]

Both rows are empty, so there is never a next value.

Constraints

  • 0 <= vec.length <= 200
  • 0 <= vec[i].length <= 500
  • -500 <= vec[i][j] <= 500
  • 1 <= operations.length <= 3000
  • Each operations[i] is "next" or "hasNext".
  • next is called only when another value is left.

More Airbnb Phone Screen questions

Similar questions at other companies

Interview reports that mention this question

Airbnb interview experiences

All Airbnb interview questionsSee Airbnb hiring insights
Saved
class Solution {
    public String[] runVector2D(int[][] vec, String[] operations) {
      // Write your code here.
    }
}
Checking account…