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
Fetch Second minimum element from an array without sorting JavaScript
We have an array of Numbers, and we are required to write a function that returns the second smallest value from the array.
For example ? if the array is ?
const arr = [67, 87, 56, 8, 56, 78, 54, 67, 98, 56, 54];
Then the output should be the following ?
54
because 54 is the smallest value after 8
Method 1: Using indexOf and splice
This approach finds the minimum element, removes it from a copy of the array, then finds the minimum of the remaining elements.
const arr = [67, 87, 56, 8, 56, 78, 54, 67, 98, 56, 54];
const minimumIndex = arr => {
return arr.indexOf(Math.min(...arr));
};
const secondMinimum = arr => {
const copy = arr.slice();
copy.splice(minimumIndex(copy), 1);
return copy[minimumIndex(copy)];
};
console.log(secondMinimum(arr));
54
Method 2: Using Two Variables (More Efficient)
A more efficient approach that finds both minimum and second minimum in a single pass through the array.
const arr = [67, 87, 56, 8, 56, 78, 54, 67, 98, 56, 54];
const findSecondMinimum = arr => {
if (arr.length < 2) return undefined;
let min = Infinity;
let secondMin = Infinity;
for (let num of arr) {
if (num < min) {
secondMin = min;
min = num;
} else if (num < secondMin && num !== min) {
secondMin = num;
}
}
return secondMin === Infinity ? undefined : secondMin;
};
console.log(findSecondMinimum(arr));
54
Method 3: Using Set and Sort
This method removes duplicates first, then sorts to find the second smallest unique value.
const arr = [67, 87, 56, 8, 56, 78, 54, 67, 98, 56, 54];
const secondMinimumUnique = arr => {
const unique = [...new Set(arr)].sort((a, b) => a - b);
return unique.length >= 2 ? unique[1] : undefined;
};
console.log(secondMinimumUnique(arr));
54
Comparison
| Method | Time Complexity | Space Complexity | Handles Duplicates |
|---|---|---|---|
| indexOf and splice | O(n²) | O(n) | Yes |
| Two Variables | O(n) | O(1) | Yes |
| Set and Sort | O(n log n) | O(n) | Removes duplicates |
Conclusion
The two-variable approach is most efficient with O(n) time complexity. Use the Set method if you need the second smallest unique value, ignoring duplicates.
