Count Set Bits for Every Integer From Zero to N

Last updated: November 29, 2026

Quick Overview

Given n, return a list where entry i is the number of 1 bits in the binary representation of i, for every i from 0 to n, in a single linear pass.

Microsoft
Coding & Algorithms
Software Engineer
Microsoft
November 29, 2026
Software Engineer
Online Assessment
Coding & Algorithms
Easy

0

0

0 solved


Given n, return a list where entry i is the number of 1 bits in the binary representation of i, for every i from 0 to n, in a single linear pass.

A short Microsoft online assessment item that separates candidates who call popcount n times from those who see the recurrence between i and i >> 1. Interviewers in follow-up rounds use it to check comfort with shifts and simple DP.

What the Interviewer Expects
  • Give the naive O(n log n) approach first
  • Find the recurrence bits[i] = bits[i >> 1] + (i & 1)
  • Alternatively use bits[i] = bits[i & (i - 1)] + 1
  • Produce the result in O(n) time
  • Explain why the recurrence is correct
Key Topics to Cover
bit manipulation
dynamic programming
popcount
math
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Why does i & (i - 1) clear the lowest set bit?
  • How would you compute the total number of set bits from 0 to n in O(log n)?
  • Which hardware instruction does this replace, and when would you just use it?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input n is a non-negative integer up to around 10^5 or 10^6. Return a list of length n + 1. Built-in popcount is allowed for checking but the interviewer wants a linear solution that reuses earlier an...

High-Level Design

Shifting i right by one drops its lowest bit, and the rest of the bits are unchanged. So the set bits of i equal the set bits of i >> 1, plus one if the dropped bit was a 1. Since i >> 1 < i, that...


Submit Your Answer
Markdown supported