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

Single-level flatten with type branching
def flatten_the_nest(items):
    result = []
    for item in items:
        if isinstance(item, list):
            result.extend(item)
        else:
            result.append(item)
    return result

Common follow-up questions