Make Array Consecutive
I have been working on some problems on CodeSignal and came across a problem that challenged me a bit. Now that I have solved it I realized the answer was very simple but I had to sit down for some time to really get it and figure it out at first.
The Problem (from CodeSignal)
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 bemakeArrayConsecutive2(statues) = 3
. - Ratiorg needs statues of sizes
4
,5
and7
.
My initial thought process
My first thought when looking at this problem was to simply iterate through each number and figure out whether the next statue was the number being iterated plus one. This was a sort of brutal force approach to this problem. By iterating I would be able to find the number of statues needed to make the array consecutive. At first I started by sketching some pseudo code on paper until I finally got some code that I was sort of satisfied with. This is what my initial code looked like this.
function makeArrayConsecutive2(statues) {
let num = 0
statues.sort(function(a, b){return a-b})
for (let i = 0; i < statues.length; i++) {
if (statues\[i\] + 1 === statues\[i + 1\]) {
return num
}
else {
statues.splice((i + 1), 0, (statues\[i\] + 1))
return num += 1
}
}
return num
}
This code only passed a few test of the 5 needed to complete the challenge. It was pretty messy code but it helped me understand the problem better and realize that I had to go a different direction. I knew there had to be a simpler way. After a few minutes of thinking about the problem I realized that I could just solve the problem using some simple math.
The Solution
It came to me that if I subtracted the smallest number in the array for the largest number and added one I would get the number of statues that should be in the array if it were consecutive. After that I could simply subtract the length of the nonconsecutive statues array to that. To get the maximum and minimum I used the Math javascript built in object. So in the end I ended up with a much cleaner and simpler answer.
function makeArrayConsecutive2(statues) {
return (Math.max(...statues) - Math.min(...statues) + 1) - statues.length
}
While this seems like a really simple problem it did give me a hard time at first. It was super fun and satisfying to finally see all the tests turn green. It was also nice to know that other users answers were really similar to mine. Thanks for reading and happy coding! 😎
Top comments (0)