Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find the element that appears more than n/2 times (guaranteed to exist) using Boyer–Moore voting.
Problem: Find the element that appears more than n/2 times (guaranteed to exist) using Boyer–Moore voting.
static int majority(int[] a) {
int cand = 0, cnt = 0;
for (int x : a) {
if (cnt == 0) cand = x;
cnt += (x == cand) ? 1 : -1;
}
return cand;
}
// majority({2, 2, 1, 1, 1, 2, 2}) + " " + majority({1, 3, 1, 3, 3})What does the commented expression evaluate to?- A. 1 3
- B. 2 3
- C. 2 1
- D. 1 1
Correct answer: B. 2 3
Pair off different values; the majority survives the cancellations. {2,2,1,1,1,2,2}: the candidate switches to 1 at index 4, then back to 2 at index 6 → 2. O(n), O(1). Without the guarantee a second pass must verify the count.
More Coding Interview Problems questions
- Problem: Sort an array of 0s, 1s and 2s in one pass (Dutch national flag). cpp void sort012(vector<int>& a) { int lo = 0, mid = 0, hi =…
- Problem: Find the next lexicographic permutation of a digit list in place. python def nextperm(a): i = len(a) - 2 while i >= 0 and a[i] >=…
- Problem: Count pairs of songs whose total duration is divisible by 60. python def pairs60(t): cnt = [0] 60; res = 0 for x in t: r = x % 60…
- Problem: Find the length of the longest subarray with equal numbers of 0s and 1s. python def longesteq(a): first = {0: -1}; bal = best = 0…
- Problem: Find all elements that appear more than ⌊n/3⌋ times. python def overthird(a): c1 = c2 = None; n1 = n2 = 0 for x in a: if x == c1…
- Problem: Find the length of the shortest unsorted continuous subarray which, if sorted, makes the whole array sorted. python def…