Practice/Google/Leetcode 251. Flatten 2D Vector
CodingMust
Design and implement an iterator class that flattens a two-dimensional vector of integers. Your iterator should support two operations:
next(): Returns the next integer in the flattened sequencehasNext(): Returns true if there are more elements to iterate over, false otherwiseThe iterator should traverse the 2D vector in row-major order (left to right, top to bottom). Some of the inner vectors may be empty, and your implementation should handle this gracefully without errors.
Vector2D class that takes a 2D vector as input in its constructornext() method should return the next integer in the sequencehasNext() method should return a boolean indicating if more elements existnext() will only be called when hasNext() returns trueExample 1:
Input: vec = [[1, 2], [3], [4, 5, 6]] Operations: hasNext(), next(), next(), hasNext(), next(), next(), next(), hasNext() Output: [true, 1, 2, true, 3, 4, 5, false] Explanation: The iterator flattens the 2D vector into [1, 2, 3, 4, 5, 6] and iterates through it sequentially.
Example 2:
Input: vec = [[], [7], [], [8, 9], []] Operations: next(), next(), next(), hasNext() Output: [7, 8, 9, false] Explanation: Empty vectors are automatically skipped. The effective sequence is [7, 8, 9].
Example 3:
Input: vec = [[]] Operations: hasNext() Output: [false] Explanation: When all inner vectors are empty, hasNext immediately returns false.