Minimum Average Difference — LeetCode 2256 Python Solution

MediumArrayPrefix Sum
Problem
#2256
Pattern
Prefix Sum
Reading time
4 min

The 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.

Example

Input
nums = [2,5,3,9,5,3]
Output
3
Explanation
- The average difference of index 0 is: |2 / 1 - (5 + 3 + 9 + 5 + 3) / 5| = |2 / 1 - 25 / 5| = |2 - 5| = 3.

Python solution

Python
class Solution:
    def minimumAverageDifference(self, nums: List[int]) -> int:
        pre, suf = 0, sum(nums)
        n = len(nums)
        ans, mi = 0, inf
        for i, x in enumerate(nums):
            pre += x
            suf -= x
            a = pre // (i + 1)
            b = 0 if n - i - 1 == 0 else suf // (n - i - 1)
            if (t := abs(a - b)) < mi:
                ans = i
                mi = t
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array nums
SpaceO(1) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 2256. Minimum Average Difference is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2256. Minimum Average Difference?
LeetCode 2256. Minimum Average Difference is rated Medium on LeetCode.
What is the time complexity of LeetCode 2256. Minimum Average Difference?
The Python solution on this page runs in O(n), where n is the length of the array nums.
What is the space complexity of LeetCode 2256. Minimum Average Difference?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2256. Minimum Average Difference cover?
LeetCode 2256. Minimum Average Difference is tagged Array and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview