Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: In a sorted array every value appears twice except one. Find it in O(log n) using index parity.

Problem: In a sorted array every value appears twice except one. Find it in O(log n) using index parity.
def single(a):
    lo, hi = 0, len(a) - 1
    while lo < hi:
        m = (lo + hi) // 2
        if m % 2: m -= 1
        if a[m] == a[m + 1]: lo = m + 2
        else: hi = m
    return a[lo]
print(single([1, 1, 3, 3, 5, 7, 7, 9, 9]))
What is printed?
  1. A. 7
  2. B. 9
  3. C. 3
  4. D. 5

Correct answer: D. 5

Before the single element, pairs start at even indices; after it, at odd indices. Checking a[m] == a[m+1] at an even m tells which side the single value is on: the search narrows to index 4, value 5.

More Coding Interview Problems questions

Exams that ask this topic