Find the Index of the Large Integer - Problem

We have an integer array arr, where all the integers in arr are equal except for one integer which is larger than the rest of the integers.

You will not be given direct access to the array, instead, you will have an API ArrayReader which have the following functions:

  • int compareSub(int l, int r, int x, int y): where 0 <= l, r, x, y < ArrayReader.length(), l <= r and x <= y. The function compares the sum of sub-array arr[l..r] with the sum of the sub-array arr[x..y] and returns:
    • 1 if arr[l]+arr[l+1]+...+arr[r] > arr[x]+arr[x+1]+...+arr[y]
    • 0 if arr[l]+arr[l+1]+...+arr[r] == arr[x]+arr[x+1]+...+arr[y]
    • -1 if arr[l]+arr[l+1]+...+arr[r] < arr[x]+arr[x+1]+...+arr[y]
  • int length(): Returns the size of the array.

You are allowed to call compareSub() 20 times at most. You can assume both functions work in O(1) time.

Return the index of the array arr which has the largest integer.

Input & Output

Example 1 — Basic Case
$ Input: arr = [5,5,8,5,5]
Output: 2
💡 Note: The large integer 8 is at index 2. We can find it by comparing sums of subarrays.
Example 2 — Large at Start
$ Input: arr = [10,3,3,3]
Output: 0
💡 Note: The large integer 10 is at index 0. Binary search will narrow down to this position.
Example 3 — Large at End
$ Input: arr = [2,2,2,7]
Output: 3
💡 Note: The large integer 7 is at index 3. Right half will have larger sum in first comparison.

Constraints

  • 2 ≤ arr.length ≤ 5 * 105
  • 1 ≤ arr[i] ≤ 106
  • It is guaranteed that there is exactly one large integer in arr
  • You are allowed to call compareSub() at most 20 times

Visualization

Tap to expand
Find the Index of the Large Integer INPUT Array (hidden via API) 5 i=0 5 i=1 8 i=2 5 i=3 5 i=4 API Functions: compareSub(l,r,x,y) Returns: 1, 0, or -1 length() = 5 Input Values: arr = [5,5,8,5,5] Max 20 API calls allowed ALGORITHM STEPS 1 Binary Search Setup left=0, right=4 2 Divide into 3 parts Compare left vs right half [0..1] [2] [3..4] 3 Compare Sums compareSub(0,1,3,4) sum[0..1]=10, sum[3..4]=10 Result: 0 (equal) Large int must be at middle! 4 Identify Answer Middle element at index 2 Time: O(log n) | Calls: O(log n) FINAL RESULT 5 5 8 5 5 LARGEST Output: 2 [OK] Verified arr[2] = 8 is largest API Calls Used: 1 Within 20 call limit Key Insight: Use ternary search by dividing array into 3 parts. Compare sums of left and right halves: - If left > right: large integer is in left half. If right > left: large integer is in right half. - If equal: large integer is the middle element (odd length) or in middle section (even length). TutorialsPoint - Find the Index of the Large Integer | Optimal Solution
Asked in
Google 25 Facebook 18 Amazon 15
18.5K Views
Medium Frequency
~25 min Avg. Time
427 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen