Browse curriculum

Bit Manipulation

The Bit Manipulation Pattern

Work on the binary form of a number directly instead of on its decimal value. A few identities carry most interview questions: n & (n - 1) clears the lowest set bit, x ^ x = 0 cancels pairs, n >> 1 and n & 1 walk the bits one at a time, and & with ^ add two numbers without the + operator.

7

Interactive problems

Recognise

How do you recognise a bit manipulation problem?

The problem talks about bits, binary representations, powers of two, or asks for O(1) extra space on a counting or "find the missing or single one" task, where XOR cancelling pairs or a bit mask replaces a hash set.

Complexity

What is the time complexity of the bit manipulation pattern?

O(number of bits) per number, which is O(1) for fixed-width integers, with O(1) extra space — against O(n) extra space for the hash set or array a counting approach would use.

Problems

Bit Manipulation practice problems

Each problem pairs a worked explanation with an interactive visualizer you step through yourself, plus the implementation in JavaScript, Python, Java and C++.

Complexity

Bit Manipulation problems by difficulty and complexity

The difficulty, running time and extra space of every bit manipulation solution on this page, as each lesson derives them.

LessonDifficultyBestAverageWorstSpace
Number of 1 BitsEasyΩ(1)Θ(k)O(32)O(1)
Single NumberEasyΩ(n)Θ(n)O(n)O(1)
Missing NumberEasyΩ(n)Θ(n)O(n)O(1)
Reverse BitsEasyΩ(32)Θ(32)O(32)O(1)
Sum of Two IntegersMediumΩ(1)Θ(1)O(32)O(1)
Pow(x, n)MediumΩ(log n)Θ(log n)O(log n)O(1)
Reverse IntegerMediumΩ(log |x|)Θ(log |x|)O(log |x|)O(1)
Curriculum

The underlying technique is covered from first principles in the bit manipulation lesson in the DSA visualizer curriculum. Bit Manipulation is one of the 18 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.

Directory

Every other coding interview pattern