v9.1.1
Menu

Flatten 2D Vector

easyPRONested Structures & IteratorsLinkedIn DSA

Implement an iterator class Vector2D that flattens a 2D vector (a list of rows, each a list of integers; rows may be empty). Its constructor takes the 2D vector vec. Support two operations:

  • next(): return the next value, reading rows in order and each row left to right.
  • has_next(): return True if at least one value has not yet been returned by next(), else False.

Input: the 2D vector, then a sequence of operations separated by semicolons. Output: the result of every operation (next() values and has_next() booleans), one per line.

Example

Input
[[1,2],[3],[4]]
next;next;next;has_next;next;has_next
Output
1
2
3
True
4
False
Reasoning
  • The input [[1,2],[3],[4]] has three rows of lengths 22, 11 and 11, so it holds 2+1+1=42+1+1 = 4 values. Read row by row, left to right, they form the single sequence 1,2,3,41, 2, 3, 4; the row boundaries never show up in the output.
  • The first three calls to next return the 1st, 2nd and 3rd values of that sequence: 1 and 2 from row 0, then 3 from row 1. After them, 33 of the 44 values have been consumed.
  • has_next asks whether any value is still unconsumed: 3<43 < 4, so it prints True. It does not consume anything, so the next next still gets 4.
  • Now 44 of 44 values are consumed, so the final has_next prints False.
  • Notice that a row can be empty: if the first row is empty and the second holds just 11, the first next call returns 1 (the empty row contributes nothing to the sequence) and has_next is then False.

Constraints

  • 0 <= rows <= 100
  • 0 <= cols <= 100

Learn this in

More from LinkedIn DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.