Minimum Average Difference - Problem

You are given a 0-indexed integer array nums of length n.

The average difference of the index i is the absolute difference between the average of the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer.

Return the index with the minimum average difference. If there are multiple such indices, return the smallest one.

Note:

  • The absolute difference of two numbers is the absolute value of their difference.
  • The average of n elements is the sum of the n elements divided (integer division) by n.
  • The average of 0 elements is considered to be 0.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,5,3,9,5,3]
Output: 3
💡 Note: At index 3: left = [2,5,3,9] (avg=4), right = [5,3] (avg=4), difference = 0 (minimum possible)
Example 2 — Single Element
$ Input: nums = [0]
Output: 0
💡 Note: Only one element, so left avg = 0, right avg = 0 (no right elements), difference = 0
Example 3 — Two Elements
$ Input: nums = [2,8]
Output: 1
💡 Note: Index 0: left avg = 2, right avg = 8, diff = 6. Index 1: left avg = 5, right avg = 0, diff = 5. Choose index 1

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Minimum Average Difference INPUT nums array (length n=6) 0 1 2 3 4 5 2 5 3 9 5 3 Average Difference at i: |avg(nums[0..i]) - avg(nums[i+1..n-1])| Goal: Find index with minimum average difference Total sum = 27 n = 6 ALGORITHM STEPS 1 Calculate Total Sum totalSum = 2+5+3+9+5+3 = 27 2 Iterate with Prefix Sum Track running leftSum 3 Compute Avg Diff rightSum = total - leftSum 4 Track Minimum Update minIdx if smaller i leftAvg rightAvg diff 0 2/1=2 25/5=5 |3| 1 7/2=3 20/4=5 |2| 2 10/3=3 17/3=5 |2| 3 19/4=4 8/2=4 |0| MIN 4 24/5=4 3/1=3 |1| 5 27/6=4 0/0=0 |4| FINAL RESULT Minimum Average Difference at Index = 3 Diff = 0 2 5 3 9 5 3 Left [0..3] sum=19, avg=4 Right [4..5] sum=8, avg=4 Output: 3 OK - |4 - 4| = 0 (minimum) Time: O(n), Space: O(1) Key Insight: Use prefix sum to compute averages in O(1) time. At each index i, leftSum accumulates values, and rightSum = totalSum - leftSum. This avoids recalculating sums from scratch, reducing time complexity from O(n^2) to O(n). Handle edge case when right side is empty (division by 0). TutorialsPoint - Minimum Average Difference | Optimal Solution
Asked in
Amazon 12 Microsoft 8
32.0K Views
Medium Frequency
~15 min Avg. Time
850 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