How to get second minimum element of an array in JavaScript

Key takeaways:

  • Sorting approach: Sorting simplifies the task but has higher time complexity O(nlogn)O(n \log n). It’s ideal when you also need a fully sorted array.

  • Linear scan approach: A single pass through the array efficiently identifies the second minimum O(n)O(n). This approach is suitable for large datasets where efficiency is crucial.

  • Efficiency comparison: Choose sorting for sorted data needs; use linear scans for isolated second minimum extraction.

JavaScript is a flexible programming language used for web development that provides dynamic and interactive website functionality. JavaScript arrays are fundamental data structures that act as containers for holding several values in a single variable.

Arrays are zero-indexed, with the first element stored at index 0, and they can store items of different data kinds. JavaScript arrays come with built-in properties and methods for simple element manipulation, making them handy for developing algorithms, storing data lists, and iterating over elements.

What is the second minimum element?

The second minimum element in an array is the smallest value greater than the minimum. It’s useful in many algorithmic problems where order or hierarchy among values matters.

Approaches to find the second minimum in JavaScript

JavaScript offers numerous solutions to find the second minimum element of an array.

  • One such method is iterating through the array while keeping track of the first and second minimum values. We can update the minimum and second minimum values by comparing each element to the current minimum.

  • Another method involves accessing the part at index 1, the second minimal element, by sorting the array in ascending order. In addition, JavaScript offers integrated array functions, such sort(), reduce() and Math.min(), that can be creatively employed to address this issue. The size of the array, necessary efficiency standards, and particular problem limitations all influence the technique chosen.

Approach 1: Finding the second minimum using sorting

Here's an explanation of the approach, which involves sorting the array to find the second minimum element.

  1. Ensure the array has at least two elements. If not, throw an error to indicate invalid input.

  2. Use the sort() method to arrange elements in ascending order.

  3. Directly retrieve the element at index 1, corresponding to the second smallest value in the sorted array.

Note: Sorting and picking the second element doesn't work with duplicates, as it may return the same value as the minimum.

Let’s look at the code for the sorting implementation discussed.

function findSecondMinimum(arr) {
if (!Array.isArray(arr) || arr.length < 2) {
throw new Error('Invalid input. Array must have at least two elements.');
}
arr.sort((a, b) => a - b);
return arr[1];
}
function main() {
const testCases = [
[5, 3, 8, 1, 9, 4],
[10, 20, 30, 40],
[2, 4, 9, 3],
[1, 2],
[1],
];
for (let i = 0; i < testCases.length; i++) {
try {
console.log(`\tArray: [${testCases[i]}]`);
const result = findSecondMinimum(testCases[i]);
console.log(`\tSecond minimum: ${result}`);
} catch (error) {
console.log(`\tArray: [${testCases[i]}]`);
console.log(`\tError: ${error.message}`);
}
console.log('-'.repeat(100));
}
}
// Execute the main function
main();

Time complexity

The time complexity of the algorithm above is O(nlogn)O(n \log n),where nn is the number of elements in the input array.

Space complexity

The space complexity of the algorithm above is O(1)O(1).

Approach 2: Efficient linear scan for the second minimum in JavaScript

The linear scan approach is more efficient and involves the following:

  1. Set min and secondMin to Infinity to track the smallest and second smallest values.

  2. Iterate through the array:

    1. If the current element is smaller than min, update both min and secondMin.

    2. If the current element is greater than min but smaller than secondMin, update secondMin.

  3. If secondMin remains Infinity, no valid second minimum exists, and an error is thrown.

Now, let’s look at the following illustration to get a better understanding of the solution:

canvasAnimation-image
1 of 9

Let’s look at the code for the linear implementation discussed.

function findSecondMinimum(arr) {
if (!Array.isArray(arr) || arr.length < 2) {
throw new Error('Invalid input. Array must have at least two elements.');
}
let min = Infinity;
let secondMin = Infinity;
for (let i = 0; i < arr.length; i++) {
if (arr[i] < min) {
secondMin = min;
min = arr[i];
} else if (arr[i] < secondMin && arr[i] !== min) {
secondMin = arr[i];
}
}
if (secondMin === Infinity) {
throw new Error('No second minimum element found in the array.');
}
return secondMin;
}
function main() {
const testCases = [
[5, 3, 8, 1, 9, 4],
[10, 20, 30, 40],
[2, 2, 2, 3],
[1, 2],
[1],
];
for (let i = 0; i < testCases.length; i++) {
try {
console.log(`\tArray: [${testCases[i]}]`);
const result = findSecondMinimum(testCases[i]);
console.log(`\tSecond minimum: ${result}`);
} catch (error) {
console.log(`\tArray: [${testCases[i]}]`);
console.log(`\tError: ${error.message}`);
}
console.log('-'.repeat(100));
}
}
// Execute the main function
main();

Time complexity

The time complexity of the algorithm above is O(n)O(n), where nn is the number of elements in the input array.

Space complexity

The space complexity of the algorithm above is O(1)O(1).

Comparison between two approaches

Below is the comparison of the above two approaches to finding the second minimum element:

Approach

Time Complexity

Space Complexity

Use Case

Sorting

O(nlogn)

O(1)

When a fully sorted array is needed alongside the second minimum.

Linear Scan

O(1)

O(1)

Ideal for large datasets or when efficiency is paramount.

To further strengthen your coding skills and boost your technical interview preparation, here are some LeetCode problems to practice:

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How to get the second element of an array in JavaScript?

In JavaScript, to get the second element of an array, you simply access the array at index 1 using bracket notation. Since arrays are zero-indexed, the first element is at index 0, and the second element is at index 1. For example, if you have an array like let arr = [10, 20, 30], you can retrieve the second element with arr[1], which will return 20. This is a straightforward and efficient way to access any element by its position in the array.


How to find the smallest element in an array in JavaScript?

To find the smallest element in an array in JavaScript, you can use the built-in Math.min() function in combination with the spread operator (...). This allows you to pass all the elements of the array as arguments to the Math.min() function. For example, Math.min(...arr) will return the smallest value in the array. This method is simple and concise, and it efficiently handles arrays with varying lengths, returning the smallest number directly.


How to find the smallest number in an array without sorting?

To find the smallest number in an array without sorting, you can iterate over the array and track the smallest value encountered. Start by assuming the first element is the smallest, then compare each subsequent element to the current smallest value. If a smaller element is found, update the smallest value. This approach runs in linear time O(n)O(n), ensuring that you only need to pass through the array once, making it more efficient than sorting for large arrays.


How to find the largest element in an array in JavaScript?

Use the Math.max() function along with the spread operator (...) to find the largest element in an array. For example, Math.max(...arr) returns the largest value in the array arr.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved