Online Majority Element In Subarray Problem
Description
LeetCode Problem 1157.
Design a data structure that efficiently finds the majority element of a given subarray.
The majority element of a subarray is an element that occurs threshold times or more in the subarray.
Implementing the MajorityChecker class:
MajorityChecker(int[] arr)Initializes the instance of the class with the given arrayarr.int query(int left, int right, int threshold)returns the element in the subarrayarr[left...right]that occurs at leastthresholdtimes, or-1if no such element exists.
Example 1:
Input
["MajorityChecker", "query", "query", "query"]
[[[1, 1, 2, 2, 1, 1]], [0, 5, 4], [0, 3, 3], [2, 3, 2]]
Output
[null, 1, -1, 2]
Explanation
MajorityChecker majorityChecker = new MajorityChecker([1, 1, 2, 2, 1, 1]);
majorityChecker.query(0, 5, 4); // return 1
majorityChecker.query(0, 3, 3); // return -1
majorityChecker.query(2, 3, 2); // return 2
Constraints:
1 <= arr.length <= 2 * 10^41 <= arr[i] <= 2 * 10^40 <= left <= right < arr.lengththreshold <= right - left + 12 * threshold > right - left + 1- At most
10^4calls will be made toquery.
Solution
Approach: Segment Tree of Boyer-Moore Votes + Binary Search
Because 2 * threshold > right - left + 1, the answer, if there is one, is a strict majority of the subarray. That brings in the Boyer-Moore voting idea: pair up different elements and cancel them; a strict majority can never be cancelled completely, so it is the element that survives. The survivor is only a candidate, though: it still has to be checked.
The useful property is that votes can be merged. Summarize a range by a pair (candidate, surplus), where surplus is how many copies of the candidate are left after cancelling. Two neighboring ranges (x, a) and (y, b) combine into:
(x, a + b)ifx == y,- otherwise the larger side wins and loses as many copies as the other side had:
(x, a - b)ifa >= b, else(y, b - a).
So we build a segment tree where every node stores the pair for its range. A query merges the O(log n) nodes that cover [left, right] and gets the candidate x of the subarray.
To check the candidate, we keep for each value the sorted list of indices where it appears. Two binary searches give how many of them lie in [left, right]. If that count is at least threshold, return x; otherwise no element qualifies (a majority would have been the candidate), so return -1.
Complexity: O(n) time to build and O(log n) per query. O(n) space for the tree and the index lists.
from bisect import bisect_left
from collections import defaultdict
def merge(a, b):
"""Combine two Boyer-Moore (candidate, surplus) pairs."""
if a[0] == b[0]:
return (a[0], a[1] + b[1])
if a[1] >= b[1]:
return (a[0], a[1] - b[1])
return (b[0], b[1] - a[1])
class MajorityChecker:
def __init__(self, arr: List[int]):
self.n = len(arr)
self.arr = arr
# Segment tree: node u covers a range and stores its (candidate, surplus) pair.
self.tree = [(0, 0)] * (4 * self.n)
self._build(1, 0, self.n - 1)
# positions[x]: sorted indices where x occurs, to count x in any range.
self.positions = defaultdict(list)
for i, x in enumerate(arr):
self.positions[x].append(i)
def _build(self, u: int, lo: int, hi: int) -> None:
if lo == hi:
self.tree[u] = (self.arr[lo], 1)
return
mid = (lo + hi) // 2
self._build(2 * u, lo, mid)
self._build(2 * u + 1, mid + 1, hi)
self.tree[u] = merge(self.tree[2 * u], self.tree[2 * u + 1])
def _query(self, u: int, lo: int, hi: int, left: int, right: int):
if left <= lo and hi <= right:
return self.tree[u]
mid = (lo + hi) // 2
if right <= mid:
return self._query(2 * u, lo, mid, left, right)
if left > mid:
return self._query(2 * u + 1, mid + 1, hi, left, right)
return merge(self._query(2 * u, lo, mid, left, right),
self._query(2 * u + 1, mid + 1, hi, left, right))
def query(self, left: int, right: int, threshold: int) -> int:
# The only element that can be a majority of the range is its Boyer-Moore candidate.
x = self._query(1, 0, self.n - 1, left, right)[0]
pos = self.positions[x]
count = bisect_left(pos, right + 1) - bisect_left(pos, left)
return x if count >= threshold else -1