Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Sum of Absolute Differences in a Sorted Array

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1685" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

You are given an integer array nums sorted in non-decreasing order. Build and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between nums[i] and all the other elements in the array. In other words, result[i] is equal to sum(|nums[i]-nums[j]|) where 0 <= j < nums.length and j != i (0-indexed). Example 1: Input: nums = [2,3,5] Output: [4,3,5] Explanation: Assuming the arrays are 0-indexed, then result[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4, result[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3, result[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5. Example 2: Input: nums = [1,4,6,8,10] Output: [24,15,13,15,21] Constraints: 2 <= nums.length <= 105 1 <= nums[i] <= nums[i + 1] <= 104

Explanation

Here's the breakdown of the approach, complexities, and the Python code:

  • Approach:

    • Utilize prefix and suffix sums to efficiently calculate the sum of absolute differences.
    • Iterate through the array, using the prefix sum to calculate the sum of differences with elements to the left, and the suffix sum for elements to the right.
    • Combine these sums to get the final result for each element.
  • Complexity:

    • Runtime Complexity: O(n)
    • Storage Complexity: O(n)

Code

    def sum_absolute_differences(nums):
    n = len(nums)
    result = [0] * n
    prefix_sum = [0] * n
    suffix_sum = [0] * n

    prefix_sum[0] = nums[0]
    for i in range(1, n):
        prefix_sum[i] = prefix_sum[i - 1] + nums[i]

    suffix_sum[n - 1] = nums[n - 1]
    for i in range(n - 2, -1, -1):
        suffix_sum[i] = suffix_sum[i + 1] + nums[i]

    for i in range(n):
        left_sum = 0
        if i > 0:
            left_sum = nums[i] * i - prefix_sum[i - 1]

        right_sum = 0
        if i < n - 1:
            right_sum = suffix_sum[i + 1] - nums[i] * (n - i - 1)

        result[i] = left_sum + right_sum

    return result

More from this blog

C

Chatmagic blog

2894 posts