#540

Single Element in a Sorted Array

Medium Pair parity

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

In a sorted array every value appears twice except one. Find the single one in O(log n) time and O(1) space.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: everything is in pairs except one; find it in O(log n).

Why this works: before the single element, pairs start at even indexes; after it, at odd ones. Check the pair at an even mid.

Example: [1, 1, 2, 3, 3, 4, 4, 8, 8]

mid 4 (3) pairs with index 5? (4) no → hi 4mid 2 (2) pairs with 3? (3) no → hi 2mid 0 (1) pairs with 1 ✓ → lo 2 → answer 2

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

XOR of everything — correct, but O(n), and the problem asks for O(log n).

Solve on LeetCode ↗
Complexity
  • Time: O(log n).
  • Space: O(1).
Topic: Binary Search
🎬 Episodes 21–23: video coming soon