Count Enabled Feature Flags in Every Bitmask From Zero to N
Last updated: November 29, 2026
Quick Overview
Feature-flag bitmasks are numbered 0 to n. Return an array where entry i is the number of set bits in i, in O(n) total time without calling a popcount builtin per number.
ByteDance
November 29, 20260
0
0 solved
Feature-flag bitmasks are numbered 0 to n. Return an array where entry i is the number of set bits in i, in O(n) total time without calling a popcount builtin per number.
ByteDance's experimentation platform (Libra) packs feature flags and experiment buckets into bitmasks, and a quick bit question is a common phone-screen opener. The interviewer looks for the recurrence that reuses earlier answers rather than counting bits of each number from scratch.
What the Interviewer Expects
- Derive a recurrence relating i to i >> 1 or i & (i - 1)
- Fill the array in one linear pass
- Explain why the recurrence is correct
- Compare with the O(n log n) naive approach
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Give the alternative recurrence using i & (i - 1) and explain it.
- How would you count set bits of a single 64-bit integer in constant time?
- How would you find how many masks in [0, n] have exactly k bits set without enumerating?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input is a non-negative integer n. Output is a list bits of length n + 1 with bits[i] equal to the population count of i. The target is linear time, using each earlier answer once....
High-Level Design
Shifting i right by one drops its lowest bit, and that bit is i & 1. So the number of set bits in i equals the count for i >> 1 plus i & 1. Since i >> 1 < i, the value is already computed ...