VOOZH about

URL: https://www.geeksforgeeks.org/dsa/to-find-smallest-and-second-smallest-element-in-an-array/

⇱ Smallest and second smallest in an array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Smallest and second smallest in an array

Last Updated : 23 Apr, 2026

Given an array arr[] of integers, find the smallest and second smallest distinct elements in the array. The result should be returned in ascending order, meaning the smallest element should come first, followed by the second smallest. If there is no valid second smallest (i.e., all elements are the same or the array has fewer than two elements), then return -1.

👁 Smallest-and-2nd-smallest-elements-in-an-array

Examples:

Input: arr[] = [12, 25, 8, 55, 10, 33, 17, 11]
Output: [8, 10]
Explanation: The smallest element is 1 and second smallest element is 10.

Input: arr[] = [2, 4, 3, 5, 6]
Output: [2, 3]
Explanation: 2 and 3 are respectively the smallest and second smallest elements in the array.

Input: arr[] = [1, 1, 1]
Output: [-1]
Explanation: Only element is 1 which is smallest, so there is no second smallest element.

[Naive Approach] Using Sorting - O(n × log(n)) Time and O(1) Space

The Idea is to is first sorted the array in ascending order, which ensures that the smallest element is at the front. Then, the code searches for the first number that is greater than the minimum to identify the second smallest. If all elements are equal and no distinct second minimum exists, it returns -1.


Output
8 10 

[Better Approach] Using Two Pass - O(n) Time and O(1) Space

The main idea of this approach is to find the smallest and second smallest distinct elements in the array using two separate passes. In the first loop, it identifies the minimum value (mini) by comparing each element. In the second loop, it looks for the smallest element that is not equal to the minimum, which becomes the second minimum (secmini). This ensures that both values are distinct.


Output
8 10 

[Expected Approach] Using Single Pass - O(n) Time and O(1) Space

The main idea of this approach is to find the smallest and second smallest distinct elements by scanning the array only once. It uses two variables: first for the minimum value and second for the second minimum.
The values are updated based on the following conditions:
=> If the current number is less than first: Update second = first and first = current number.
=> Else if the current number is greater than first but less than second: Update second = current number.


Output
8 10 
Comment
Article Tags: