Program to find sum of absolute differences in a sorted array in Python

Given a sorted array in non-decreasing order, we need to create a result array where each element contains the sum of absolute differences between that element and all other elements in the array.

For example, with nums = [5, 7, 12], the result will be [9, 7, 12] because:

  • |5−5| + |5−7| + |5−12| = 0+2+7 = 9
  • |7−5| + |7−7| + |7−12| = 2+0+5 = 7
  • |12−5| + |12−7| + |12−12| = 7+5+0 = 12

Naive Approach

The straightforward approach calculates absolute differences for each element ?

def solve_naive(nums):
    n = len(nums)
    result = []
    
    for i in range(n):
        total = 0
        for j in range(n):
            total += abs(nums[i] - nums[j])
        result.append(total)
    
    return result

nums = [5, 7, 12]
print(solve_naive(nums))
[9, 7, 12]

This approach has O(n²) time complexity, which is inefficient for large arrays.

Optimized Approach

Since the array is sorted, we can use mathematical optimization to achieve O(n) complexity ?

def solve(nums):
    result = []
    total_sum = 0
    n = len(nums)
    
    # Calculate sum for first element
    for i in range(1, n):
        total_sum += nums[i] - nums[0]
    result.append(total_sum)
    
    # Calculate sum for remaining elements using optimization
    for i in range(1, n):
        diff = nums[i] - nums[i-1]
        total_sum += diff * i
        total_sum -= diff * (n - i)
        result.append(total_sum)
    
    return result

nums = [5, 7, 12]
print(solve(nums))
[9, 7, 12]

How the Optimization Works

The key insight is that for a sorted array, when moving from nums[i-1] to nums[i]:

  • Elements to the left of i contribute positively: diff * i
  • Elements to the right of i contribute negatively: diff * (n-i)

Testing with Different Examples

# Test with different arrays
test_cases = [
    [1, 4, 6, 8, 10],
    [2, 3, 5],
    [1]
]

for nums in test_cases:
    result = solve(nums)
    print(f"Input: {nums}")
    print(f"Output: {result}")
    print()
Input: [1, 4, 6, 8, 10]
Output: [24, 15, 13, 15, 24]

Input: [2, 3, 5]
Output: [4, 3, 4]

Input: [1]
Output: [0]

Comparison

Approach Time Complexity Space Complexity Best For
Naive O(n²) O(1) Small arrays, easy understanding
Optimized O(n) O(1) Large arrays, production use

Conclusion

The optimized approach leverages the sorted property to calculate absolute differences efficiently in O(n) time. This mathematical optimization makes it suitable for large datasets while maintaining accuracy.

Updated on: 2026-03-26T14:13:08+05:30

602 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements