Bash Array: find the first missing integer

/ Category: Scripts / Comments: None

Spread the love

The script below will find the first missing number in an array of integers.

array=(100 101 102 105)
for (( i = 0 ; i < $((${#array[@]}-1)) ; i++ )); do
if [ $((${array[$i]}+1)) -ne ${array[$(($i + 1))]} ] ;then 

echo $M_NUMBER

Explaining the code:

$((${#array[@]}-1)) – number of array elements minus one

$((${array[$i]}+1)) – i-element of the array plus one, starting from the first element

${array[$(($i + 1))]} – i+1 (next) element of the array, starting from the second element

If the next element is not equal to previous element plus one, the script will print the missing number – $((${array[$i]}+1))

PS. If you liked this post please share it with your friends on the social networks using the buttons on the left or simply leave a reply below. Thanks.


Be the first to write a comment.

Your feedback