Find the smallest and second smallest elements in an array
Last Updated :
22 Jul, 2025
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.ArrayList;
import java.util.Arrays;
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(' '));
[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.ArrayList;
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]
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(" "));
[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.ArrayList;
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]
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(" "));
Find the smallest and second smallest elements in an array
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem