My current challenge involves solving CodeSignal projects, and I recently encountered a problem where a random array of numbers is given, requiring me to determine how many additional numbers are needed to make the array consecutive.
For instance, if the array is [3, 6, 8], you would need '4', '5', and '7' to have all consecutive numbers in the sequence. Therefore, the desired output should be '3'.
I discovered a solution that seems to work:
return Math.max.apply(Math, arr) - Math.min.apply(Math, arr) -
arr.length + 1;
However, I am uncertain about why this formula produces the correct result. Is there a mathematical principle or concept behind subtracting the minimum value and the length of the array from the maximum value?
- All numbers in the array are integers
- The array is not sorted