COMPILED CANVAS
DSA IN JAVA

One line of XOR beats a HashMap

Bit tricks for coding interviews

Tap to start →

XOR

Pairs cancel out

int ans = 0; for (int x : nums) ans ^= x; // 4,1,2,1,2 → 4

x ^ x = 0. XOR all numbers and the one without a pair is left.

1 of 4 · keep tapping →
AND

Is it odd?

101

n & 1 is 1 for odd numbers, 0 for even.

2 of 4 · keep tapping →
SHIFT

Multiply by 2

5 → 10 → 20

Shifting left by 1 doubles a number. Shifting right halves it.

3 of 4 · keep tapping →
POWER OF 2

n & (n − 1)

8 & 7 = 0 ✓
6 & 5 = 4 ✗

It's 0 only when n is a power of two.

4 of 4 · keep tapping →
⚠ MOST PEOPLE MISS THIS

The mistake

Forgetting brackets: n & 1 == 0 is read as n & (1 == 0). Write (n & 1) == 0.

QUICK QUIZ

Can you get it?

Tap an answer. The full video explains why.

📸 SCREENSHOT THIS

Cheat sheet

  • x ^ x = 0
  • n & 1 → odd or even
  • Shift left = × 2
  • n & (n−1) = 0 → power of 2
  • Use brackets with &
COMPILED CANVAS

Want the full lesson?

▶ Watch the full videoPractice + free notes

Free DSA in Java course. Subscribe to Compiled Canvas on YouTube.

Watch the full video