Guess the Number Using Bitwise Questions I - Problem

Imagine you're playing a digital guessing game where you need to find a hidden number n. However, instead of asking "Is it higher or lower?", you can only ask bitwise questions!

You have access to a special API function: int commonSetBits(int num)

This function tells you how many bit positions have 1s in both the hidden number n and your guess num. In other words, it returns the count of set bits in n & num (bitwise AND).

Your mission: Use this API strategically to discover the hidden number n.

Example: If the hidden number is n = 6 (binary: 110):
โ€ข commonSetBits(4) returns 1 because 6 & 4 = 110 & 100 = 100 (one set bit)
โ€ข commonSetBits(7) returns 2 because 6 & 7 = 110 & 111 = 110 (two set bits)

Input & Output

example_1.py โ€” Small Number
$ Input: Hidden number: 5 Binary representation: 101
โ€บ Output: 5
๐Ÿ’ก Note: Using bit-by-bit discovery: commonSetBits(1)=1 (bit 0 set), commonSetBits(2)=0 (bit 1 not set), commonSetBits(4)=1 (bit 2 set). Result: 101โ‚‚ = 5โ‚โ‚€
example_2.py โ€” Power of Two
$ Input: Hidden number: 8 Binary representation: 1000
โ€บ Output: 8
๐Ÿ’ก Note: Only commonSetBits(8) returns 1, all other powers of 2 return 0. This directly gives us 8.
example_3.py โ€” Edge Case Zero
$ Input: Hidden number: 0 Binary representation: 0
โ€บ Output: 0
๐Ÿ’ก Note: All calls to commonSetBits with any positive number return 0, indicating the target number is 0.

Visualization

Tap to expand
Digital SafeBinary Combination Lock1011Bit 3Bit 2Bit 1Bit 0Testing Processโœ“ Test bit 0: commonSetBits(1) = 1โœ“ Test bit 1: commonSetBits(2) = 0โœ“ Test bit 2: commonSetBits(4) = 1โœ“ Test bit 3: commonSetBits(8) = 1Result: 1101โ‚‚ = 13โ‚โ‚€UNLOCKED!
Understanding the Visualization
1
Test Position 1
Check if the first dial should be set to 1
2
Test Position 2
Check if the second dial should be set to 1
3
Continue Testing
Test each position systematically
4
Build Combination
Combine all discovered positions to get the final code
Key Takeaway
๐ŸŽฏ Key Insight: By testing individual bit positions with powers of 2, we can reconstruct any number using at most logโ‚‚(n) API calls instead of potentially n calls with brute force!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

We may need to test up to n numbers in the worst case, where n is the target value

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using a constant amount of extra space for variables

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค n โ‰ค 230
  • The hidden number is a positive integer
  • Interactive problem: You must call the API efficiently
  • Maximum 50 calls to commonSetBits allowed
Asked in
Google 25 Microsoft 18 Amazon 15 Meta 12
38.5K Views
Medium Frequency
~15 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen