...

/

Flatten Nested List Iterator

Flatten Nested List Iterator

Try to solve the Flatten Nested List Iterator problem.

Statement

You’re given a nested list of integers. Each element is either an integer or a list whose elements may also be integers or other integer lists. Your task is to implement an iterator to flatten the nested list.

You will have to implement the Nested Iterator class. This class has the following functions:

  • Constructor: This initializes the iterator with the nested list.
  • Next (): This returns the next integer in the nested list.
  • Has Next (): This returns TRUE if there are still some integers in the nested list. Otherwise, it returns FALSE.

Constraints

  • The nested list length is between 11 and 200200.
  • The nested list consists of integers between [1,104][1, 10^4].

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Flatten Nested List Iterator

1.

What is the output if the following set of parameters are passed to the Constructor(), Next, and Has next() functions?

Constructor([3, [6, 7], 8])
Next()
Has Next()
Next()
Next()
A.

NULL

3

TRUE

6

7

B.

NULL

3

TRUE

[6, 7]

8

C.

NULL

3

TRUE

[6, 7, 8]

9


1 / 3

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Note: You need to figure out the solution of the Has Next () function only.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3

Try it yourself

Implement your solution in nested_iterator.py in the following coding playground. You’ll need the provided supporting code to implement your solution.

Python
usercode > nested_iterator.py
from nested_integers import NestedIntegers
class NestedIterator:
# Initializes the NestedIterator with nested_list
def __init__(self, nested_list):
# Write your code here
pass
# checks if there are still some integers in nested_list
def has_next(self):
# Write your code here
pass
# returns the next element from nested_list
def next(self):
# Write your code here
pass
# ------ Please don't change the following function ----------
# flatten_list function is used for testing porpuses.
# Your code will be tested using this function
def flatten_list(nested_iterator_object):
result = []
while nested_iterator_object.has_next():
result.append(nested_iterator_object.next())
return result
Flatten Nested List Iterator

Access this course and 1200+ top-rated courses and projects.