LeetCode #3636 — HARD

Threshold Majority Queries

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

You are given an integer array nums of length n and an array queries, where queries[i] = [li, ri, thresholdi].

Return an array of integers ans where ans[i] is equal to the element in the subarray nums[li...ri] that appears at least thresholdi times, selecting the element with the highest frequency (choosing the smallest in case of a tie), or -1 if no such element exists.

Example 1:

Input: nums = [1,1,2,2,1,1], queries = [[0,5,4],[0,3,3],[2,3,2]]

Output: [1,-1,2]

Explanation:

Query Sub-array Threshold Frequency table Answer
[0, 5, 4] [1, 1, 2, 2, 1, 1] 4 1 → 4, 2 → 2 1
[0, 3, 3] [1, 1, 2, 2] 3 1 → 2, 2 → 2 -1
[2, 3, 2] [2, 2] 2 2 → 2 2

Example 2:

Input: nums = [3,2,3,2,3,2,3], queries = [[0,6,4],[1,5,2],[2,4,1],[3,3,1]]

Output: [3,2,3,2]

Explanation:

Query Sub-array Threshold Frequency table Answer
[0, 6, 4] [3, 2, 3, 2, 3, 2, 3] 4 3 → 4, 2 → 3 3
[1, 5, 2] [2, 3, 2, 3, 2] 2 2 → 3, 3 → 2 2
[2, 4, 1] [3, 2, 3] 1 3 → 2, 2 → 1 3
[3, 3, 1] [2] 1 2 → 1 2

Constraints:

  • 1 <= nums.length == n <= 104
  • 1 <= nums[i] <= 109
  • 1 <= queries.length <= 5 * 104
  • queries[i] = [li, ri, thresholdi]
  • 0 <= li <= ri < n
  • 1 <= thresholdi <= ri - li + 1
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given an integer array nums of length n and an array queries, where queries[i] = [li, ri, thresholdi]. Return an array of integers ans where ans[i] is equal to the element in the subarray nums[li...ri] that appears at least thresholdi times, selecting the element with the highest frequency (choosing the smallest in case of a tie), or -1 if no such element exists.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Hash Map · Binary Search

Example 1

[1,1,2,2,1,1]
[[0,5,4],[0,3,3],[2,3,2]]

Example 2

[3,2,3,2,3,2,3]
[[0,6,4],[1,5,2],[2,4,1],[3,3,1]]
Step 02

Core Insight

What unlocks the optimal approach

  • Use sqrt decomposition: let <code>B = int(sqrt(n))</code> and sort queries by <code>(l//B, r)</code>
  • Maintain window <code>[L,R]</code> with a frequency map <code>cnt</code> and buckets <code>bucket[f]</code> of values at count <code>f</code>
  • Slide <code>L</code> and <code>R</code> per query, updating <code>cnt</code> and <code>bucket</code>, then scan from <code>threshold</code> to max freq to find the smallest valid value or -1
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3636: Threshold Majority Queries
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3636: Threshold Majority Queries
// package main
// 
// import (
// 	"cmp"
// 	"math"
// 	"slices"
// 	"sort"
// )
// 
// // https://space.bilibili.com/206214
// func subarrayMajority(nums []int, queries [][]int) []int {
// 	n, m := len(nums), len(queries)
// 
// 	a := slices.Clone(nums)
// 	slices.Sort(a)
// 	a = slices.Compact(a)
// 	indexToValue := make([]int, n)
// 	for i, x := range nums {
// 		indexToValue[i] = sort.SearchInts(a, x)
// 	}
// 
// 	cnt := make([]int, len(a)+1)
// 	maxCnt, minVal := 0, 0
// 	add := func(i int) {
// 		v := indexToValue[i]
// 		cnt[v]++
// 		c := cnt[v]
// 		x := nums[i]
// 		if c > maxCnt {
// 			maxCnt, minVal = c, x
// 		} else if c == maxCnt {
// 			minVal = min(minVal, x)
// 		}
// 	}
// 
// 	ans := make([]int, m)
// 	blockSize := int(math.Ceil(float64(n) / math.Sqrt(float64(m*2))))
// 	type query struct{ bid, l, r, threshold, qid int } // [l,r) 左闭右开
// 	qs := []query{}
// 	for i, q := range queries {
// 		l, r, threshold := q[0], q[1]+1, q[2] // 左闭右开
// 		// 大区间离线(保证 l 和 r 不在同一个块中)
// 		if r-l > blockSize {
// 			qs = append(qs, query{l / blockSize, l, r, threshold, i})
// 			continue
// 		}
// 		// 小区间暴力
// 		for j := l; j < r; j++ {
// 			add(j)
// 		}
// 		if maxCnt >= threshold {
// 			ans[i] = minVal
// 		} else {
// 			ans[i] = -1
// 		}
// 		// 重置数据
// 		for _, v := range indexToValue[l:r] {
// 			cnt[v]--
// 		}
// 		maxCnt = 0
// 	}
// 
// 	slices.SortFunc(qs, func(a, b query) int { return cmp.Or(a.bid-b.bid, a.r-b.r) })
// 
// 	var r int
// 	for i, q := range qs {
// 		l0 := (q.bid + 1) * blockSize
// 		if i == 0 || q.bid > qs[i-1].bid { // 遍历到一个新的块
// 			r = l0 // 右端点移动的起点
// 			// 重置数据
// 			clear(cnt)
// 			maxCnt = 0
// 		}
// 
// 		// 右端点从 r 移动到 q.r(q.r 不计入)
// 		for ; r < q.r; r++ {
// 			add(r)
// 		}
// 
// 		// 左端点从 l0 移动到 q.l(l0 不计入)
// 		tmpMaxCnt, tmpMinVal := maxCnt, minVal
// 		for l := q.l; l < l0; l++ {
// 			add(l)
// 		}
// 		if maxCnt >= q.threshold {
// 			ans[q.qid] = minVal
// 		} else {
// 			ans[q.qid] = -1
// 		}
// 
// 		// 回滚
// 		maxCnt, minVal = tmpMaxCnt, tmpMinVal
// 		for _, v := range indexToValue[q.l:l0] {
// 			cnt[v]--
// 		}
// 	}
// 	return ans
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(log n)
Space
O(1)

Approach Breakdown

LINEAR SCAN
O(n) time
O(1) space

Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.

BINARY SEARCH
O(log n) time
O(1) space

Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).

Shortcut: Halving the input each step → O(log n). Works on any monotonic condition, not just sorted arrays.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.

Mutating counts without cleanup

Wrong move: Zero-count keys stay in map and break distinct/count constraints.

Usually fails on: Window/map size checks are consistently off by one.

Fix: Delete keys when count reaches zero.

Boundary update without `+1` / `-1`

Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.

Usually fails on: Two-element ranges never converge.

Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.