Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Python heapq to find K'th smallest element in a 2D array
Next article icon

Find the smallest and second smallest elements in an array

Last Updated : 11 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an array arr[] of size N, find the smallest and second smallest element in an array.

Examples:

Input: arr[] = {12, 13, 1, 10, 34, 1}
Output: 1 10
Explanation: The smallest element is 1 and second smallest element is 10.

Input: arr[] = {111, 13, 25, 9, 34, 1}
Output: 1 9
Explanation: The smallest element is 1 and second smallest element is 9.

Approach 1:

A Simple Solution is to sort the array in increasing order. The first two elements in the sorted array would be the two smallest elements. In this approach, if the smallest element is present more than one time then we will have to use a loop for printing the unique smallest and second smallest elements. 

Below is the implementation of the above approach:

C++
// C++ simple approach to print smallest // and second smallest element. #include <bits/stdc++.h> using namespace std; int main() {     int arr[] = { 111, 13, 25, 9, 34, 1};     int n = sizeof(arr) / sizeof(arr[0]);     // sorting the array using     // in-built sort function     sort(arr, arr + n);     // printing the desired element     cout << "smallest element is " << arr[0] << endl;     cout << "second smallest element is " << arr[1];     return 0; }  // this code is contributed by Machhaliya Muhammad 
Java
/*package whatever //do not write package name here */  import java.io.*; import java.util.*;  class GFG {     // Java simple approach to print smallest     // and second smallest element.      // Driver Code     public static void main(String args[])     {         int arr[] = { 111, 13, 25, 9, 34, 1 };         int n = arr.length;          // sorting the array using         // in-built sort function         Arrays.sort(arr);          // printing the desired element         System.out.println("smallest element is " + arr[0]);         System.out.println("second smallest element is "                            + arr[1]);     } }  // This code is contributed by shinjanpatra 
Python
# Python3 simple approach to print smallest # and second smallest element.  # driver code  arr = [111, 13, 25, 9, 34, 1] n = len(arr) # sorting the array using # in-built sort function arr.sort()  # printing the desired element print("smallest element is "+str(arr[0])) print("second smallest element is "+str(arr[1]))  # This code is contributed by shinjanpatra 
C#
// C# simple approach to print smallest // and second smallest element. using System;  public class GFG {     // Driver Code     static public void Main()     {         int[] arr = { 111, 13, 25, 9, 34, 1};         int n = arr.Length;          // sorting the array using         // in-built sort function         Array.Sort(arr);          // printing the desired element         Console.WriteLine("smallest element is " + arr[0]);         Console.WriteLine("second smallest element is "                           + arr[1]);     } }  // This code is contributed by kothavvsaakash 
JavaScript
// JavaScript simple approach to print smallest // and second smallest element.  // driver code  let arr = [111, 13, 25, 9, 34, 1]; let n = arr.length; // sorting the array using // in-built sort function   arr.sort((a, b) => a - b);  // printing the desired element console.log("smallest element is "+arr[0]); console.log("second smallest element is "+arr[1]); 

Output
smallest element is 1 second smallest element is 9

Time complexity: O(N * logN)
Auxiliary space: O(1)

Finding the smallest and second smallest elements by traversing the array twice (Two-pass):

A Better Solution is to scan the array twice. In the first traversal find the minimum element. Let this element be x. In the second traversal, find the smallest element greater than x.

Using this method, we can overcome the problem of Method 1 which occurs when the smallest element is present in an array more than one time.

The above solution requires two traversals of the input array. 

C++
// C++ program to find smallest and // second smallest element in array #include <bits/stdc++.h> using namespace std; int main() {     int arr[] = { 111, 13, 25, 9, 34, 1 };     int n = sizeof(arr) / sizeof(arr[0]);     int smallest = INT_MAX;     // traversing the array to find     // smallest element.     for (int i = 0; i < n; i++)     {         if (arr[i] < smallest)         {             smallest = arr[i];         }     }     cout << "smallest element is: " << smallest << endl;      int second_smallest = INT_MAX;      // traversing the array to find second smallest element     for (int i = 0; i < n; i++)     {         if (arr[i] < second_smallest && arr[i] > smallest)         {             second_smallest = arr[i];         }     }     cout << "second smallest element is: " << second_smallest << endl;     return 0; }  // This code is contributed by Machhaliya Muhamma 
Java
// Java program to find smallest and // second smallest element in array import java.io.*; class GFG {     public static void main(String args[])     {         int arr[] = { 111, 13, 25, 9, 34, 1 };         int n = arr.length;         int smallest = Integer.MAX_VALUE;         // traversing the array to find         // smallest element.         for (int i = 0; i < n; i++) {             if (arr[i] < smallest) {                 smallest = arr[i];             }         }         System.out.println("smallest element is: "                            + smallest);          int second_smallest = Integer.MAX_VALUE;          // traversing the array to find second smallest         // element         for (int i = 0; i < n; i++) {             if (arr[i] < second_smallest                 && arr[i] > smallest) {                 second_smallest = arr[i];             }         }         System.out.println("second smallest element is: "                            + second_smallest);     } }  // This code is contributed by Lovely Jain 
Python
# python program to find smallest and second smallest element in array  # import the module import sys  arr = [111, 13, 25, 9, 34, 1] n = len(arr) smallest = sys.maxint  # traversing the array to find smallest element. for i in range(n):     if(arr[i] < smallest):         smallest = arr[i]  print('smallest element is: ' + str(smallest)) second_smallest = sys.maxint  # traversing the array to find second smallest element for i in range(n):     if(arr[i] < second_smallest and arr[i] > smallest):         second_smallest = arr[i]  print('second smallest element is: ' + str(second_smallest))  # This code is contributed by lokeshmvs21. 
C#
// C# program to find smallest and // second smallest element in array  using System;  public class GFG {   static public void Main ()   {     int[] arr = { 111, 13, 25, 9, 34, 1 };     int n = arr.Length;     int smallest = Int32.MaxValue;     // traversing the array to find     // smallest element.     for (int i = 0; i < n; i++)      {       if (arr[i] < smallest)        {         smallest = arr[i];       }     }     Console.WriteLine("smallest element is: " + smallest);      int second_smallest = Int32.MaxValue;      // traversing the array to find second smallest     // element     for (int i = 0; i < n; i++)     {        if (arr[i] < second_smallest && arr[i] > smallest)       {         second_smallest = arr[i];       }     }     Console.WriteLine("second smallest element is: " + second_smallest);   } }  // This code is contributed by kothavvsaakash 
JavaScript
// JavaScript program to find smallest and second smallest element in array  let arr = [111, 13, 25, 9, 34, 1]; let n = arr.length;  // Initialize smallest with Infinity let smallest = Infinity;  // Traverse the array to find the smallest element for (let i = 0; i < n; i++) {   if (arr[i] < smallest) {     smallest = arr[i];   } }  console.log("Smallest element is: " + smallest);  // Initialize second smallest with Infinity let secondSmallest = Infinity;  // Traverse the array to find second smallest element for (let i = 0; i < n; i++) {   if (arr[i] < secondSmallest && arr[i] > smallest) {     secondSmallest = arr[i];   } }  console.log("Second smallest element is: " + secondSmallest); 

Output
smallest element is: 1 second smallest element is: 9 

Time complexity: O(N)
Auxiliary space: O(1)

Finding the smallest and second smallest elements by traversing the array twice (One-pass):

Efficient Solution can find the minimum two elements in one traversal. Below is the complete algorithm.

Algorithm: 

1. Initialize both first and second smallest as INT_MAX

first = second = INT_MAX

2. Loop through all the elements.

  • If the current element is smaller than first, then update first and second. 
  • Else if the current element is smaller than second then update second.

Below is the implementation of the above approach:

C++
// C++ program to find smallest and // second smallest elements #include <bits/stdc++.h> using namespace std; /* For INT_MAX */  void print2Smallest(int arr[], int arr_size) {     int i, first, second;      /* There should be atleast two elements */     if (arr_size < 2) {         cout << " Invalid Input ";         return;     }      first = second = INT_MAX;     for (i = 0; i < arr_size; i++) {         /* If current element is smaller than first         then update both first and second */         if (arr[i] < first) {             second = first;             first = arr[i];         }          /* If arr[i] is in between first and second         then update second */         else if (arr[i] < second && arr[i] != first)             second = arr[i];     }     if (second == INT_MAX)         cout << "There is no second smallest element\n";     else         cout << "The smallest element is " << first              << " and second "                 "Smallest element is "              << second << endl; }  /* Driver code */ int main() {     int arr[] = { 111, 13, 25, 9, 34, 1 };     int n = sizeof(arr) / sizeof(arr[0]);     print2Smallest(arr, n);     return 0; }  // This is code is contributed by rathbhupendra 
C
// C program to find smallest and second smallest elements #include <limits.h> /* For INT_MAX */ #include <stdio.h>  void print2Smallest(int arr[], int arr_size) {     int i, first, second;      /* There should be atleast two elements */     if (arr_size < 2) {         printf(" Invalid Input ");         return;     }      first = second = INT_MAX;     for (i = 0; i < arr_size; i++) {         /* If current element is smaller than first            then update both first and second */         if (arr[i] < first) {             second = first;             first = arr[i];         }          /* If arr[i] is in between first and second            then update second  */         else if (arr[i] < second && arr[i] != first)             second = arr[i];     }     if (second == INT_MAX)         printf("There is no second smallest element\n");     else         printf("The smallest element is %d and second "                "Smallest element is %d\n",                first, second); }  /* Driver program to test above function */ int main() {     int arr[] = { 111, 13, 25, 9, 34, 1 };     int n = sizeof(arr) / sizeof(arr[0]);     print2Smallest(arr, n);     return 0; } 
Java
// Java program to find smallest and second smallest // elements  import java.io.*;  class SecondSmallest {     /* Function to print first smallest and second smallest       elements */     static void print2Smallest(int arr[])     {         int first, second, arr_size = arr.length;          /* There should be atleast two elements */         if (arr_size < 2) {             System.out.println(" Invalid Input ");             return;         }          first = second = Integer.MAX_VALUE;         for (int i = 0; i < arr_size; i++) {             /* If current element is smaller than first               then update both first and second */             if (arr[i] < first) {                 second = first;                 first = arr[i];             }              /* If arr[i] is in between first and second                then update second  */             else if (arr[i] < second && arr[i] != first)                 second = arr[i];         }         if (second == Integer.MAX_VALUE)             System.out.println("There is no second"                                + "smallest element");         else             System.out.println("The smallest element is "                                + first                                + " and second Smallest"                                + " element is " + second);     }      /* Driver program to test above functions */     public static void main(String[] args)     {         int arr[] = { 111, 13, 25, 9, 34, 1 };         print2Smallest(arr);     } } /*This code is contributed by Devesh Agrawal*/ 
Python
# Python program to find smallest and second smallest elements  import math   def print2Smallest(arr):      # There should be atleast two elements     arr_size = len(arr)     if arr_size < 2:         print("Invalid Input")         return      first = second = math.inf     for i in range(0, arr_size):          # If current element is smaller than first then         # update both first and second         if arr[i] < first:             second = first             first = arr[i]          # If arr[i] is in between first and second then         # update second         elif (arr[i] < second and arr[i] != first):             second = arr[i]      if (second == math.inf):         print("No second smallest element")     else:         print('The smallest element is', first, 'and',               ' second smallest element is', second)   # Driver function to test above function arr = [111, 13, 25, 9, 34, 1] print2Smallest(arr)  # This code is contributed by Devesh Agrawal 
C#
// C# program to find smallest // and second smallest elements  using System;  class GFG {      /* Function to print first smallest      and second smallest elements */     static void print2Smallest(int[] arr)     {         int first, second, arr_size = arr.Length;          /* There should be atleast two elements */         if (arr_size < 2) {             Console.Write(" Invalid Input ");             return;         }          first = second = int.MaxValue;          for (int i = 0; i < arr_size; i++) {             /* If current element is smaller than first             then update both first and second */             if (arr[i] < first) {                 second = first;                 first = arr[i];             }              /* If arr[i] is in between first and second             then update second */             else if (arr[i] < second && arr[i] != first)                 second = arr[i];         }         if (second == int.MaxValue)             Console.Write("There is no second"                           + "smallest element");         else             Console.Write("The smallest element is " + first                           + " and second Smallest"                           + " element is " + second);     }      /* Driver program to test above functions */     public static void Main()     {         int[] arr = { 111, 13, 25, 9, 34, 1 };         print2Smallest(arr);     } }  // This code is contributed by Sam007 
JavaScript
// Javascript program to find smallest and  // second smallest elements   function print2Smallest( arr, arr_size)  {      let i, first, second;       /* There should be atleast two elements */     if (arr_size < 2)      {          console.log(" Invalid Input ");          return;      }       first=Number.MAX_VALUE ;     second=Number.MAX_VALUE ;      for (i = 0; i < arr_size ; i ++)      {          /* If current element is smaller than first          then update both first and second */         if (arr[i] < first)          {              second = first;              first = arr[i];          }           /* If arr[i] is in between first and second          then update second */         else if (arr[i] < second && arr[i] != first)              second = arr[i];      }      if (second == Number.MAX_VALUE )          console.log("There is no second smallest element\n");      else         console.log("The smallest element is " + first + " and second "+             "Smallest element is " + second +'\n');  }        // Driver program           let arr = [ 111, 13, 25, 9, 34, 1 ];      let n = arr.length;      print2Smallest(arr, n);  

Output
The smallest element is 1 and second Smallest element is 9 

The same approach can be used to find the largest and second-largest elements in an array.

Time Complexity: O(N)
Auxiliary Space: O(1)

Related Article: Minimum and Second minimum elements using minimum comparisons


Next Article
Python heapq to find K'th smallest element in a 2D array
author
kartik
Improve
Article Tags :
  • Searching
  • DSA
  • Arrays
  • Amazon
Practice Tags :
  • Amazon
  • Arrays
  • Searching

Similar Reads

  • Maximum sum of smallest and second smallest in an array
    Given an array arr[] of size n, the task is to find the maximum sum of the smallest and second smallest elements among all possible subarrays of size greater than equals to two. Examples: Input : arr[] = [4, 3, 1, 5, 6]Output : 11Subarrays with smallest and second smallest are,Subarray: [4, 3], smal
    8 min read
  • Find k smallest elements in an array
    Given an array arr[] and an integer k, the task is to find k smallest elements in the given array. Elements in the output array can be in any order. Examples: Input: arr[] = [1, 23, 12, 9, 30, 2, 50], k = 3Output: [1, 2, 9] Input: arr[] = [11, 5, 12, 9, 44, 17, 2], k = 2Output: [2, 5] Table of Conte
    15 min read
  • Find the first, second and third minimum elements in an array
    Find the first, second and third minimum elements in an array in O(n). Examples: Input : 9 4 12 6 Output : First min = 4 Second min = 6 Third min = 9 Input : 4 9 1 32 12 Output : First min = 1 Second min = 4 Third min = 9 First approach : First we can use normal method that is sort the array and the
    8 min read
  • Python heapq to find K'th smallest element in a 2D array
    Given an n x n matrix and integer k. Find the k'th smallest element in the given 2D array. Examples: Input : mat = [[10, 25, 20, 40], [15, 45, 35, 30], [24, 29, 37, 48], [32, 33, 39, 50]] k = 7 Output : 7th smallest element is 30 We will use similar approach like K’th Smallest/Largest Element in Uns
    3 min read
  • Find Second largest element in an array | Set 2
    Given an array arr[] consisting of N integers, the task is to find the second largest element in the given array using N+log2(N) - 2 comparisons. Examples: Input : arr[] = {22, 33, 14, 55, 100, 12}Output : 55 Input : arr[] = {35, 23, 12, 35, 19, 100}Output : 35 Sorting and Two-Traversal Approach: Re
    9 min read
  • Kth smallest element from an array of intervals
    Given an array of intervals arr[] of size N, the task is to find the Kth smallest element among all the elements within the intervals of the given array. Examples: Input : arr[] = {{5, 11}, {10, 15}, {12, 20}}, K =12Output: 13Explanation: Elements in the given array of intervals are: {5, 6, 7, 8, 9,
    7 min read
  • Find the Kth smallest element in the sorted generated array
    Given an array arr[] of N elements and an integer K, the task is to generate an B[] with the following rules: Copy elements arr[1...N], N times to array B[].Copy elements arr[1...N/2], 2*N times to array B[].Copy elements arr[1...N/4], 3*N times to array B[].Similarly, until only no element is left
    8 min read
  • Print n smallest elements from given array in their original order
    We are given an array of m-elements, we need to find n smallest elements from the array but they must be in the same order as they are in given array. Examples: Input : arr[] = {4, 2, 6, 1, 5}, n = 3 Output : 4 2 1 Explanation : 1, 2 and 4 are 3 smallest numbers and 4 2 1 is their order in given arr
    5 min read
  • Find smallest subarray that contains all elements in same order
    Given two arrays of integers of size m and n. The task is to find the minimum length subarray in the first array that contains all the elements of second array. Note: element of second array may be present in the large array in non-contiguous but order must same. ( m < n ) Examples : Input : A[]
    14 min read
  • Smallest element in an array that is repeated exactly 'k' times.
    Given an array of size n, the goal is to find out the smallest number that is repeated exactly 'k' times where k > 0? Assume that array has only positive integers and 1 <= arr[i] < 1000 for each i = 0 to n -1. Examples: Input : arr[] = {2 2 1 3 1} k = 2 Output: 1 Explanation: Here in array,
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences