#2256

Minimum Average Difference

Medium
ArrayPrefix SumPrefix SumArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

By using prefix sums, we can calculate the sums of the left and right segments in constant time, significantly reducing the number of operations needed.

⚙️

Algorithm

4 steps
  1. 1Step 1: Calculate the total sum of the array.
  2. 2Step 2: Initialize a prefix sum variable to keep track of the sum of elements from the start up to the current index.
  3. 3Step 3: For each index, calculate the left average using the prefix sum and the total sum for the right average.
  4. 4Step 4: Compute the absolute difference and track the minimum difference and its index.
solution.py18 lines
1# Full working Python code
2
3def minimumAverageDifference(nums):
4    n = len(nums)
5    total_sum = sum(nums)
6    prefix_sum = 0
7    min_diff = float('inf')
8    min_index = -1
9    for i in range(n):
10        prefix_sum += nums[i]
11        left_avg = prefix_sum // (i + 1)
12        right_avg = (total_sum - prefix_sum) // (n - i - 1) if n - i - 1 > 0 else 0
13        diff = abs(left_avg - right_avg)
14        if diff < min_diff:
15            min_diff = diff
16            min_index = i
17    return min_index
18

Complexity note: This complexity is O(n) because we traverse the array a constant number of times, and we use a fixed amount of extra space.

  • 1Using prefix sums allows for efficient average calculations.
  • 2Rounding down averages is crucial for accurate difference calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.