Skip to main content
LeetCode 1538, Medium. Topics: Array, Math, Interactive. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 28 parametrized pytest cases, and a playground notebook:

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 has the following functions:
  • int query(int a, int b, int c, int d): where 0 <= a < b < c < d < ArrayReader.length(). The function returns the distribution of the value of the 4 elements:
    • 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 elements 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.

Examples

Constraints

  • 5 <= nums.length <= 10^5
  • 0 <= nums[i] <= 1
Follow up: What is the minimum number of calls needed to find the majority element?

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026