Find the Index of the Large Integer - Problem
Imagine you're a detective trying to find the one special number in a hidden array! ๐ต๏ธโโ๏ธ
You have access to an integer array arr where all numbers are identical except for one integer that's larger than the rest. However, there's a catch - you can't directly access the array elements!
Instead, you have a special ArrayReader API with two powerful functions:
compareSub(l, r, x, y): Compares the sum of subarrayarr[l..r]with subarrayarr[x..y]
Returns: 1 if left sum > right sum, 0 if equal, -1 if left sum < right sumlength(): Returns the array size
Challenge: Find the index of the largest integer using at most 20 API calls! โก
Goal: Return the index where the special (largest) number is hiding.
Input & Output
example_1.py โ Basic Case
$
Input:
arr = [5, 5, 8, 5, 5] (hidden array)
โบ
Output:
2
๐ก Note:
The array has all 5s except index 2 which has 8. The algorithm compares subarrays to locate this larger element efficiently.
example_2.py โ Edge Position
$
Input:
arr = [7, 3, 3, 3] (hidden array)
โบ
Output:
0
๐ก Note:
The larger element is at the beginning. Binary search will compare left half [7,3] with right half [3,3], find left half has larger sum, then narrow down to index 0.
example_3.py โ Single Element
$
Input:
arr = [10] (hidden array)
โบ
Output:
0
๐ก Note:
With only one element, it must be the largest (and only) element, so return index 0.
Visualization
Tap to expand
Understanding the Visualization
1
Divide the Coins
Split all coins into two equal groups and place them on opposite sides of the balance scale
2
Compare Groups
The scale tips toward the side with the gold coin, revealing which group contains our target
3
Eliminate & Focus
Discard the lighter group and focus only on the heavier group that contains the gold coin
4
Repeat Process
Continue dividing the remaining group until only one coin remains - that's our gold coin!
Key Takeaway
๐ฏ Key Insight: By comparing group sums instead of individual elements, we can eliminate half the search space with each comparison, guaranteeing we find the target within log(n) steps - well within our 20 API call limit!
Time & Space Complexity
Time Complexity
O(n)
In worst case, we need to check each element once
โ Linear Growth
Space Complexity
O(1)
Only using constant extra space for variables
โ Linear Space
Constraints
- 1 โค arr.length โค 105
- All integers in arr are equal except for one integer which is larger
-
You can call
compareSub()at most 20 times - 0 โค l, r, x, y < arr.length where l โค r and x โค y
- ArrayReader functions work in O(1) time
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code