Data Structures & AlgorithmsVery hardProduct company OA
Boyer–Moore majority vote WITHOUT the verification pass, returning (candidate, final counter). What is printed?
Boyer–Moore majority vote WITHOUT the verification pass, returning (candidate, final counter). What is printed?
def vote(a):
cand, cnt = None, 0
for x in a:
if cnt == 0: cand = x
cnt += 1 if x == cand else -1
return cand, cnt
print(vote([2, 2, 1, 3, 1, 1, 4, 1, 1]), vote([1, 2, 3, 1, 2, 3, 3]), vote([5, 5, 6, 6, 7]))- A. (1, 3) (3, 0) (7, 1)
- B. (1, 1) (3, 1) (5, 1)
- C. (2, 3) (3, 1) (7, 1)
- D. (1, 3) (3, 1) (7, 1)
Correct answer: D. (1, 3) (3, 1) (7, 1)
The vote cancels pairs of different values, so a TRUE majority (> n/2) always survives as the candidate – [2,2,1,3,1,1,4,1,1] gives 1 with net 3. But when no majority exists the survivor is arbitrary: [1,2,3,1,2,3,3] yields 3 although it occurs 3/7 times, and [5,5,6,6,7] yields 7, which occurs once. So a second O(n) counting pass is mandatory before reporting a majority. O(1) space.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Inversions counted during merge sort (pairs i < j with a[i] > a[j]). What is printed? python def inv(a): if len(a) <= 1: return a, 0 m =…
- One Hoare partition with the FIRST element (6) as pivot. What is printed (array after the partition, returned index)? python def hoare(a)…
- Counting palindromic substrings (by position) with centre expansion over 2n − 1 centres. What is printed? python def pal(s): c = 0 for…
- Sum over all subarrays of (max − min), computed as Σ max − Σ min with two monotonic-stack passes, checked against brute force. What is…
- Merging files costs the size of the result each time. Compare the greedy 'always merge the two smallest' (heap) with merging left to right…
- You must count pairs i < j with a[i] + a[j] ≤ T for n ≤ 2·10⁵ values up to 10⁹ in absolute value (time limit 1 s). Which plan passes?