Flip a specific bit in an integer
Company: Box
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Given a non-negative integer num and a zero-based bit position p, return the integer resulting from flipping only the bit at position p (i.e., 0 becomes 1, 1 becomes
0). Explain your approach and its time/space complexity.
Quick Answer: 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.
Given a non-negative integer `num` and a zero-based bit position `p`, return the integer that results from flipping ONLY the bit at position `p` (a `0` becomes `1`, a `1` becomes `0`). All other bits remain unchanged.
The bit at position `p` has place value 2^p. Flipping it is a classic application of the XOR operator: XOR-ing any bit with `1` toggles it, while XOR-ing with `0` leaves it unchanged. So building a mask with a single `1` at position `p` (`1 << p`) and XOR-ing it with `num` flips exactly that one bit.
Example: `num = 5` (binary `101`), `p = 1`. The mask `1 << 1` is `010`. `101 ^ 010 = 111 = 7`.
Return the resulting integer.
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.