LeetCode Problem

How to Solve Online Majority Element In Subarray

This problem requires implementing a data structure that quickly identifies the majority element within any given subarray. The key challenge is handling multiple queries efficiently without scanning the subarray each time. Techniques like binary search over possible candidate elements combined with segment trees or indexed frequency maps ensure queries run in sub-linear time, making the solution scalable for large arrays.

GhostInterview Help

Need help with Online Majority Element In Subarray without spending extra time grinding it?

GhostInterview can read Online Majority Element In Subarray from a screenshot, generate the answer path, explain the complexity, and support solver-first interview workflows when you need direct help fast.

Screenshot Input

Capture the prompt fast instead of rewriting the problem by hand.

Answer + Complexity

Get the solution path, trade-offs, and complexity summary in one pass.

Stealth Workflow

Stay outside captured layers on supported screen-share workflows.

Problem #1157Binary search over the valid answer spaceReviewed 2026-03-08
Difficulty
Hard
Primary pattern
Binary search over the valid answer space
Answer-first problem summary
Step-by-step approach and complexity
GhostInterview solver workflow

This problem requires implementing a data structure that quickly identifies the majority element within any given subarray. The key challenge is handling multiple queries efficiently without scanning the subarray each time. Techniques like binary search over possible candidate elements combined with segment trees or indexed frequency maps ensure queries run in sub-linear time, making the solution scalable for large arrays.

Problem Statement

You need to implement a class MajorityChecker that supports efficiently finding the majority element in a subarray. A majority element in a subarray is an element that occurs at least a given threshold number of times.

The class should support multiple queries of the form query(left, right, threshold) and return the majority element for that subarray, or -1 if no such element exists. Optimize your design to handle frequent online queries efficiently for arrays up to length 2 * 10^4.

Examples

Example 1

Input: See original problem statement.

Output: See original problem statement.

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 * 104
  • 1 <= arr[i] <= 2 * 104
  • 0 <= left <= right < arr.length
  • threshold <= right - left + 1
  • 2 * threshold > right - left + 1
  • At most 104 calls will be made to query.

Solution Approach

Preprocess the array by storing the positions of each distinct element. For each query, iterate over potential majority candidates and use binary search on their positions to count occurrences in the subarray. Return the candidate that meets the threshold.

Segment Tree for Candidate Queries

Build a segment tree where each node stores a potential majority element and its frequency. For a query, merge segment nodes and check if the candidate exceeds the threshold. This reduces redundant scanning of subarrays and supports fast range queries.

Random Sampling Optimization

For large subarrays, randomly sample elements and check their frequency within the range using precomputed positions. With multiple samples, the probability of missing the true majority element is low, providing a probabilistic but fast approach.

Complexity Analysis

MetricValue
TimeDepends on the final approach
SpaceDepends on the final approach

Time and space complexity depend on the approach: frequency maps with binary search give O(k log n) per query, segment trees give O(log n) per query, and random sampling achieves expected O(log n) with extra space for index maps.

What Interviewers Usually Probe

  • Can you handle multiple online queries efficiently without scanning each subarray?
  • What data structures allow you to count element frequencies quickly within a range?
  • How can binary search be applied over the candidate element positions to validate thresholds?

Common Pitfalls or Variants

Common pitfalls

  • Assuming a linear scan per query is fast enough for large arrays.
  • Forgetting that the majority element must meet the threshold, not just be most frequent.
  • Not handling the case when no element satisfies the threshold and returning -1 incorrectly.

Follow-up variants

  • Find the majority element for dynamic subarrays where elements can be updated between queries.
  • Return all elements that appear more than a fraction of the subarray size rather than a fixed threshold.
  • Optimize for streaming input where queries arrive in real time and the array is too large to store completely.

How GhostInterview Helps

  • Identifies which elements could be the majority candidate for each subarray quickly using preprocessed maps.
  • Suggests segment tree and binary search combinations to handle online queries efficiently.
  • Highlights the threshold verification step to avoid common mistakes when candidates do not meet the requirement.

Topic Pages

FAQ

What is the main strategy for Online Majority Element In Subarray?

The main strategy is to preprocess element positions and use binary search or segment trees to efficiently verify potential majority elements per query.

Can we solve this problem without extra space?

Not efficiently; tracking element occurrences with maps or trees is essential to support multiple fast queries.

Why is binary search over candidate positions used?

Binary search allows counting occurrences of a candidate in a subarray in logarithmic time, avoiding linear scans.

How does the threshold affect candidate selection?

Only elements that appear at least threshold times in the subarray are valid; all others are discarded during the query check.

Is random sampling a reliable approach here?

Yes, for large arrays it can efficiently detect the majority element with high probability, especially when combined with position maps.

GhostInterview Solver

Need direct help with Online Majority Element In Subarray instead of spending more time grinding it?

Download GhostInterview when you want a LeetCode solver, not another long practice loop. Capture Online Majority Element In Subarray from a screenshot, get the answer path and complexity, and use supported stealth workflows that stay outside captured layers.

Screenshot Input

Capture the prompt fast instead of rewriting the problem by hand.

Answer + Complexity

Get the solution path, trade-offs, and complexity summary in one pass.

Stealth Workflow

Stay outside captured layers on supported screen-share workflows.