Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Binary search

The one value without a partner

Medium · Target 15 minutes · Binary search · Type asked atOptiverGoogleMicrosoft

A sorted array contains every value exactly twice, except one value that appears once. Return that value in O(log n) time and O(1) extra space.

Examples

InputOutputWhy
a = [1, 1, 2, 3, 3, 4, 4, 8, 8]2
a = [3, 3, 7, 7, 10, 11, 11]10
a = [5]5

Constraints

  • 1 ≤ n ≤ 10⁵, n odd
  • −10⁵ ≤ a[i] ≤ 10⁵
  • a is sorted

Hints

Hint 1

XOR of everything finds the value in O(n). What does sortedness add?

Hint 2

Look at the indices of each pair before the single value, and after it. Which index does each pair start on?

Hint 3

Before the single value, a pair starts at an even index i with a[i] = a[i + 1]. From the single value on, that fails. Search for the first even index where a[i] ≠ a[i + 1].

Where people lose marks

  • Testing odd values of mid against mid + 1, which compares the second element of one pair with the first of the next.
  • Reading a[mid + 1] when mid = n − 1. With hi = n − 1 and mid made even and below hi, it never happens.
  • Returning the index rather than the value.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.