Count Server Pairs Whose ID XOR Falls in a Range
Last updated: November 29, 2026
Quick Overview
Given an array of non-negative integers and bounds low and high, count pairs i < j with low <= nums[i] XOR nums[j] <= high.
0
0
0 solved
Given an array of non-negative integers and bounds low and high, count pairs i < j with low <= nums[i] XOR nums[j] <= high.
A hard Google onsite bit problem. The interviewer checks the reduction from a range to two "less than" counts and a binary trie with subtree counts that answers "how many stored values y have x XOR y < limit" in one walk.
What the Interviewer Expects
- Reduce to f(high + 1) - f(low) where f(t) counts pairs with XOR below t
- Store subtree counts in a binary trie
- At each bit where the limit has a 1, add the count of the branch that keeps XOR's bit 0
- Insert each number after querying it to count only earlier elements
- Verify against brute force
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
- How would you count pairs with XOR exactly equal to k in linear time?
- How would you count pairs with XOR at least k?
- What changes for 64-bit values?
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: nums with values below 2^15 (or any fixed width), low <= high. Output: the number of index pairs i < j satisfying the inequality. Up to 2 x 10^4 elements, so O(n^2) is borderline an...
High-Level Design
Counting a range directly is awkward, so count pairs with XOR strictly less than t and subtract: answer = less(high + 1) - less(low). To count stored y with x ^ y < t, walk bits from the top. ...