1114. Range Mode Counts

Hard7.5 points estimatedArraySortingHash Table3 hints

A library keeps books on one long shelf. The book at position i (counting from 0) belongs to the genre with id nums[i]. Visitors ask q questions, where question queries[i] = [a, b] covers every shelf position between a and b inclusive. The two ends may be given in either order, so the covered stretch is from min(a, b) to max(a, b).

For each question, find the genre that appears most often in the covered stretch and report how many books of that genre it contains. When several genres tie, the count is of course the same. Return an array answer where answer[i] is the reported count for queries[i].

Example 1

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

Positions 0..4 hold 3,1,3,2,3 so genre 3 appears 3 times; positions 5..7 are all genre 1 (3 books); positions 2..3 are 3 and 2, each once; positions 0..7 contain genre 1 four times.

Example 2

Input:
nums = [8,8,8,8], queries = [[1,2],[0,3],[3,3]]
Output:
[2,4,1]
Explanation:

Every stretch contains only genre 8, so the count equals the stretch length: 2, 4 and 1.

Example 3

Input:
nums = [5,6,7,8,9], queries = [[0,4],[2,2]]
Output:
[1,1]
Explanation:

All genres are different, so the most common genre appears just once in any stretch.

Constraints

1 ≤ nums.length ≤ 20000

0 ≤ nums[i] ≤ 109

1 ≤ queries.length ≤ 20000, each query is [a, b] with 0 ≤ a, b < nums.length

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

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

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…