Java O(n) space O(1) time

  • 0

    I know we could do better to bring down the space complexity but here is a intuitive one...
    Basically we just convert the nested list into an arraylist in the constructor and keep track of the index of the previous accessed element:

    public class Vector2D implements Iterator<Integer> {
        List<Integer> result;
        int curr_idx = 0;
        public Vector2D(List<List<Integer>> vec2d) {
            result = new ArrayList<>();
            for (int i = 0; i < vec2d.size(); i++) {
                if (!vec2d.get(i).isEmpty()) {
        public Integer next() {
            return result.get(curr_idx++);       
        public boolean hasNext() {
            return curr_idx < result.size();        

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.