Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find all elements that appear more than ⌊n/3⌋ times.
Problem: Find all elements that appear more than ⌊n/3⌋ times.
def over_third(a):
c1 = c2 = None; n1 = n2 = 0
for x in a:
if x == c1: n1 += 1
elif x == c2: n2 += 1
elif n1 == 0: c1, n1 = x, 1
elif n2 == 0: c2, n2 = x, 1
else: n1 -= 1; n2 -= 1
return sorted(c for c in {c1, c2} if c is not None and a.count(c) > len(a) // 3)
print(over_third([3, 2, 3]), over_third([1, 2, 3, 1, 2, 3, 1, 2]), over_third([4, 4, 5, 6, 7, 8, 9]))What is printed?- A. [3] [1, 2, 3] []
- B. [2, 3] [1, 2] [4]
- C. [3] [1, 2] []
- D. [3] [1, 2] [4]
Correct answer: C. [3] [1, 2] []
At most two values can exceed n/3, so keep two candidates with Boyer–Moore counters, then verify with a second pass. In the 8-element list 1 and 2 appear 3 times (> 2) but 3 only twice. In the last list 4 survives as a candidate but appears only 2 times, not more than ⌊7/3⌋ = 2, so verification rejects it. O(n), O(1).
More Coding Interview Problems questions
- Problem: Find the length of the shortest unsorted continuous subarray which, if sorted, makes the whole array sorted. python def…
- Problem: Compute the amount of rain water trapped between bars. python def trap(h): l, r = 0, len(h) - 1; lm = rm = water = 0 while l < r…
- Problem: Find the three numbers in an array whose sum is closest to a target. python def closest3(a, t): a.sort(); best = a[0] + a[1] +…
- Problem: Return all unique triplets that sum to zero. python def threesum(a): a.sort(); res = [] for i in range(len(a) - 2): if i and a[i]…
- Problem: Given n ≤ 10⁵ words, find the longest chain where each word is the previous word with exactly one letter inserted (word length ≤…
- Problem: A string of length n = 10⁵; answer q = 10⁵ queries 'are substrings [l1, r1] and [l2, r2] equal?'. Which technique fits?