LeetCode 251: Flatten 2D Vector Solution
Master LeetCode problem 251 (Flatten 2D Vector), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
251. Flatten 2D Vector
Problem Explanation
Explanation:
To flatten a 2D vector, we can implement an iterator that iterates over each element in the 2D vector in a flattened manner. We can achieve this by using two indices, row and col, to keep track of the current position in the 2D vector.
Algorithm:
- Initialize
rowandcolto 0. - In the
next()function, return the element atrow,colposition. - In the
hasNext()function, check if there are more elements left in the 2D vector. - If
colreaches the end of the current row, incrementrowand resetcolto 0. - Repeat steps 2-4 until all elements are visited.
Time Complexity:
next()andhasNext()functions will take O(1) time on average.
Space Complexity:
- O(1) as we are not using any extra data structures. :
Solution Code
class Vector2D {
int[][] vec2d;
int row;
int col;
public Vector2D(int[][] vec) {
vec2d = vec;
row = 0;
col = 0;
}
public int next() {
hasNext();
return vec2d[row][col++];
}
public boolean hasNext() {
while (row < vec2d.length && col == vec2d[row].length) {
row++;
col = 0;
}
return row < vec2d.length;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 251 (Flatten 2D Vector)?
This page provides optimized solutions for LeetCode problem 251 (Flatten 2D Vector) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 251 (Flatten 2D Vector)?
The time complexity for LeetCode 251 (Flatten 2D Vector) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 251 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 251 in Java, C++, or Python.