Distinct Gift Bags
Medium · Backtracking · about 20 min
A shelf holds gift items given by id, and the same id can appear more than once (two identical mugs both have id 4). A bag is any selection of items from the shelf, including the empty bag. Two bags are the same if they hold the same ids the same number of times. Return each different bag exactly once.
- Write each bag with its ids sorted ascending.
- Return the bags sorted the way Python sorts lists (compare item by item; a shorter bag that is the start of a longer one comes first).
itemsholds 0 to 10 integers in any order, possibly negative.
distinct_bags([2, 1, 2]) → [[], [1], [1, 2], [1, 2, 2], [2], [2, 2]]
Hints
- Sort first so equal ids are neighbours.
- Use a helper with a start position that records the current bag, then tries each position from start onward.
- In that loop, skip a position whose id equals the previous position's id, but only when the previous position was also tried in this same loop.
Learn the pattern first: the Backtracking lesson.
More Backtracking problems
- Every Snack Bundle (Easy)
- Every Seating Plan (Easy)
- Keypad Spellings (Easy)
- Exact Change Stacks (Medium)
- Trace a Word on the Letter Board (Medium)
- Mirror Word Splits (Medium)
- Peaceful Queens Count (Hard)