Compute the Common Bit Prefix Across a Range of Instance IDs
Last updated: November 29, 2026
Quick Overview
EC2 instance IDs in a placement group are consecutive integers from left to right inclusive. Return the bitwise AND of every ID in the range, which tells you which ID bits are shared by the entire group, without iterating over the range.
Amazon
November 29, 20260
0
0 solved
EC2 instance IDs in a placement group are consecutive integers from left to right inclusive. Return the bitwise AND of every ID in the range, which tells you which ID bits are shared by the entire group, without iterating over the range.
Asked in Amazon phone screens to test whether a candidate can reason about how bits change across consecutive integers. Looping over a range of up to 2^31 values times out, so the interviewer wants the common-prefix insight.
What the Interviewer Expects
- Recognizes that looping is too slow for large ranges
- Explains that any bit that flips inside the range becomes 0
- Finds the common binary prefix by shifting both ends
- Alternatively uses n & (n - 1) to drop low bits
- Handles left == right and left == 0
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
- Compute the bitwise OR of the range instead.
- What if the IDs are not consecutive but you get them as a list?
- How many bits does the loop run in the worst case?
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: integers 0 <= left <= right <= 2^31 - 1. Output: AND of all integers in [left, right]. The range can contain two billion numbers, so we need something proportional to the bit width....
High-Level Design
Counting upward, any bit below the highest position where left and right differ takes both values 0 and 1 somewhere in the range, so it is 0 in the AND. Bits above that position are identical across t...