DSA Trainer
← Foundations

Foundations · Unit 17

Bit Manipulation

Every integer your program holds is really a row of bits, ones and zeros, each standing for a power of two. Most of the time you never think about that. But a handful of problems crack open beautifully when you operate on those bits directly, often solving in O(1) extra space what a hash map would need O(n) for.

The classic example: an array where every number appears twice except one, and you want the loner. A hash map works, but XOR finds it with a single accumulator and no extra memory, because XOR makes identical values cancel. That kind of trick is what this unit is about, and equally important, when NOT to reach for it.

Bit manipulation is a narrow, sharp tool. It shines on specific structures, pairs that cancel, powers of two, packing a set of yes/no flags into one number, and it is the wrong tool for general counting. This unit teaches the operators, the few tricks worth memorizing, and the recognition that keeps you from forcing bits where a plain hash map belongs.

Goal: Use the bitwise operators (especially XOR) to solve specific structured problems in O(1) space, and recognize when bits are the wrong tool.
Lesson 1 of 60%

You’re not signed in. Your progress here won’t be saved.

Numbers are bits

An integer is stored in binary: a sequence of bit positions, each worth a power of two. The number 13 is 1101 in binary, which is 8 + 4 + 0 + 1. Each 1 turns its power of two on; each 0 leaves it off.

That is the whole foundation. When a problem can be reframed as "which bits are set," you can sometimes manipulate those bits far more cheaply than working with the numbers as a whole.

The binary number 1011 represents what value?

Premium practice

The drills and graded test are premium

The lessons above are free. The interactive practice that turns recognizing the pattern into recalling it on a blank page unlocks with premium:

  • 3 applied drills: train spotting when the concept applies
  • A 5-question graded test to clear the unit
  • The full guided problem ladder with faded hints, plus the cold-read capstone
Unlock everything →

From $6/month. Cancel anytime.