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?- A. 3 10
- B. 2 11
- C. 8 10
- 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
- Problem: Find a peak element (strictly greater than its neighbours; outside the array counts as −∞). Return its index. python def peak(a)…
- Problem: Return the k-th smallest element of the union of two sorted arrays (k is 1-based) in O(log(m + n)). python def kth(a, b, k): if…
- Problem: Reverse a singly linked list of order IDs. python class Node: def init(self, v, nxt=None): self.v, self.next = v, nxt def…
- Problem: Return the middle node of a linked list (the second middle when the length is even). python class Node: def init(self, v…
- Problem: Remove the k-th node from the end of a list in one pass. python class Node: def init(self, v, nxt=None): self.v, self.next = v…
- Problem: Merge two sorted linked lists into one sorted list. python class Node: def init(self, v, nxt=None): self.v, self.next = v, nxt…