Every Snack Bundle
Easy · Backtracking · about 15 min
A café sells snacks with distinct id numbers. A bundle is any group of these snacks: the empty bundle and the bundle with every snack both count. Return every bundle.
- Write each bundle with its ids sorted ascending.
- Return the bundles sorted the way Python sorts lists: compare them item by item, and if one bundle is the start of another, the shorter one comes first. (In JavaScript,
.sort()with no comparator sorts as text, so write a comparator or build the bundles in order.) itemsholds 0 to 10 distinct integers, in any order, possibly negative.
all_bundles([3, 1, 2]) → [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
all_bundles([]) → [[]]
Hints
- Sort the ids first so every bundle is built in ascending order.
- Write a helper that takes a start position. It records the current bundle, then for each position from start onward: add that id, recurse from the next position, remove the id.
- Record a copy of the bundle. If you record the list you keep changing, every entry ends up empty.
Learn the pattern first: the Backtracking lesson.
More Backtracking problems
- Every Seating Plan (Easy)
- Keypad Spellings (Easy)
- Distinct Gift Bags (Medium)
- Exact Change Stacks (Medium)
- Trace a Word on the Letter Board (Medium)
- Mirror Word Splits (Medium)
- Peaceful Queens Count (Hard)