2 min read ~ Hello readers! It’s really important for me to continue my practice and learning. Lately, I have been completing a coding challenge a day with codewars. This helps me keep my skills sharp and see how other devs all over the planet would solve these problems. Being able to see other solutions expands my mind for solving future problems in a clever and efficient way. I’ve decided that I am going to post my solutions here written in Java, JavaScript and Python for all of my readers to learn! Please let me know if you have any questions.
Find the first non-consecutive number in an array
Your task is to find the first element of an array that is not consecutive.
E.g. If we have an array [1,2,3,4,6,7,8]
then 1
then 2
then 3
then 4
are all consecutive but 6
is not, so that’s the first non-consecutive number.
If the whole array is consecutive then return null
2.
The array will always have at least 2
elements1 and all elements will be numbers. The numbers will also all be unique and in ascending order. The numbers could be positive or negative and the first non-consecutive could be either too!
JavaScript
function firstNonConsecutive (arr) {
// Initialize default value to increment
let previous = arr[0];
// Establish a variable to collect the non consecutive integer
let first;
for (let i = 1; i < arr.length; i++) {
// If prev value is not equal to the next element array val
if ((previous + 1) !== arr[i]) {
// You've found your first non consecutive and break
first = arr[i];
break;
}
previous ++;
}
// return null if first is never set
return first !== undefined ? first : null;
}
Python
def first_non_consecutive(arr):
prev = arr[0]
first = None
for num in arr[1:]:
if (prev + 1) != num:
first = num
break
prev += 1
return first
Java
class FirstNonConsecutive {
static Integer find(final int[] array) {
Integer prev = array[0];
Integer first = null;
for (Integer i = 1; i < array.length; i++) {
if ((prev + 1) != array[i]) {
first = array[i];
break;
}
prev ++;
}
return first;
}
}
Disclaimer: *Now, as much as I am tempted to use ES8 & ES9 functions to reduce the number of lines in JavaScript, I am always a fan of readable code that others can understand. Therefore, with the JavaScript examples, I will try to write it without fancy functions as much as possible so it can actually be read and absorbed by my readers. All of my solutions are commented to explain my thinking. Of course, they could always be better. Please feel free to share how you would solve it!*