# The Single Bit

> One particular pattern hides in plain sight.

Canonical URL: <https://datadriven.io/problems/the_single_bit>

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Given an integer, return True if it is a positive power of 2 (1, 2, 4, 8, 16, ...). Use bitwise operations: (n > 0) AND (n & (n - 1)) == 0.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **bitwise operations** and understanding of binary representation. Powers of two have exactly one bit set, and the classic `n & (n - 1)` trick clears the lowest set bit, making it a single-operation check.

> **Trick to Solving**
>
> A positive power of two in binary is a single 1 followed by zeros (e.g., 8 = `1000`). Subtracting 1 flips all bits below that 1 (e.g., 7 = `0111`). The AND of these two values is always 0 for powers of two.

---

### Break down the requirements

#### Step 1: Guard against non-positive inputs

Zero and negative numbers are not powers of two. Check `n > 0` first.

#### Step 2: Apply the bit trick

Compute `n & (n - 1)`. If the result is 0, n has exactly one bit set and is a power of two.

---

### The solution

**Single-bit check with AND trick**

```python
def is_power_of_two(n: int) -> bool:
    if n <= 0:
        return False
    result = (n & (n - 1)) == 0
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(1). A single bitwise AND and comparison.
> 
> **Space:** O(1). No additional data structures.

> **Interviewers Watch For**
>
> Can you explain WHY `n & (n - 1)` works? Candidates who memorize the trick without understanding the binary mechanics get follow-up probes.

> **Common Pitfall**
>
> Forgetting the `n > 0` guard. Zero satisfies `0 & (-1) == 0` in Python, but zero is not a power of two.

---

## Common follow-up questions

- How would you find the position of the set bit? _(Tests knowledge of bit shifting or `n.bit_length()`.)_
- What if you needed to check if a number is a power of 4? _(Tests extending the bit trick: power of 4 means one bit set at an even position.)_
- How does this apply in memory allocators? _(Tests real-world awareness: allocators align to power-of-two boundaries for efficiency.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_single_bit)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.