Skip to content

BitMask ​

A bitmask is a technique that uses the binary digits (bits) of a single integer like switches to represent whether each element of a set is present.

At a Glance ​

Imagine five light switches mounted in a row on a wall. On is 1 and off is 0. You can write "switches 1, 2 and 5 are on" as a single line like 10011, and that line is simply a number. A bitmask is a way of packing many yes/no answers into one integer.

Why Use a Bitmask? ​

  • It lets you solve problems, such as DP or permutation problems, where representing the state with arrays alone is cumbersome or too heavy
  • It can solve problems with little memory and fast running time (as long as the number of elements is not too large)
  • A set can be represented as an array index
  • The code becomes more concise

With n elements there are 2^n possible subsets, so it is usually used when n is around 20 or less. (2^20 is about 1 million, 2^30 is about 1 billion.)

What Is a Bit? ​

It is the smallest unit of data used in computers (0 and 1). It is easiest to think in terms of binary.

What happens when we convert an everyday decimal number to binary?

9 (decimal) → 1001 (binary)

Place8421
9 in binary1001

8 + 1 = 9. The rightmost digit is called bit 0, and moving left you get bit 1, bit 2 and so on.

Trying Out Bitmasking ​

Let's use 0 and 1 as flags (markers).

Suppose we have the set [1, 2, 3, 4, 5]. We are given a situation where we need to pick some of its elements arbitrarily and check them. (In other words, subsets.)

text
{1}, {2}, ..., {1,2}, ..., {1,2,5}, ..., {1,2,3,4,5}

Of course, you could simply loop with for statements and store the combinations in arrays. With bitmasking, however, each element can be represented like an index and accessed efficiently.

SubsetBinaryDecimal
[1, 2, 3, 4, 5]1111131
[2, 3, 4, 5]1111030
[1, 2, 5]1001119
[2]000102

A 1 means the i-th element of the set is present, and 0 means it is not. In this table, the rightmost position (bit 0) is element 1, the one to its left is element 2, ..., and the leftmost position (bit 4) is element 5.

Such binary numbers can be converted back to decimal. 11111 is 31 in decimal, so it is possible to represent a subset as an integer. 31 means the subset containing all of [1, 2, 3, 4, 5].

Now, when we want to add i to a subset, we can represent it by turning just that bit into 1. This kind of work is controlled with bitwise operations.

Bitwise Operations ​

There are AND, OR, XOR, NOT and SHIFT. In the examples below, A = 1100 and B = 1010.

OperationSymbolRuleExample
AND&1 when both corresponding bits are 11100 & 1010 = 1000
OR|1 when at least one of the corresponding bits is 1 (also 1 if both are 1)1100 | 1010 = 1110
XOR^1 when the corresponding bits differ1100 ^ 1010 = 0110
NOT~Flips the bit values~1100 = 0011 (4 digits)
SHIFT<<, >>Moves the bits left or right0001 << 2 = 0100
  • Left shift: A << B = A * 2^B
  • Right shift: A >> B = A / 2^B (the fractional part is dropped, i.e. A // 2^B. Example: 13 >> 1 = 6)
DirectionBit changeDecimal change
Left0001 → 0010 → 0100 → 10001 → 2 → 4 → 8
Right1000 → 0100 → 0010 → 00018 → 4 → 2 → 1

Be careful with ~ in Python. Python integers have no digit limit, so ~a becomes -a - 1 (a negative number). To keep only the n digits you want, AND it with a number whose n digits are all 1, as in ~a & ((1 << n) - 1).

Bitwise operation practice problem: Baekjoon 12813 (see the Python code below)

How It Works ​

Once you have practiced, let's return to bitmasks and put bitwise operations to use. The work divides into insert, delete and lookup. (Bits are numbered from 0 at the right end.)

TaskExpressionExample (i = 3)Result
InsertS | (1 << i)10101 | 0100011101
DeleteS & ~(1 << i)11101 & 1011110101
LookupS & (1 << i)10101 & 010000 (off)

1. Insert ​

The current state is 10101, and we want to change bit i to 1. If i = 3, the result should be 11101. Here we use the OR operation.

text
10101 | (1 << 3)

1 << 3 is 1000, so this becomes 10101 | 01000, which gives 11101. OR leaves positions that are already 1 unchanged and turns on only bit 3.

2. Delete ​

Conversely, to change a bit to 0, use the AND and NOT operations.

text
11101 & ~(1 << 3)

~(1 << 3) is 10111, the inverse of 1000, so this becomes 11101 & 10111, which gives 10101. ANDing with a number that has 0 only at bit 3 and 1 everywhere else turns off only bit 3.

The parentheses are required. Because ~ is evaluated before <<, writing ~1 << 3 means (~1) << 3, which is ...11110000, and it clears the lower three bits as well. (The result of 11101 & ~1 << 3 is 10000, not 10101.)

3. Lookup ​

To find out the value of bit i, use the AND operation.

text
10101 & (1 << i)

Value of bit 3 : 10101 & (1 << 3) = 10101 & 01000 → 0
Value of bit 4 : 10101 & (1 << 4) = 10101 & 10000 → 10000

If the result is 0 like this, you know bit i is 0. (Conversely, if it is not 0, the bit is definitely 1.)

Solving problems with techniques like these is what a bitmask is about.

Python Code ​

Bitwise Operation Practice (Baekjoon 12813) ​

The problem takes two binary strings A and B of the same length and prints A & B, A | B, A ^ B, ~A and ~B in order.

python
def bit_ops(a_str, b_str):
    n = len(a_str)
    a = int(a_str, 2)                  # 1. Convert the '0'/'1' string to an integer
    b = int(b_str, 2)
    mask = (1 << n) - 1                # 2. A number whose n digits are all 1 (used to trim NOT results to n digits)
    results = [
        a & b,                         # 3. AND
        a | b,                         #    OR
        a ^ b,                         #    XOR
        ~a & mask,                     # 4. NOT A (keep only n digits with mask)
        ~b & mask,                     #    NOT B
    ]
    return [format(x, f'0{n}b') for x in results]  # 5. Back to n-digit binary strings


for line in bit_ops('0001100110', '1100110011'):
    print(line)
# Output:
# 0000100010
# 1101110111
# 1101010101
# 1110011001
# 0011001100
  1. int(string, 2) converts a binary string to an integer.
  2. If n = 10, mask is 1111111111.
  3. AND, OR and XOR are computed between whole integers at once. (The original C code computed them one character at a time in a loop, taking advantage of the fact that the character codes of '0' and '1' differ only in the last bit.)
  4. Python's ~ produces a negative number, so AND it with mask to keep only n digits.
  5. Writing format(x, '010b') returns an n-digit binary string padded with leading zeros.

Insert, Delete, Lookup and Iterating Over Subsets ​

python
items = [1, 2, 3, 4, 5]

# 1. Subset <-> integer: element k is bit (k-1) from the right
def to_mask(subset):
    mask = 0
    for x in subset:
        mask |= 1 << (x - 1)
    return mask

def to_subset(mask):
    return [items[i] for i in range(len(items)) if mask & (1 << i)]

print(format(to_mask([1, 2, 5]), '05b'), to_mask([1, 2, 5]))  # Output: 10011 19
print(to_subset(0b11110))                                     # Output: [2, 3, 4, 5]

# 2. Insert: set bit i to 1 (OR)
s = 0b10101
s = s | (1 << 3)
print(format(s, '05b'))            # Output: 11101

# 3. Delete: set bit i to 0 (AND + NOT), parentheses required
s = s & ~(1 << 3)
print(format(s, '05b'))            # Output: 10101

# 4. Lookup: is bit i on? (AND)
print(s & (1 << 3))                # Output: 0   -> bit 3 is 0
print(format(s & (1 << 4), '05b')) # Output: 10000 -> not 0, so bit 4 is 1

# 5. Iterate over all subsets: 0 ~ 2^n - 1
n = 3
for mask in range(1 << n):
    print(format(mask, '03b'), to_subset(mask))
# Output:
# 000 []
# 001 [1]
# 010 [2]
# 011 [1, 2]
# 100 [3]
# 101 [1, 3]
# 110 [2, 3]
# 111 [1, 2, 3]
  1. Element 1 maps to bit 0 and element 5 maps to bit 4. This is the same rule as in the earlier table.
  2. Turn on bit 3 with OR. 10101 → 11101.
  3. AND with ~(1 << 3) to turn off only bit 3. 11101 → 10101.
  4. If the result is 0 the bit is off; otherwise it is on.
  5. The integers from 0 to 2^n - 1 are exactly all subsets of n elements. A single for loop can go through every subset.

Time and Space Complexity ​

TaskBestAverageWorstExtra space
Insert / delete / lookup (one bit)O(1)O(1)O(1)O(1)
Listing all subsetsO(n · 2^n)O(n · 2^n)O(n · 2^n)O(1) (one integer for listing)
Traveling salesman bitmask DPO(n^2 · 2^n)O(n^2 · 2^n)O(n^2 · 2^n)O(n · 2^n)
  • An operation on a single bit is a computation on one integer, so it is O(1). (This assumes the number of elements is at most 64, the size of a machine integer. Python also handles larger integers, but it slows down in proportion to the number of digits.)
  • There are 2^n subsets, and each one checks n elements, so it is O(n · 2^n).
  • For the notation, see the time complexity article.

Where It Is Used: Traveling Salesman (Baekjoon 2098) ​

Bitmask practice problem: Baekjoon 2098

The problem asks for the minimum cost of visiting every city exactly once and returning to the starting point.

Brute force can find the answer, but N can be up to 16, so there are 16! visiting orders (15!, about 1.3 trillion, even with the starting city fixed), which leads to a time-out.

So you need DP, and since "which cities have been visited so far" is hard to manage with arrays, it is a good problem for bitmasks. If the set of visited cities is represented as a single integer (mask), that integer can be used directly as a cell index in the DP table. This reduces the work to about 16 × 16 × 2^16 ≈ 17 million.

dp[mask][cur] = "the minimum cost to get here when the set of visited cities is mask and we are currently at city cur"

python
INF = float('inf')


def tsp(w):
    n = len(w)
    full = (1 << n) - 1                # 1. State where every city has been visited (all n digits are 1)
    # 2. dp[mask][cur] = minimum cost so far when the visited set is mask and we are at cur
    dp = [[INF] * n for _ in range(1 << n)]
    dp[1][0] = 0                       # Start from city 0 (mask = 0001)

    for mask in range(1 << n):
        for cur in range(n):
            if dp[mask][cur] == INF:
                continue
            for nxt in range(n):
                # 3. Skip if already visited or there is no road (lookup)
                if mask & (1 << nxt) or w[cur][nxt] == 0:
                    continue
                new_mask = mask | (1 << nxt)   # 4. Mark nxt as visited (insert)
                cost = dp[mask][cur] + w[cur][nxt]
                if cost < dp[new_mask][nxt]:
                    dp[new_mask][nxt] = cost

    # 5. After visiting everything, add the cost of returning to city 0 and take the minimum
    return min(dp[full][cur] + w[cur][0]
               for cur in range(n) if w[cur][0] != 0 and dp[full][cur] != INF)


w = [
    [0, 10, 15, 20],
    [5, 0, 9, 10],
    [6, 13, 0, 12],
    [8, 8, 9, 0],
]
print(tsp(w))  # Output: 35
  1. With 4 cities, full is 1111 (15).
  2. The number of cells is (possible visited sets 2^n) × (current city n). It starts from the state where only city 0 has been visited (0001) with cost 0. Since the tour forms a cycle, the answer is the same no matter which city it starts from.
  3. Use lookup to check whether nxt has already been visited. w[cur][nxt] == 0 means there is no road.
  4. Use insert to create a new state with nxt added to the visited set, and update it if the cost is lower. new_mask is always larger than mask, so if masks are processed from small to large, the needed values are already filled in.
  5. From the state where every city has been visited, add the road back to the starting point and pick the cheapest value. (This assumes only inputs where a tour is possible are given.)

The answer 35 in the example is the order 0 → 1 → 3 → 2 → 0 (10 + 10 + 9 + 6).

Summary ​

ConceptPlain-language summary
BitmaskPacking the on/off states of many switches into one number
Subset ↔ integerPositions of elements that are present are 1, absent ones are 0
InsertTurn on that switch with OR: S | (1 << i)
DeleteTurn off only that position by ANDing with the NOT value: S & ~(1 << i) (parentheses required)
LookupIf the AND result is 0 it is off, otherwise on: S & (1 << i)
Bitmask DPTurn "where have we visited" into an integer and use it as a cell index in the DP table

Reference: mygumi blog - Bitmask, Baekjoon 12813, Baekjoon 2098