Flatten with reduce()

Hard ⏱ 18 min 29% acceptance ★★★★★ 4.7
Write flatten(lists) that concatenates a list of lists into one list using functools.reduce with a lambda (+ on lists). Include the empty-list initializer so flatten([]) returns []. Note for discussion: this is O(n²) — fine for interviews, but mention why.

Examples

Example 1
Input
flatten([[1, 2], [3], []])
Output
[1, 2, 3]
Explanation

Lists fold together left to right.

Constraints

  • Use reduce, not sum() or itertools.
  • flatten([]) → [].

Topics

Lambda & Functionalreduce

Companies

AirbnbLinkedIn

Hints

Hint 1

reduce(lambda a, b: a + b, lists, []).

Hint 2

Each + creates a new list — that is where the O(n²) comes from.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.