Into One Stream
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L5
- Asked in
- eHealth
Problem
A log collector hands you a buffer where each slot is either a single event id or a batch of ids grouped in a nested list. Return every id from items in one flat list, keeping their left-to-right order.
Some arrive alone, some in batches. Line them all up.
Example 1
Input:
items = [1,[2,3],4,[5]]
Output:
[1,2,3,4,5]
Example 2
Input:
items = [[1,2],[3,4]]
Output:
[1,2,3,4]
Worked solution and explanation
What this really is
This is type-driven dispatch wearing a data-cleaning costume. Each slot is either a scalar id or a batch of ids, and the whole game is deciding, per element, whether to unpack it or drop it in as-is. Anyone can write the loop. The tell is how you merge a batch: most candidates reach for sum(items, []) or a comprehension that assumes every element is a list, and it detonates the moment it meets a bare integer, because you cannot concatenate an int. Get the branch wrong and you either raise TypeError on the first scalar or silently lose the singletons.
Break down the requirements
Step 1: Iterate through the top-level list once
Walk items a single time. Every element is either an integer or a one-level nested list of integers, so one linear pass over the top level is enough. no recursion needed.
Step 2: Branch: extend for lists, append for scalars
If the element is a list, spread its contents into result with result.extend(item). Otherwise the element is a scalar, so drop it in directly with result.append(item). That two-way branch is the entire problem. an empty batch simply extends with nothing, so no special-casing is required.
The solution
def flatten_the_nest(items):
result = []
for item in items:
if isinstance(item, list):
result.extend(item)
else:
result.append(item)
return resultCommon follow-up questions
- What if a batch could arrive as a `tuple` as well as a list? (Tests broadening the type check to `isinstance(item, (list, tuple))` to accept more than one container type.)
- How would you handle `None` values mixed into the buffer? (Tests whether `None` is a leaf to include or a value to filter out. forces you to define the branch precisely.)
- What changes if batches could themselves contain batches, to arbitrary depth? (Tests generalizing the single branch into recursion or an explicit stack with a depth parameter.)