Skip to content
BytePatterns

Every Subset by Bitmask

EasyBit Manipulation#bitmask#subsets~20m

Problem

Given a list of distinct items, return every subset of it. Order the subsets by counting: read a subset as a binary number in which bit i is 1 when items[i] is included, and list the subsets from that number 0 up to the largest. Inside each subset keep the items in their original order. The list holds at most 15 items, and the empty list still has one subset.

Examples

Input:  items = ["a", "b"]
Output: [[], ['a'], ['b'], ['a', 'b']]
Why:    the numbers 0, 1, 2 and 3 in binary are 00, 01, 10 and 11
Input:  items = [1, 2, 3]
Output: [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
Why:    items[2] joins from number 4 onwards, when bit 2 turns on
Input:  items = []
Output: [[]]
Why:    edge case, the empty set is the only subset

Hints

0 / 3

Stuck on the idea rather than the code? Bitmask as a Set covers it.