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 on the new till to make sure the prices come out right: the plain burger, every burger with one topping, every pair, all the way up to the one with everything.

Two burgers with the same toppings are the same burger, whatever order the toppings were added in. 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 either on the burger or not, so 3 toppings give 2 × 2 × 2 = 8 burgers. The plain burger [] counts, and ["onion", "cheese"] would be the same burger as ["cheese", "onion"], so it must not appear twice.

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

With no toppings on the menu there is still one burger to ring up: the plain one. So the answer 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 loop for single toppings, two nested loops for pairs, three for triples. But the number of nested loops would have to match the size of the menu, and you cannot write a different number of loops for every input. Recursion is the way to get "one loop level per topping".

Speed is not the issue here: the answer itself holds 2n selections, so no method can beat O(n · 2n). Counting in binary from 0 to 2n − 1 and reading each bit as "topping in or out" is just as fast. The recursive version is worth learning because the same skeleton still works when later problems add rules about 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