Skip to content

Make Array Consecutive

Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, each statue having an non-negative integer size. Since he likes to make things perfect, he wants to arrange them from smallest to largest so that each statue will be bigger than the previous one exactly by 1. He may need some additional statues to be able to accomplish that. Help him figure out the minimum number of additional statues needed.

Example

For statues = [6, 2, 3, 8], the output should be

make_array_consecutive(status) = 3

Ratiorg needs statues of sizes 4, 5 and 7.

Solution

py
def make_array_consecutive(sequence):
    return max(sequence) - min(sequence) - len(sequence) + 1

print(make_array_consecutive([6, 2, 3, 8]))
js
function makeArrayConsecutive(statues) {
  // return Math.max(...statues) - Math.min(...statues) - statues.length + 1;

  // without ... operator
  let min = statues[0];
  let max = statues[0];
  for (let i = 1; i < statues.length; i++) {
    if (statues[i] < min) {
      min = statues[i];
    }
    if (statues[i] > max) {
      max = statues[i];
    }
  }
  return max - min - statues.length + 1;
}

console.log(makeArrayConsecutive([6, 2, 3, 8]));

my thoughts are neither my employer's nor my wife's