Count Set Bits for Every Permission Mask From Zero to N

Last updated: November 29, 2026

Quick Overview

An access-control service stores permissions as bitmasks, and an audit needs the number of granted permissions for every mask value from 0 to n. Return the list of popcounts in O(n) total time.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Easy

0

0

0 solved


An access-control service stores permissions as bitmasks, and an audit needs the number of granted permissions for every mask value from 0 to n. Return the list of popcounts in O(n) total time.

Google interviewers use this to see whether you can reuse earlier answers instead of recomputing, a small DP over integers. A loop with bin(i).count('1') works but they will ask for the linear-time recurrence and why it is correct.

What the Interviewer Expects
  • Relate the bit count of i to a smaller number already computed
  • Use either i >> 1 or i & (i - 1) as the subproblem
  • Explain why the recurrence is correct in binary
  • Produce O(n) time without per-number bit loops
Key Topics to Cover
1D dynamic programming
Bit manipulation
Popcount
Reuse of subproblems
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
  • Which recurrence would you pick if the hardware has a fast popcount instruction?
  • Count how many masks in 0..n have exactly k bits set without listing them.
  • Return only the total number of set bits across 0..n in O(log n).
  • How does the answer change for signed 32-bit masks?
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: integer n >= 0. Output: list ans of length n + 1 where ans[i] is the number of 1 bits in i. We want O(n)O(n) overall rather than O(nlog⁡n)O(n \log n) from counting each number separately....

High-Level Design

Shifting i right by one drops its lowest bit, giving a smaller number whose count we already know. So bits[i] = bits[i >> 1] + (i & 1). An equivalent recurrence uses i & (i - 1), which clears the ...


Submit Your Answer
Markdown supported