15% off all plans & roadmaps Use code
See plansFlatten 2D Vector
- LeetCode 251
- Medium
- Design Patterns
- Design (General/Specific)
Updated
TL;DR: Flatten the nested list with a row cursor and a column cursor. Read one cell at a time, and move into the next row when a row ends. The pointer walk runs in O(N + R) time. The naive version that rescans rows for every position runs in O(N * R) time.
Problem
You are given a 2D vector vec, a list of lists of integers. Design an iterator that flattens it and visits every element in row-major order, meaning left to right and then top to bottom.
Implement the Vector2D class:
Vector2D(int[][] vec)creates the object with the 2D vectorvec.int next()returns the next element of the flattened vector.boolean hasNext()returns true if elements remain, and false otherwise.
Your implementation must support calling next() and hasNext() many times, in any order.
Return the value each operation produces, as described above.
Example 1
Input: vec2d = [[1, 2], [3], [4, 5, 6]] Output: [1, 2, 3, 4, 5, 6]
Constraints that matter
- Rows can have different lengths and can be empty, so no single formula from a flat index can locate a cell. You must track a row and a column, and skip empty rows.
- The output holds all N elements, so O(N) work for the output is unavoidable. Any solution that is linear in N and R is optimal for this problem.
- Re-scanning from row 0 for every output element costs O(N * R), which is too slow when both N and R are large. The cursor must only move forward.
Hints
Hint 1
The flatten function takes the nested list and returns every element in row-major order.
Hint 2
The naive plan treats each output position on its own.
Solution
Intuition
The flatten function takes the nested list and returns every element in row-major order. The Vector2D design asks for the same order, one value per call. Both need one traversal, so the best solution is a pointer walk. This is the iterator pattern: a cursor that remembers its place between reads.
Picture reading a book with chapters of uneven length, some of them blank. Your bookmark holds the chapter and the line, and you turn to the next chapter only when the current one ends, skipping blank ones at once.
The problem forces a jagged grid. Rows have different lengths, and some rows are empty. A single formula from a flat index cannot find a cell in a grid like that. You need two numbers, the row and the column, and a rule for moving from one to the next.
The rule is short. Read the cell under the cursor, then move the column right. When the column leaves its row, move to the next row and reset the column to 0. An empty row fails the column check at once, so the same rule skips it.
The cursor never moves backward, so each cell is read exactly once. That property keeps the walk linear even when many rows are empty.
Worked example
Input: vec2d = [[1, 2], [3], [4, 5, 6]] Output: [1, 2, 3, 4, 5, 6] Explanation: Row 0 contributes 1 and 2. Row 1 contributes 3. Row 2 contributes 4, 5 and 6. Reading each row left to right, from the top row to the bottom row, gives the output in order.
Approach 1: Brute force: scan rows for each position
The naive plan treats each output position on its own. For position k, subtract row lengths from k until the rest fits inside one row, then read that cell. Repeat this for every k from 0 to N - 1, where N is the total count.
Nothing carries over between positions. Every lookup starts again at row 0, so the work for position k + 1 repeats most of the work done for position k.
Steps
- Sum the row lengths to get N, the total element count.
- For each k from 0 to N - 1, set remaining to k.
- Walk the rows from the top, starting with row 0.
- If remaining is less than the current row's length, append row[remaining] and stop walking.
- Otherwise subtract the row's length from remaining and move to the next row.
- Return the result after every position has been filled.
Dry run
Trace the example with N = 6. Each k starts at the top row.
- k = 0: row 0 has length 2, and 0 < 2, so output 1.
- k = 1: 1 < 2, so output 2.
- k = 2: 2 is not less than 2, so remaining becomes 0. Row 1 has length 1, and 0 < 1, so output 3.
- k = 3: remaining is 3, then 1 after row 0, then 0 after row 1. Row 2 has length 3, and 0 < 3, so output 4.
- k = 4: remaining is 4, then 2, then 1. Row 2 gives index 1, so output 5.
- k = 5: remaining is 5, then 3, then 2. Row 2 gives index 2, so output 6.
The result is [1, 2, 3, 4, 5, 6].
Complexity
| Time | O(N * R) |
|---|---|
| Space | O(1) extra, O(N) for the output |
Let N be the total element count and R the number of rows. The outer loop runs N times, once for each output position. Each inner walk visits at most R rows before it finds the right one, so one lookup costs O(R). The total is O(N * R), plus one O(R) pass to sum the row lengths.
PythonTested in our runner
from typing import List, Optional
class Solution:
def flatten2DVector(self, vec2d: List[List[int]]) -> List[int]:
total = sum(len(row) for row in vec2d)
result = []
for k in range(total):
remaining = k
for row in vec2d:
if remaining < len(row):
result.append(row[remaining])
break
remaining -= len(row)
return resultThe Design (General/Specific) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Design (General/Specific)
Part of Design Patterns
Approach 2: Row and column pointer walkOptimalDesign (General/Specific)
What's slow: each lookup restarts at row 0 and passes rows it already crossed for the previous position. Neighboring positions repeat almost all of the same scan.
The insight that fixes it: the cell after (row, col) is either the next cell in the same row, or the first cell of the next non-empty row. Keep row and col between steps. Advance the cursor one cell at a time, and let it carry into the next row when a row ends.
Why it is correct. The cursor always points at the first cell not yet returned, in row-major order. Each step reads that cell and moves to the next one in the same order, so nothing is skipped or repeated. Empty rows and row ends fall under the same check, so the walk visits every cell exactly once.
Steps
- Set row = 0, col = 0, and create an empty result list.
- While row is less than R, compare col with the length of vec2d[row].
- If col is inside the row, append vec2d[row][col] and increase col by 1.
- If col is at or past the end of the row, increase row by 1 and set col to 0.
- Stop when row equals R, then return the result.
- In Java and C#, sum the row lengths first so the result array has the right size.
Dry run
The cursor starts at (0, 0). Each table row is one loop iteration. The result column shows what has been appended so far.
| Step | row | col | Check: col < len(row) | Action | result |
|---|---|---|---|---|---|
| 1 | 0 | 0 | 0 < 2, yes | append 1, col = 1 | [1] |
| 2 | 0 | 1 | 1 < 2, yes | append 2, col = 2 | [1, 2] |
| 3 | 0 | 2 | 2 < 2, no | row = 1, col = 0 | [1, 2] |
| 4 | 1 | 0 | 0 < 1, yes | append 3, col = 1 | [1, 2, 3] |
| 5 | 1 | 1 | 1 < 1, no | row = 2, col = 0 | [1, 2, 3] |
| 6 | 2 | 0 | 0 < 3, yes | append 4, col = 1 | [1, 2, 3, 4] |
| 7 | 2 | 1 | 1 < 3, yes | append 5, col = 2 | [1, 2, 3, 4, 5] |
| 8 | 2 | 2 | 2 < 3, yes | append 6, col = 3 | [1, 2, 3, 4, 5, 6] |
| 9 | 2 | 3 | 3 < 3, no | row = 3, col = 0 | [1, 2, 3, 4, 5, 6] |
| 10 | 3 | 0 | row 3 < 3 fails, loop ends | none | [1, 2, 3, 4, 5, 6] |
The loop ends at step 10 with the result [1, 2, 3, 4, 5, 6].
Complexity
| Time | O(N + R) |
|---|---|
| Space | O(1) extra, O(N) for the output |
With N the total element count and R the row count, every iteration either appends one element or moves row forward by one. Each append uses up one element, so at most N iterations append. Row never decreases, so at most R iterations move it. The total is at most N + R iterations of constant work, and the Java and C# size pass adds only O(R).
PythonTested in our runner
from typing import List, Optional
class Solution:
def flatten2DVector(self, vec2d: List[List[int]]) -> List[int]:
result = []
row, col = 0, 0
while row < len(vec2d):
if col < len(vec2d[row]):
# Read the cell under the cursor, then move right
result.append(vec2d[row][col])
col += 1
else:
# Row finished or empty: move to the next row
row += 1
col = 0
return resultCommon mistakes
col = 0withoutrow += 1in the else branch. An empty row then keeps the cursor in place, and the loop never ends. Advance the row and reset the column in the same branch.row += 1withoutcol = 0. The next row starts at the old column, so the walk skips its first cells or reads past the end of a shorter row.- A single
ifwhere awhilebelongs in the iterator form.hasNext()must skip several empty rows in a row, such as[[], [], [7]], before it can answer true. - Sizing the Java or C# result array with
new int[vec2d.length], which uses the row count. Output indices run past the array as soon as one row holds more than one element. Sum the row lengths first. - Reading
vec2d[row][col]innext()before the skip logic runs. When the cursor sits at the end of a row, that read is out of bounds. Skip empty rows first, then read. - In the brute force, indexing
vec2d[k]with the output position k. The position is a flat index, not a row index, so the read is wrong or fails once k reaches R.
Edge cases
[]expects[]. The loop never runs, so the result stays empty.[[]]and[[], []]expect[]. Every row is empty, so the walk must reach the end of the grid without appending anything.[[], [3]]expects[3]. A leading empty row must be skipped before the first read.[[1], [], [], [2]]expects[1, 2]. Several empty rows in a row must all be skipped.[[-1, 0], [0]]expects[-1, 0, 0]. Negative values and duplicates are copied as values, so they need no special handling.- A maximum-size input with N elements spread over many rows. The pointer walk stays linear, while the brute force does O(N * R) work.
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Flatten 2D Vector, with how to answer them.
Unlock the follow-upsFlatten 2D Vector FAQ
What is the time complexity of Flatten 2D Vector?
The pointer walk runs in O(N + R) time, where N is the total number of elements and R is the number of rows. The brute force that rescans rows for each position runs in O(N * R) time. Both are O(N) when every row has at least one element.
Why use a pointer walk for Flatten 2D Vector?
The walk keeps its position between steps, so each step does constant work. Rows are visited in order and never revisited, which bounds the total loop count by N + R. The same cursor becomes the state behind next() and hasNext() in the design version.
Can Flatten 2D Vector be solved in O(1) extra space?
Yes, beyond the output. The walk keeps two integers, row and col, and reads the input directly. The flatten function must return N values, so the output itself is O(N). In the iterator form there is no output list, and the state stays O(1).
Why does my flatten loop hang on empty rows?
An empty row fails the column check, and the else branch must move the row forward. If that branch only resets col, the cursor stays on the empty row forever. Increment row in the same branch that resets col.
Does Flatten 2D Vector need a hash map or sorting?
No. Row-major order matches the order the input already has, so no reordering or lookup table is needed. The only state is the two cursor values.
Asked at
See which companies ask this — Pro
Related problems
- LRU Cache · same technique: Design (General/Specific)
- Min Stack · same technique: Design (General/Specific)
- Time Based Key-Value Store · same technique: Design (General/Specific)
- Encode and Decode Strings · same technique: Design (General/Specific)
- Detect Squares · same technique: Design (General/Specific)
- Design Circular Queue · same technique: Design (General/Specific)
- Find Median from Data Stream · next harder, same pattern
- Implement Trie (Prefix Tree) · same pattern: Design Patterns
- Design Add and Search Words Data Structure · same pattern: Design Patterns
- Extra Characters in a String · same pattern: Design Patterns