Problem Description
Given an API interface to an integer array where every element is equal except one large integer, find the index of that large integer. You cannot access the array directly but must use the provided API functions: compareSub(l, r, x, y) to compare the sums of two subarrays, and length() to obtain the size of the array. You are allowed to call compareSub at most 20 times.
Key Insights
- Use binary search to efficiently narrow down the position of the unique large value.
- At each step, divide the candidate range into two halves (or almost two halves when the range size is odd) and use compareSub to determine which half contains the large integer.
- Comparing two subarrays of equal length will reveal the region that contains the extra value via the sum difference.
- Handle odd-length ranges carefully by isolating the middle element if needed.
Space and Time Complexity
Time Complexity: O(log n) – because binary search is performed over the range. Space Complexity: O(1) – only a few pointers are maintained, no additional space is required.
Solution
The solution applies a binary search approach over the array indices. At every iteration:
- Calculate the current segment length.
- If the length is even, split the segment evenly and compare the left half versus the right half using compareSub.
- If the length is odd, compare two halves of equal size while ignoring the middle element. If the sums are equal, then the middle index holds the large value.
- Update the search bounds based on the result of compareSub.
- Continue until the search space is reduced to one index, which is the answer.
This method ensures that you locate the large integer with O(log n) calls to compareSub, well within the limit of 20 calls.