DSA: shapeArea

Niani Byrd
2 min readNov 5, 2021

Read the following problem statement:

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.ExampleFor statues = [6, 2, 3, 8], the output should be
makeArrayConsecutive2(statues) = 3.
Ratiorg needs statues of sizes 4, 5 and 7.

When I was a student at Flatiron School, sorting questions were very common, because they are so important to know how to do! The sort method in JavaScript is how we will answer this question.

Let’s define a variable “o”:

function makeArrayConsecutive2(statues) {   
let o = 0;
}

We’ll call the sort method on statues, so that we can order our array so that it ascends from smallest to largest.

function makeArrayConsecutive2(statues) {    
let o = 0;
statues.sort((a, b) => b - a);
}

Afterwards, we want to iterate over the entire array by writing a for loop. Remember to designate the length of the array subtract one so that we close out the loop at the appropriate time. We’ll take the o variable that we set earlier, and increment that by the length of the statues, so we can find the missing values.

function makeArrayConsecutive2(statues) {    
let o = 0;
statues.sort((a, b) => b - a);
for(let i = 0; i < statues.length - 1; i++) {
o += statues[i] - statues[i + 1] - 1;
}
}

Now, all that’s left to do is to return the value of o!

function makeArrayConsecutive2(statues) {    
let o = 0;
statues.sort((a, b) => b - a);
for(let i = 0; i < statues.length - 1; i++) {
o += statues[i] - statues[i + 1] - 1;
}
return o;
}

--

--