645. Guess the Majority in a Hidden Array
Given an integer array nums, where each element is either 0 or 1. However, there is no direct access to the array. Instead,there is an API called ArrayReader, which provides the following methods:
- int query(int a, int b, int c, int d): Queries four distinct indices (a, b, c, d) such that 0 ≤ a < b < c < d < ArrayReader.length(). Returns one of the following values: 4: if all four elements are the same (all 0s or all 1s), 2: if three elements are the same and one is different and 0: if two elements are 0 and two are 1.
- int length(): Returns the size of the array.
There can be at most 2 * n calls to query(), where n is the size of the array.
The task is to find any index of the most frequently occurring value (0 or 1). If there is a tie between 0s and 1s, return -1. Since there can be multiple answers the output will be true if the index returned is correct, false otherwise.
Example 1:
Input: nums = [0,0,1,0,1,1,1,1]
Output: 5
Explanation: The following calls to the API
reader.length() // returns 8 because there are 8 elements in the hidden array.
reader.query(0,1,2,3) // returns 2 this is a query that compares the elements nums[0], nums[1], nums[2], nums[3]
// Three elements have a value equal to 0 and one element has value equal to 1 or vice versa.
reader.query(4,5,6,7) // returns 4 because nums[4], nums[5], nums[6], nums[7] have the same value.
We can infer that the most frequent value is found in the last 4 elements.
Index 2, 4, 6, 7 is also a correct answer.
Example 2:
Input: nums = [0,0,1,1,0]
Output: 0
Explanation: The following calls to the API
reader.length() // returns 5 because there are 5 elements in the hidden array.
reader.query(0,1,2,3) // returns 2, meaning two elements among nums[0], nums[1], nums[2], and nums[3] have the same value.
reader.query(1,2,3,4) // returns 2, indicating that two elements among nums[1], nums[2], nums[3], and nums[4] have the same value.
From these queries, we can infer that the most frequent value is 0.
Index 0 is one of the correct answers.
Now Your Turn!
Pick the correct output for the given inputInput: nums = [1,0,1,0,1,0,1,0]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 5 <= nums.length <= 105
- 0 <= nums[i] <= 1