Online Majority Element In Subarray - Problem

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.

Implement the MajorityChecker class:

  • MajorityChecker(int[] arr) - Initializes the instance of the class with the given array arr.
  • int query(int left, int right, int threshold) - Returns the element in the subarray arr[left...right] that occurs at least threshold times, or -1 if no such element exists.

Input & Output

Example 1 — Basic Majority Check
$ Input: arr = [1,1,2,2,1,1], queries = [[0,5,4],[0,3,3],[2,3,2]]
Output: [1,-1,2]
💡 Note: Query [0,5,4]: Element 1 appears 4 times in full array (≥4). Query [0,3,3]: No element appears ≥3 times in [1,1,2,2]. Query [2,3,2]: Element 2 appears 2 times in [2,2] (≥2).
Example 2 — No Majority Found
$ Input: arr = [1,2,3,4,5], queries = [[0,4,3]]
Output: [-1]
💡 Note: In range [0,4], each element [1,2,3,4,5] appears only once, none meet threshold 3.
Example 3 — Small Range
$ Input: arr = [3,3,3], queries = [[0,2,2]]
Output: [3]
💡 Note: Element 3 appears 3 times in range [0,2], which is ≥ threshold 2.

Constraints

  • 1 ≤ arr.length ≤ 2 × 104
  • 1 ≤ arr[i] ≤ 2 × 104
  • 0 ≤ left ≤ right < arr.length
  • threshold ≤ right - left + 1
  • 1 ≤ queries ≤ 104

Visualization

Tap to expand
Online Majority Element: Find elements with count ≥ thresholdArray: [1, 1, 2, 2, 1, 1]112211Query: range [0,5], threshold = 4Find elements appearing ≥ 4 timesElement 1: count = 4 ✓Result: 1 (majority element found)
Understanding the Visualization
1
Input
Array [1,1,2,2,1,1] and queries [[0,5,4]]
2
Process
Check if any element appears ≥ threshold times in range
3
Output
Return the majority element or -1
Key Takeaway
🎯 Key Insight: Random sampling makes majority detection extremely efficient since true majorities have high probability of being discovered quickly.
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
23.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen