Finding the first missing number in a continuous sequence of integers within an array is a common interview question in automation testing and programming assessments.
One simple and efficient approach to solving this problem is by iterating through the array and comparing each element with the next element. Since the numbers are expected to be in sequential order, the difference between consecutive elements should always be 1.
While looping through the array:
- Calculate the difference between the current element and the next element.
- If the difference is not equal to
1, it means a number is missing in the sequence. - The missing number can be determined by returning the current element plus
1. - If no such difference is found throughout the loop, it means there is no missing number in the sequence.
Below is an example implementation that returns the first missing number from the array:
Example code:
package tests;
import org.testng.annotations.Test;
public class FindMissedNumber {
@Test
public void findValue() {
int[] arr = {1,2,4,5,6,8,9};
if(arr[0] != 1){
System.out.print(“missed value is”+ 1);
}else if(missedValue(arr) != -1){
System.out.print(“missed value is”+ missedValue(arr));
}else{
System.out.print(“No missed value”);
}
}
public int missedValue(int[] arr) {
int len = arr.length;
for(int i=0;i<len-1;i++) {
if(arr[i+1]-arr[i] != 1) return arr[i]+1;
}
return -1;
}
}
Solution:
In the FindMissedNumber class, the @Test annotation is used to execute the findValue() method as part of the TestNG test run.
Inside the findValue() method, an integer array containing sequential positive numbers is created and passed to the missedValue() method to determine if any number is missing in the sequence.
The missedValue() method works as follows:
- It iterates through the array.
- It checks the difference between consecutive elements.
- If the difference between two adjacent numbers is not equal to
1, it means a number is missing. - In that case, the method returns the missing number (
arr[i] + 1). - If no missing number is found after checking the entire array, the method returns
-1.
Additionally, as a precondition, if the first element of the array (arr[0]) is not equal to 1, the method assumes that 1 is the missing number (since the sequence is expected to start from 1 for positive integers).