Flip a specific bit in an integer
Company: Box
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: This question evaluates a candidate's understanding of bitwise operations and low-level integer manipulation, along with the ability to reason about the time and space complexity of bit-level operations.
Read the full Box Software Engineer interview experience this question came from
Constraints
- 0 <= num (non-negative integer)
- 0 <= p (zero-based bit position)
- Flipping a bit at a position beyond num's highest set bit simply sets that bit to 1.
- Python integers are arbitrary-precision, so very large p values are handled natively.
Examples
Input: (5, 0)
Expected Output: 4
Explanation: 5 is 101. Bit 0 is 1, so it clears to 0: 100 = 4.
Input: (5, 1)
Expected Output: 7
Explanation: 5 is 101. Bit 1 is 0, so it sets to 1: 111 = 7.
Hints
- Which bitwise operator toggles a bit: AND, OR, or XOR? Recall that x ^ 1 = NOT x and x ^ 0 = x.
- Build a mask with a single 1 at position p using a left shift: 1 << p.
- XOR the number with that mask: num ^ (1 << p). This flips only the targeted bit and leaves every other bit untouched, in O(1) time and space.