Smallest Integer Greater Than p With No Consecutive 1s in Binary
Company: Airbnb
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Other
Overview: Given a non-negative integer p, find the smallest integer strictly greater than p whose binary representation has no two adjacent 1 bits. The problem tests bit manipulation, reasoning about binary carries, and finding a search fast enough for inputs up to one billion, along with an argument that it stays correct.
Constraints
- 0 <= p <= 10^9
- The answer is at most 2^30 = 1,073,741,824, so it fits in a signed 32-bit integer (int in Java and C++).
Examples
Input: (0,)
Expected Output: 1
Explanation: Smallest input: 1 (binary 1) is the first value above 0 and has no 11.
Input: (1,)
Expected Output: 2
Explanation: 2 is 10 in binary, so the first candidate already works.
Hints
- The answer must be larger than p even when p has no 11 of its own, so the first value worth checking is p + 1.
- p can be as large as 10^9, and the gap between p and the answer can exceed 2 * 10^8, so checking every integer after p one by one can be too slow.
- A power of two has a single 1 bit, so the answer never needs more than one bit beyond the binary length of p + 1.