Bitwise AND of Numbers Range

MediumBit Manipulationbit manipulation

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given two integers left and right with 0 <= left <= right. Return the result of applying bitwise AND to **every** integer in the inclusive range [left, right]. Looping over the range is far too slow when the range spans billions of values, so aim for O(log right) time.

Examples

Input: left = 5, right = 7
Output: 4
101 & 110 & 111 = 100, which is 4.
Input: left = 0, right = 0
Output: 0
The range holds only 0.
Input: left = 1, right = 2147483647
Output: 0
1 & 2 is already 0, and AND can never turn a bit back on.

Constraints

  • 0 <= left <= right <= 2^31 - 1

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More bit manipulation problems