#1157

Online Majority Element In Subarray

Hard
ArrayBinary SearchDesignBinary Indexed TreeSegment TreeHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + q log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n + q log n)Space O(n)

Using a combination of a hashmap and a binary search approach allows us to efficiently count occurrences and quickly find majority elements in subarrays.

⚙️

Algorithm

3 steps
  1. 1Step 1: Preprocess the array to create a hashmap that stores the indices of each element.
  2. 2Step 2: For each query, use binary search to find the leftmost and rightmost indices of the queried element within the specified range.
  3. 3Step 3: Count the occurrences of the element using the indices and check if it meets the threshold.
solution.py18 lines
1from collections import defaultdict
2from bisect import bisect_left, bisect_right
3
4class MajorityChecker:
5    def __init__(self, arr):
6        self.arr = arr
7        self.indices = defaultdict(list)
8        for i, num in enumerate(arr):
9            self.indices[num].append(i)
10
11    def query(self, left, right, threshold):
12        for num in self.indices:
13            indices = self.indices[num]
14            left_index = bisect_left(indices, left)
15            right_index = bisect_right(indices, right) - 1
16            if right_index - left_index + 1 >= threshold:
17                return num
18        return -1

Complexity note: The preprocessing step takes O(n) to build the index map, and each query takes O(log n) for binary search, leading to an overall complexity of O(n + q log n).

  • 1A majority element appears more than half the time in a subset, which can be leveraged for efficient searching.
  • 2Using data structures like maps and binary search can significantly reduce the time complexity for repeated queries.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.