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?- A. 7
- B. 9
- C. 3
- 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
- Problem: Split an array into contiguous parts of length at most k; every element of a part becomes that part's maximum. Maximise the final…
- Problem: Build a binary tree whose leaves (in order) are the array values; each internal node's value is (max leaf on its left) × (max…
- Problem: Longest arithmetic subsequence (not necessarily contiguous) using a dictionary of (difference → length) per index. python def…
- Problem: Count all square submatrices made entirely of 1s. python def count(m): R, C = len(m), len(m[0]); tot = 0 dp = [row[:] for row in…
- Problem: Paint n fence posts with k colours so that no three consecutive posts share a colour. python def ways(n, k): same, diff = 0, k…
- Problem: A pointer starts at index 0 of an array of length n; each step it moves left, right or stays (never leaving the array). Count the…