Open In App

Find the smallest and second smallest elements in an array

Last Updated : 27 Jun, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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.

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.

C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;

vector<int> minAnd2ndMin(vector<int> &arr) {
    
    // Sort the array in ascending order
    sort(arr.begin(), arr.end());
    
    int n = arr.size();
    
    // Initialize minimum and second minimum with smallest possible integer
    int mini = INT_MIN, secmini = INT_MIN;
    
    // The first element after sorting is the minimum
    mini = arr[0];
    
    // Find the first element greater than mini (i.e., second minimum)
    for(int i = 0; i < n; i++) {
        
        if(arr[i] != mini) {
            secmini = arr[i];
            break;
        }
    }
    
    // If no second minimum found (i.e., all elements are equal), return -1
    if(secmini == INT_MIN) {
        return {-1};
    }
    
    // Return both minimum and second minimum
    return {mini, secmini};
}

int main() {
    vector<int> arr = {12, 25, 8, 55, 10, 33, 17, 11};
    vector<int> res = minAnd2ndMin(arr);
    for(auto it : res) {
        cout << it << " ";
    }
    cout << "\n";
    return 0;
}
Java
import java.util.*;

class GfG{

    public static ArrayList<Integer> minAnd2ndMin(int[] arr) {
        
        Arrays.sort(arr); 
        int n = arr.length;

        int mini = arr[0];
        int secmini = Integer.MIN_VALUE;

        // Find the first number greater than mini
        for (int i = 0; i < n; i++) {
            
            if (arr[i] != mini) {
                secmini = arr[i];
                break;
            }
        }

        // If second minimum doesn't exist
        if (secmini == Integer.MIN_VALUE) {
            ArrayList<Integer> result = new ArrayList<>();
            result.add(-1);
            return result;
        }

        // Return result as ArrayList
        ArrayList<Integer> result = new ArrayList<>();
        result.add(mini);
        result.add(secmini);
        return result;
    }

    public static void main(String[] args) {
        int[] arr = {12, 25, 8, 55, 10, 33, 17, 11};
        ArrayList<Integer> result = minAnd2ndMin(arr);

        for (int num : result) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}
Python
def minAnd2ndMin(arr):
    
    # Sort the array
    arr.sort()  
    
    mini = arr[0]
    secmini = None

    # Find the first number greater than the minimum
    for num in arr:
        if num != mini:
            secmini = num
            break

    # If no second minimum is found
    if secmini is None:
        return [-1]

    return [mini, secmini]

if __name__ == "__main__":
    arr = [12, 25, 8, 55, 10, 33, 17, 11]
    result = minAnd2ndMin(arr)
    print(*result)
C#
using System;
using System.Collections.Generic;

class GfG{
    
    public static List<int> minAnd2ndMin(int[] arr){
        
        Array.Sort(arr);
        int n = arr.Length;

        int mini = arr[0];
        int secmini = int.MinValue;

        // Find the first number greater than mini
        for (int i = 0; i < n; i++){
            
            if (arr[i] != mini){
                
                secmini = arr[i];
                break;
            }
        }

        // If second minimum doesn't exist
        if (secmini == int.MinValue){
            
            return new List<int> { -1 };
        }

        // Return both values
        return new List<int> { mini, secmini };
    }

    static void Main(string[] args){
        
        int[] arr = {12, 25, 8, 55, 10, 33, 17, 11};
        List<int> result = minAnd2ndMin(arr);

        foreach (int num in result){
            
            Console.Write(num + " ");
        }
        Console.WriteLine();
    }
}
JavaScript
function minAnd2ndMin(arr) {
    
    // Sort the array in ascending order
    arr.sort((a, b) => a - b);  
    
    let mini = arr[0];
    let secmini = Number.MIN_SAFE_INTEGER;

    // Find the first number greater than the minimum
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] !== mini) {
            secmini = arr[i];
            break;
        }
    }

    // If second minimum does not exist, return [-1]
    if (secmini === Number.MIN_SAFE_INTEGER) {
        return [-1];
    }

    return [mini, secmini];
}

// Driver Code
let arr = [12, 25, 8, 55, 10, 33, 17, 11];
let result = minAnd2ndMin(arr);
console.log(result.join(' '));

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.

C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;

vector<int> minAnd2ndMin(vector<int> &arr) {
    
    int n = arr.size();
    int mini = INT_MAX;      
    int secmini = INT_MAX;
    
    // First loop to find the minimum element in the array
    for(int i = 0; i < n; i++) {
        mini = min(mini, arr[i]);
    }

    // Second loop to find the second minimum element 
    for(int i = 0; i < n; i++) {
        if(arr[i] != mini) {
            secmini = min(secmini, arr[i]);
        }
    }

    // If second minimum was not updated, it means all elements are equal
    if(secmini == INT_MAX) {
        return {-1};  
    }

    return {mini, secmini};
}

int main() {
    vector<int> arr = {12, 25, 8, 55, 10, 33, 17, 11}; 
    vector<int> res = minAnd2ndMin(arr);  

    for(auto it : res) {
        cout << it << " ";
    }
    cout << "\n";

    return 0;
}
Java
import java.util.*;

class GfG {

    public static ArrayList<Integer> minAnd2ndMin(int[] arr) {

        int n = arr.length;
        int mini = Integer.MAX_VALUE;
        int secmini = Integer.MAX_VALUE;

        // First loop to find the minimum element in the array
        for (int i = 0; i < n; i++) {
            mini = Math.min(mini, arr[i]);
        }

        // Second loop to find the second minimum element
        for (int i = 0; i < n; i++) {
            if (arr[i] != mini) {
                secmini = Math.min(secmini, arr[i]);
            }
        }

        // If second minimum was not updated, it means all elements are equal
        if (secmini == Integer.MAX_VALUE) {
            ArrayList<Integer> result = new ArrayList<>();
            result.add(-1);
            return result;
        }

        ArrayList<Integer> result = new ArrayList<>();
        result.add(mini);
        result.add(secmini);
        return result;
    }

    public static void main(String[] args) {

        int[] arr = {12, 25, 8, 55, 10, 33, 17, 11};
        ArrayList<Integer> res = minAnd2ndMin(arr);

        for (int x : res) {
            System.out.print(x + " ");
        }
        System.out.println();
    }
}
Python
def minAnd2ndMin(arr):
    n = len(arr)
    mini = float('inf')
    secmini = float('inf')

    # First loop to find the minimum element in the array
    for i in range(n):
        mini = min(mini, arr[i])

    # Second loop to find the second minimum element
    for i in range(n):
        if arr[i] != mini:
            secmini = min(secmini, arr[i])

    # If second minimum was not updated, it means all elements are equal
    if secmini == float('inf'):
        return [-1]

    return [mini, secmini]

# Driver Code
if __name__ == "__main__":
    arr = [12, 25, 8, 55, 10, 33, 17, 11]
    result = minAnd2ndMin(arr)
    print(*result)
C#
using System;
using System.Collections.Generic;

class GfG{
    
    public static List<int> minAnd2ndMin(int[] arr){
        
        int n = arr.Length;
        int mini = int.MaxValue;
        int secmini = int.MaxValue;

        // First loop to find the minimum element in the array
        for (int i = 0; i < n; i++){
            
            mini = Math.Min(mini, arr[i]);
        }

        // Second loop to find the second minimum element
        for (int i = 0; i < n; i++){
            
            if (arr[i] != mini){
                secmini = Math.Min(secmini, arr[i]);
            }
        }

        // If second minimum was not updated, it means all elements are equal
        if (secmini == int.MaxValue){
            
            return new List<int> { -1 };
        }

        return new List<int> { mini, secmini };
    }

    static void Main(string[] args){
        
        int[] arr = {12, 25, 8, 55, 10, 33, 17, 11};
        List<int> res = minAnd2ndMin(arr);

        foreach (int x in res){
            
            Console.Write(x + " ");
        }
        Console.WriteLine();
    }
}
JavaScript
function minAnd2ndMin(arr) {
    let n = arr.length;
    let mini = Number.MAX_SAFE_INTEGER;
    let secmini = Number.MAX_SAFE_INTEGER;

    // First loop to find the minimum element in the array
    for (let i = 0; i < n; i++) {
        mini = Math.min(mini, arr[i]);
    }

    // Second loop to find the second minimum element
    for (let i = 0; i < n; i++) {
        if (arr[i] !== mini) {
            secmini = Math.min(secmini, arr[i]);
        }
    }

    // If second minimum was not updated, it means all elements are equal
    if (secmini === Number.MAX_SAFE_INTEGER) {
        return [-1];
    }

    return [mini, secmini];
}

// Driver Code
let arr = [12, 25, 8, 55, 10, 33, 17, 11];
let res = minAnd2ndMin(arr);
console.log(res.join(" "));

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.
C++
#include <iostream>
#include <vector>
#include <climits>
using namespace std;

vector<int> minAnd2ndMin(const vector<int> &arr) {
    
    int n = arr.size();

    // Need at least two elements to have a second minimum
    if (n < 2) {
        return { -1 };
    }

    // Initialize first and second minimums to "infinity"
    int first = INT_MAX;
    int second = INT_MAX;

    // Single pass over the array
    for (int i = 0; i < n; i++) {
        
        // Found new minimum: shift down the old minimum
        if (arr[i] < first) {
            second = first;
            first = arr[i];
        }
        
        // arr[i] is not equal to first but smaller than current second
        else if (arr[i] < second && arr[i] != first) {
            second = arr[i];
        }
    }

    // If second was never updated, all elements were equal
    if (second == INT_MAX) {
        return { -1 };
    }

    // Return the two minima
    return { first, second };
}

int main() {
    vector<int> arr = {12, 25, 8, 55, 10, 33, 17, 11};
    vector<int> res = minAnd2ndMin(arr);

    for (int x : res) {
        cout << x << " ";
    }
    cout << "\n";

    return 0;
}
Java
import java.util.*;

class GfG {

    public static ArrayList<Integer> minAnd2ndMin(int[] arr) {

        int n = arr.length;

        // Need at least two elements to have a second minimum
        if (n < 2) {
            ArrayList<Integer> result = new ArrayList<>();
            result.add(-1);
            return result;
        }

        // Initialize first and second minimums to "infinity"
        int first = Integer.MAX_VALUE;
        int second = Integer.MAX_VALUE;

        // Single pass over the array
        for (int i = 0; i < n; i++) {

            // Found new minimum: shift down the old minimum
            if (arr[i] < first) {
                second = first;
                first = arr[i];
            }

            // arr[i] is not equal to first but smaller than current second
            else if (arr[i] < second && arr[i] != first) {
                second = arr[i];
            }
        }

        // If second was never updated, all elements were equal
        if (second == Integer.MAX_VALUE) {
            ArrayList<Integer> result = new ArrayList<>();
            result.add(-1);
            return result;
        }

        // Return the two minima
        ArrayList<Integer> result = new ArrayList<>();
        result.add(first);
        result.add(second);
        return result;
    }

    public static void main(String[] args) {
        int[] arr = {12, 25, 8, 55, 10, 33, 17, 11};
        ArrayList<Integer> res = minAnd2ndMin(arr);

        for (int x : res) {
            System.out.print(x + " ");
        }
        System.out.println();
    }
}
Python
def minAnd2ndMin(arr):
    n = len(arr)

    # Need at least two elements to have a second minimum
    if n < 2:
        return [-1]

    # Initialize first and second minimums to "infinity"
    first = float('inf')
    second = float('inf')

    # Single pass over the array
    for i in range(n):
        # Found new minimum: shift down the old minimum
        if arr[i] < first:
            second = first
            first = arr[i]

        # arr[i] is not equal to first but smaller than current second
        elif arr[i] < second and arr[i] != first:
            second = arr[i]

    # If second was never updated, all elements were equal
    if second == float('inf'):
        return [-1]

    # Return the two minima
    return [first, second]


# Driver Code
if __name__ == "__main__":
    arr = [12, 25, 8, 55, 10, 33, 17, 11]
    res = minAnd2ndMin(arr)
    
    for x in res:
        print(x, end=' ')
    print()
C#
using System;
using System.Collections.Generic;

class GfG{
    
    public static List<int> minAnd2ndMin(int[] arr){
        
        int n = arr.Length;

        // Need at least two elements to have a second minimum
        if (n < 2){
            return new List<int> { -1 };
        }

        // Initialize first and second minimums to "infinity"
        int first = int.MaxValue;
        int second = int.MaxValue;

        // Single pass over the array
        for (int i = 0; i < n; i++){
            
            // Found new minimum: shift down the old minimum
            if (arr[i] < first){
                second = first;
                first = arr[i];
            }

            // arr[i] is not equal to first but smaller than current second
            else if (arr[i] < second && arr[i] != first){
                
                second = arr[i];
            }
        }

        // If second was never updated, all elements were equal
        if (second == int.MaxValue){
            return new List<int> { -1 };
        }

        // Return the two minima
        return new List<int> { first, second };
    }

    static void Main(string[] args){
        
        int[] arr = {12, 25, 8, 55, 10, 33, 17, 11};
        List<int> res = minAnd2ndMin(arr);

        foreach (int x in res){
            
            Console.Write(x + " ");
        }
        Console.WriteLine();
    }
}
JavaScript
function minAnd2ndMin(arr) {
    let n = arr.length;

    // Need at least two elements to have a second minimum
    if (n < 2) {
        return [-1];
    }

    // Initialize first and second minimums to "infinity"
    let first = Number.MAX_SAFE_INTEGER;
    let second = Number.MAX_SAFE_INTEGER;

    // Single pass over the array
    for (let i = 0; i < n; i++) {
        // Found new minimum: shift down the old minimum
        if (arr[i] < first) {
            second = first;
            first = arr[i];
        }

        // arr[i] is not equal to first but smaller than current second
        else if (arr[i] < second && arr[i] != first) {
            second = arr[i];
        }
    }

    // If second was never updated, all elements were equal
    if (second === Number.MAX_SAFE_INTEGER) {
        return [-1];
    }

    // Return the two minima
    return [first, second];
}

// Driver Code
let arr = [12, 25, 8, 55, 10, 33, 17, 11];
let res = minAnd2ndMin(arr);

console.log(res.join(" "));

Output
8 10 

Next Article
Article Tags :
Practice Tags :

Similar Reads