Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: In an array where every element appears twice except one, and pairs sit next to each other, the array is sorted. Find the single element in O(log n).

Problem: In an array where every element appears twice except one, and pairs sit next to each other, the array is sorted. Find the single element in O(log n).
def single(a):
    lo, hi = 0, len(a) - 1
    while lo < hi:
        mid = (lo + hi) // 2
        if mid % 2 == 1:
            mid -= 1
        if a[mid] == a[mid + 1]:
            lo = mid + 2
        else:
            hi = mid
    return a[lo]
print(single([1, 1, 2, 3, 3, 4, 4, 8, 8]), single([3, 3, 7, 7, 10, 11, 11]))
What is printed?
  1. A. 3 10
  2. B. 2 11
  3. C. 8 10
  4. D. 2 10

Correct answer: D. 2 10

Before the single element, pairs start at even indices; after it they start at odd ones. Snap mid to even and test whether a[mid] == a[mid + 1]: if yes the single element is to the right. O(log n) versus O(n) for XOR.

More Coding Interview Problems questions

Exams that ask this topic