DSA Continued: Make Array Consecutive 2

Niani Byrd
2 min readJan 7, 2022

Let’s take a look at another DSA problem.

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.

The question is asking us to return the number of additional statues that might be needed. The first thing we’ll do is set a variable and assign it the value of 0. We’ll revisit this variable later in the function.

function makeArrayConsecutive2(statues) {    
let statuesNeeded = 0;

Next, we need to sort the array from smallest to largest.

function makeArrayConsecutive2(statues) {    
let statuesNeeded = 0;
// Sort array smallest to largest
statues.sort((a, b) => {
return a - b;
})

Then, we should iterate through the array so we can find the gaps in values.

function makeArrayConsecutive2(statues) {    
let statuesNeeded = 0;
// Sort array smallest to largest
statues.sort((a, b) => {
return a - b;
})
// Iterate through array and find gaps in values
for(let i = 0; i < statues.length; i++) {

This is where it might get a little tricky. The way we can tell if there is a gap between neighboring numbers, is by subtracting the higher number from the lower number. So for example, if we subtract 8 from 10, there is a gap of 2, meaning one number is missing (9).

function makeArrayConsecutive2(statues) {    
let statuesNeeded = 0;
// Sort array smallest to largest
statues.sort((a, b) => {
return a - b;
})
// Iterate through array and find gaps in values
for(let i = 0; i < statues.length; i++) {
if(statues[i + 1] - statues[i] > 1) {
statuesNeeded += statues[i + 1] - statues[i] - 1;
}
}

Lastly, we return the statues that are needed!

function makeArrayConsecutive2(statues) {    
let statuesNeeded = 0;
// Sort array smallest to largest
statues.sort((a, b) => {
return a - b;
})
// Iterate through array and find gaps in values
for(let i = 0; i < statues.length; i++) {
if(statues[i + 1] - statues[i] > 1) {
statuesNeeded += statues[i + 1] - statues[i] - 1;
}
}
return statuesNeeded;
}

:D

--

--