Skip to main content
Back to problems
#251
Medium Algorithms

Flatten 2d vector

Array Two Pointers Design Iterator
50.5% acceptance
Mar 31, 2026
739
418
Design an iterator to flatten a 2D vector. It should support the next and hasNext operations. Implement the Vector2D class: Vector2D(int[][] vec) initializes the object with the 2D vector vec. next() returns the next element from the 2D vector and moves the pointer one step forward. You may assume that all the calls to next are valid. hasNext() returns true if there are still some elements in the vector, and false otherwise.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
struct Vector2D {
  data: Vec<i32>,
  idx: usize,
}


/** 
 * `&self` means the method takes an immutable reference.
 * If you need a mutable reference, change it to `&mut self` instead.
 */
impl Vector2D {

  fn new(vec: Vec<Vec<i32>>) -> Self {
    Vector2D {
      data: vec.into_iter().flatten().collect(),
      idx: 0,
    }
  }
  
  fn next(&mut self) -> i32 {
    let val = self.data[self.idx];
    self.idx += 1;
    val
  }
  
  fn has_next(&self) -> bool {
    self.idx < self.data.len()
  }
}