Published on

# Making an Array Consecutive 2

Imagine you want to give Sarah some numbers as gifts for her birthday. The numbers you give cannot be negative. Sarah has a preference for arranging her gifts in ascending order, so she wants them sorted from smallest to largest, in such a way that each gift is exactly 1 larger than the previous one. To achieve this sorted arrangement, she needs more numbers. Your task is to assist her in determining how many additional gifts she requires to accomplish this.

Example:

Consider the array [6, 2, 3, 8]. Here, the answer should be 3. This means that numbers 4, 5, and 7 are missing, and she needs 3 more numbers to complete her gifts.

Example 2:

For the array [0, 3], the answer is 2. Numbers 1 and 2 are missing.

Example 3:

For the array [5, 4, 6], the answer is 0. No additional numbers are needed, as 4, 5, and 6 are already consecutive.

Solution:

In the case of the array [6, 2, 3, 8], if we take the largest number (8) and subtract the smallest number (2), we can determine how many numbers should ideally be in between. We already have a set of numbers, essentially becoming a count of length + 1. Therefore, the solution boils down to subtracting the number of existing elements from the number of required elements, yielding:

``````return Math.max(...statues) - Math.min(...statues) - statues.length + 1
``````

This calculation helps Sarah figure out the exact number of additional gifts she needs to complete her sorted sequence of gifts.