Skip to content
playdsa
Preferences

Make yourself comfortable.

Saved on this browser. Your device’s reduced-motion preference is always respected.

Theme
Advanced settings

The Bit Census

Learn
Play
Prove
Problem context and objectives
Mission briefing

Puzzle systems engineer · A game mechanic is behaving incorrectly

Reuse the count after removing one set bit: The Bit Census.

Brute force may pass the demo but fail when the world fills with players.

How you win

  1. 1Recognize when Counting bits matches the clues
  2. 2Keep this true after every move: counts[value] is the exact number of set bits for every processed value
  3. 3Reach the result within O(n) time and O(n) output space

Rules and pressure

  • Target cost: O(n) time and O(n) output space
  • State rule: counts[value] is the exact number of set bits for every processed value
Lesson 1 of 3

Live algorithm trace

Counting bits

Complete execution
1 of 5

Seed zero with no one-bits.

1counts[0] = 0
2for value from 1 through n
3smaller = value & (value - 1)
4counts[value] = counts[smaller] + 1
5return counts
counts = [0]
Truth to preserve / Cost target
Truth to preserve

counts[value] is the exact number of set bits for every processed value

Cost target

O(n) time and O(n) output space

Clearing the lowest set bit maps each positive integer to a smaller number whose answer is already known. Add one for the bit that was removed.

Your call · What should guide every step of this algorithm?

Help shape PlayDSA

Something confusing, broken, or missing? Leave a quick note without leaving your lesson.

Please leave out passwords, payment details and other private information.

Page included: /

Sign in to save feedback here, or send it with your email app. Your draft stays here while you sign in.

Open email instead