Flatten a category tree

lists

Flatten a category tree

Amazon Python Interview Question

Amazon's catalog exports product categories as nested lists, where a list inside a list holds subcategories, which can be nested to any depth.

Write a function flatten(categories) that returns a single flat list with every category name in the order it appears.

Asked of

  • Data Analyst
  • Data Engineer
  • Data Scientist
  • ML Engineer
  • AI Engineer

Example 1

Input

categories = ["Electronics", ["Laptops", ["Gaming Laptops"], "Tablets"], "Books"]

Output

["Electronics", "Laptops", "Gaming Laptops", "Tablets", "Books"]

Example 2

Input

categories = [["a"], ["b", ["c"]]]

Output

["a", "b", "c"]

Explanation

In the first example, "Laptops" and "Tablets" sit one level down and "Gaming Laptops" sits two levels down. Flattened, the names appear in the order they are written.

Submit also runs 3 hidden test cases that check edge cases.