Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding the smallest positive integer not present in an array in JavaScript
We are required to write a JavaScript function that takes in array of integers as the first and the only argument.
Our function should find and return that smallest positive integer which is not present in the array.
For example, if the input array is:
const arr = [4, 2, -1, 0, 3, 9, 1, -5];
Then the output should be:
5
Because 1, 2, 3, 4 are already present in the array and 5 is the smallest positive integer absent from the array.
Using Sequential Search Approach
The most straightforward approach is to start from 1 and keep checking if each positive integer exists in the array:
const arr = [4, 2, -1, 0, 3, 9, 1, -5];
const findSmallestMissing = (arr = []) => {
let count = 1;
if (!arr?.length) {
return count;
}
while (arr.indexOf(count) !== -1) {
count++;
}
return count;
};
console.log(findSmallestMissing(arr));
5
Using Set for Better Performance
For larger arrays, using a Set provides O(1) lookup time instead of O(n) with indexOf:
const arr = [4, 2, -1, 0, 3, 9, 1, -5];
const findSmallestMissingOptimized = (arr = []) => {
if (!arr?.length) {
return 1;
}
const numSet = new Set(arr);
let count = 1;
while (numSet.has(count)) {
count++;
}
return count;
};
console.log(findSmallestMissingOptimized(arr));
5
Testing with Different Arrays
Let's test our function with various input cases:
const testCases = [
[1, 2, 3, 4, 5], // Expected: 6
[2, 3, 4, 5], // Expected: 1
[], // Expected: 1
[-1, -2, -3], // Expected: 1
[1, 3, 5, 7] // Expected: 2
];
testCases.forEach((test, index) => {
console.log(`Test ${index + 1}: [${test}] -> ${findSmallestMissing(test)}`);
});
Test 1: [1,2,3,4,5] -> 6 Test 2: [2,3,4,5] -> 1 Test 3: [] -> 1 Test 4: [-1,-2,-3] -> 1 Test 5: [1,3,5,7] -> 2
How It Works
The algorithm works by:
- Starting with the smallest positive integer (1)
- Checking if it exists in the array
- If found, increment and check the next number
- Continue until finding a number not in the array
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Sequential with indexOf | O(n²) | O(1) | Small arrays |
| Set-based approach | O(n) | O(n) | Large arrays |
Conclusion
Both approaches effectively find the smallest missing positive integer. Use the Set-based method for better performance with larger datasets, or the simple sequential approach for smaller arrays.
