Counting Bits
Problem Statement
Given n, build an array of n + 1 numbers. The number at index i is how many 1 bits i has in binary, for every i from 0 to n. Do not use built-in bit-count functions.
Follow-up: it is easy to get O(N log N) time. Can you do it in O(N) time, in a single pass?
An integer n.
An array ans of length n + 1, where ans[i] is the number of 1 bits in i.
0 has no 1 bits. 1 = 1 has one. 2 = 10 has one.
3 = 11 has two 1 bits, 4 = 100 has one, and 5 = 101 has two.
- β’ 0 β€ n β€ 10^5
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each i, shift it right and add up its bits
ans[i] = ans[i >> 1] + (i & 1), filled from 1 up to n
Count the 1 bits of each i from 0 to n on its own. Each count shifts i right one bit at a time and adds the lowest bit.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Bit Manipulation translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.