Sum of Absolute Differences in a Sorted Array

Advanced

Sum of Absolute Differences in a Sorted Array

Hello Coding Explorers! 🕵️‍♀️✨ Today, let's have a little fun with numbers. Your challenge is to write a function that computes the sum of the absolute differences between each pair of numbers in a sorted array. This might sound complicated, but don’t worry; we’ll break it down together!

What's the Challenge?

You have a sorted list of numbers, and we want you to calculate the total "distance" between all numbers in this list. By "distance," we mean the absolute difference between each pair of numbers in the list. This can be a fun exercise to practice your number-crunching and problem-solving skills!

The Challenge Explained!

Imagine we have a list like [1, 3, 6, 10]. The absolute differences between each adjacent pair of numbers are calculated as follows:

  • The difference between 1 and 3 is |1 - 3| = 2
  • The difference between 3 and 6 is |3 - 6| = 3
  • The difference between 6 and 10 is |6 - 10| = 4

Add them all together: 2 + 3 + 4 = 9. And that's your answer!

Here’s how your function should work:

sum_of_absolute_differences([1, 3, 6, 10]) # Output: 9 sum_of_absolute_differences([5, 8, 12]) # Output: 7 sum_of_absolute_differences([0, 0, 0]) # Output: 0

Write a Function

Your task is to write a function sum_of_absolute_differences that takes this list as input and returns the sum of all these absolute differences.

Let's get started!

Ready, Set, Code! 🚀

Geek
Inputs

Arg 1:

[1,3,6,10]
Expected Output
9
Actual Output