Guess the Majority in a Hidden Array - Problem
We have an integer array nums, where all the integers in nums are 0 or 1. You will not be given direct access to the array, instead, you will have an API ArrayReader which have the following functions:
int query(int a, int b, int c, int d): where0 <= a < b < c < d < ArrayReader.length(). The function returns the distribution of the value of the 4 elements and returns:- 4: if the values of the 4 elements are the same (0 or 1).
- 2: if three elements have a value equal to 0 and one element has value equal to 1 or vice versa.
- 0: if two element have a value equal to 0 and two elements have a value equal to 1.
int length(): Returns the size of the array.
You are allowed to call query() 2 * n times at most where n is equal to ArrayReader.length(). Return any index of the most frequent value in nums, in case of tie, return -1.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,1,0,1,0] (hidden)
›
Output:
0
💡 Note:
Array has three 1s and two 0s. Since 1 appears more frequently, return any index containing 1, such as index 0.
Example 2 — Tie Case
$
Input:
nums = [1,0,1,0] (hidden)
›
Output:
-1
💡 Note:
Array has equal numbers of 0s and 1s (2 each). Since there's a tie, return -1.
Example 3 — Majority Zeros
$
Input:
nums = [0,0,0,1,1] (hidden)
›
Output:
0
💡 Note:
Array has three 0s and two 1s. Since 0 appears more frequently, return any index containing 0, such as index 0.
Constraints
- 4 ≤ nums.length ≤ 105
- nums[i] is either 0 or 1
- You can call query() at most 2 * n times
Visualization
Tap to expand
Understanding the Visualization
1
Hidden Array
Array [1,1,0,1,0] is hidden, only query() is available
2
Strategic Queries
Use overlapping 4-element queries to gather information
3
Find Majority
Determine that 1 appears 3 times (majority), return index 0
Key Takeaway
🎯 Key Insight: Use overlapping queries to mathematically deduce element values and find the majority without direct array access
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code