progress

~/problems / Bit manipulation

Watering rota as weekday bitmasks

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A community garden stores each plant's watering days as a 7-bit mask: bit d is set if it's watered on day d (0 = Monday, ..., 6 = Sunday). So 5 = 0b0000101 is Monday and Wednesday.

Write two functions:

  1. busiest_day(masks: list[int]) -> int: the day 0..6 with the most plants watered; on a tie, the earliest.
  2. disjoint_pairs(masks: list[int]) -> int: the number of pairs i < j that share no day (masks[i] & masks[j] == 0), so one volunteer can take both.
busiest_day([5, 1, 64])          # 0     (Monday: plants 0 and 1)
busiest_day([2, 4])              # 1     (tie between Tuesday and Wednesday: earliest wins)
disjoint_pairs([5, 1, 64])       # 2     (5 & 64 == 0 and 1 & 64 == 0, but 5 & 1 != 0)
disjoint_pairs([3, 3, 4, 4])     # 4     (each 3 pairs with each 4)

Up to 10^5 plants, each mask 1 to 127.

⭐ Bonus: a speed test with 100,000 plants earns a star if disjoint_pairs is close to linear. Checking every pair is about 5·10^9 checks.

Show hint

test day d with (mask >> d) & 1. There are only 127 possible masks: count plants per mask and compare masks instead of plants.

Topic: Bit manipulation (IP / CIDR). IPv4 as a 32-bit int; lowest set bit for block sizes.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc