Burger Truck Test Orders

EasybacktrackingAlso known as Subsets

A burger truck lets customers add any of its extra toppings, each at most once. Before opening day, the owner wants to ring up every possible burger to check the till's prices: the plain burger, every burger with a single topping, every pair of toppings, and so on up to the burger with everything.

Burgers with the same toppings are the same burger, whatever order the toppings went on. Your job is to produce the full test list.

Your task

Write allOrders(toppings). toppings is a list of different topping names. Return a list containing every possible selection of toppings exactly once, including the empty selection (the plain burger).

Each selection is a list of topping names. The selections can be in any order, and the toppings inside a selection can be in any order.

allOrders(toppings: string[]) → string[][] Several answers can be correct; any valid one is accepted.

Examples

Example 1
Input
toppings = ["cheese", "onion", "pickle"]
Output
[[], ["pickle"], ["onion"], ["onion", "pickle"], ["cheese"], ["cheese", "pickle"], ["cheese", "onion"], ["cheese", "onion", "pickle"]]
Why

Each topping is on or off, so 3 toppings give 2 × 2 × 2 = 8 burgers. The plain burger [] counts, and ["onion", "cheese"] is the same burger as ["cheese", "onion"], so it must not appear twice.

Example 2
Input
toppings = []
Output
[[]]
Why

With no toppings there is still one burger to ring up, the plain one. The result is a list holding one empty selection, not an empty list.

Constraints

  • 0 ≤ toppings.length ≤ 10
  • All topping names are different, non-empty strings.
  • Selections and the toppings inside them may be returned in any order.
Start with brute force

The first instinct is nested loops: one for singles, two for pairs, three for triples. But the number of loops would have to match the number of toppings, which changes with every input. Recursion gives you one level of looping per topping without fixing the number of levels in advance.

Speed is not the issue, because the answer holds 2n selections and so nothing beats O(n · 2n). Counting in binary from 0 to 2n − 1, with each bit meaning that a topping is in or out, is just as fast. Recursion is worth learning because its skeleton still works when later problems restrict which choices are allowed.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code