Thursday, July 4, 2024
HomeData ModellingData Structure & AlgorithmFind the smallest and second smallest elements in an array

Find the smallest and second smallest elements in an array

Write an efficient C++/C program to find the smallest and second smallest element in an array.

Example:

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

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.
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


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


Python3




# 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


Javascript




<script>
  
// 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();
  
// printing the desired element
document.write("smallest element is "+arr[0],"</br>");
document.write("second smallest element is "+arr[1],"</br>");
  
// This code is contributed by shinjanpatra
  
</script>


Output

smallest element is 1
second smallest element is 9

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

Approach 2A: 

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[] = {12, 13, 1, 10, 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[] = { 12, 13, 1, 10, 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 = [12, 13, 1, 10, 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 = { 12, 13, 1, 10, 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




<script>
  
// Javascript program to find smallest and
// second smallest elements
  
function solution( arr, arr_size)
{
  let first = Number.MAX_VALUE,
        second = Number.MAX_VALUE;
  
  /* There should be atleast two elements */
  if (arr_size < 2)
  {
    document.write(" Invalid Input ");
    return;
  }
   /* find the smallest element */
  for (let i = 0; i < arr_size ; i ++)
  {
    if (arr[i] < first){
      first = arr[i];
    }
  }
   /* find the second smallest element */
   for (let i = 0; i < arr_size ; i ++){
    if (arr[i] < second && arr[i] > first){
      second = arr[i];
    }
  }
  if (second == Number.MAX_VALUE )
    document.write("There is no second smallest element\n");
  else
    document.write("The smallest element is " + first + " and second "+
      "Smallest element is " + second +'\n');
}
  
  
  // Driver program
    
  let arr = [ 12, 13, 1, 10, 34, 1 ];
  let n = arr.length;
  solution(arr, n);
    
</script>


Output

smallest element is: 1
second smallest element is: 10
 

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

Approach 2B:

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 <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[] = { 12, 13, 1, 10, 34, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    print2Smallest(arr, n);
    return 0;
}


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 = { 12, 13, 1, 10, 34, 1 };
        print2Smallest(arr);
    }
}
  
// This code is contributed by Sam007


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[] = { 12, 13, 1, 10, 34, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    print2Smallest(arr, n);
    return 0;
}
  
// This is code is contributed by rathbhupendra


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[] = { 12, 13, 1, 10, 34, 1 };
        print2Smallest(arr);
    }
}
/*This code is contributed by Devesh Agrawal*/


Python3




# 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 = [12, 13, 1, 10, 34, 1]
print2Smallest(arr)
  
# This code is contributed by Devesh Agrawal


PHP




<?php
// PHP  program to find smallest and
// second smallest elements
  
function print2Smallest($arr, $arr_size)
{
    $INT_MAX = 2147483647;
      
    /* There should be atleast 
       two elements */
    if ($arr_size < 2)
    {
        echo(" 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)
        echo("There is no second smallest element\n");
    else
        echo "The smallest element is ",$first
             ," and second Smallest element is "
                                     , $second;
}
  
// Driver Code
$arr = array(12, 13, 1, 10, 34, 1);
$n = count($arr);
print2Smallest($arr, $n)
  
// This code is contributed by Smitha
?>


Javascript




<script>
  
// 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) 
    
        document.write(" 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 ) 
        document.write("There is no second smallest element\n"); 
    else
        document.write("The smallest element is " + first + " and second "+
            "Smallest element is " + second +'\n'); 
  
  
    // Driver program 
      
    let arr = [ 12, 13, 1, 10, 34, 1 ]; 
    let n = arr.length; 
    print2Smallest(arr, n); 
      
</script>


Output

The smallest element is 1 and second Smallest element is 10

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)

Approach 3:

A N*log(N) approach using Priority_queue data structure. You can read about Priority Queue in more detail here.

C#




using System;
using System.Collections.Generic;
  
class GFG {
    static void Main(string[] args)
    {
        int[] arr = { 2, 5, 7, 3, 9, 10, 11, 1 };
        int n = arr.Length;
  
        PriorityQueue<int> pq = new PriorityQueue<int>();
  
        // adding elements to priority queue
        for (int i = 0; i < n; i++) {
            pq.Enqueue(arr[i]);
        }
  
        int t = pq.Peek(); // smallest element will be on
        // top of pq
        pq.Dequeue(); // removing first element so second
                      // will
        // be on top.
        int w = pq.Peek();
  
        Console.WriteLine("smallest element : " + t);
        Console.WriteLine("second smallest element : " + w);
    }
}
  
public class PriorityQueue<T> where T : IComparable<T> {
    private List<T> data;
  
    public PriorityQueue() { this.data = new List<T>(); }
  
    public void Enqueue(T item)
    {
        data.Add(item);
        int ci = data.Count - 1;
        while (ci > 0) {
            int pi = (ci - 1) / 2;
            if (data[ci].CompareTo(data[pi]) >= 0)
                break;
            T tmp = data[ci];
            data[ci] = data[pi];
            data[pi] = tmp;
            ci = pi;
        }
    }
  
    public T Dequeue()
    {
        // Assumes pq isn't empty
        int li = data.Count - 1;
        T frontItem = data[0];
        data[0] = data[li];
        data.RemoveAt(li);
  
        --li;
        int pi = 0;
        while (true) {
            int ci = pi * 2 + 1;
            if (ci > li)
                break;
            int rc = ci + 1;
            if (rc <= li
                && data[rc].CompareTo(data[ci]) < 0)
                ci = rc;
            if (data[pi].CompareTo(data[ci]) <= 0)
                break;
            T tmp = data[pi];
            data[pi] = data[ci];
            data[ci] = tmp;
            pi = ci;
        }
        return frontItem;
    }
  
    public T Peek()
    {
        T frontItem = data[0];
        return frontItem;
    }
  
    public int Count
    {
        get { return data.Count; }
    }
}


C++




#include <bits/stdc++.h>
  
using namespace std;
  
int main()
{
    int arr[] = { 2, 5, 7, 3, 9, 10, 11, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    priority_queue<int, vector<int>, greater<int> >
        pq; // min heap priority_queue
    // adding elements to priority queue
    for (int i = 0; i < n; i++) {
        pq.push(arr[i]);
    }
    int t = pq.top(); // smallest element will be on top of
                      // pq as it is min heap
    pq.pop(); // removing first element so second will be on
              // top.
    int w = pq.top();
  
    cout << "smallest element : " << t << endl;
    cout << "second smallest element : " << w << endl;
  
    return 0;
}
// this code is contributed by lakshyadeeppatel


Java




import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        int arr[] = { 2, 5, 7, 3, 9, 10, 11, 1 };
        int n = arr.length;
  
        PriorityQueue<Integer> pq
            = new PriorityQueue<Integer>();
  
        // adding elements to priority queue
        for (int i = 0; i < n; i++) {
            pq.add(arr[i]);
        }
  
        int t = pq.peek(); // smallest element will be on
        // top of pq
        pq.poll(); // removing first element so second will
        // be on top.
        int w = pq.peek();
  
        System.out.println("smallest element : " + t);
        System.out.println("second smallest element : "
                           + w);
    }
}
  
// This code is contributed by divyansh2212


Python3




from queue import PriorityQueue
  
arr = [2, 5, 7, 3, 9, 10, 11, 1]
n = len(arr)
pq = PriorityQueue()
  
# adding elements to priority queue
for i in range(0, n):
    pq.put(arr[i])
  
t = pq.get()  # smallest element will be on top of pq as it is min heap
w = pq.get()
  
print("smallest element :", t)
print("second smallest element :", w)


Javascript




class PriorityQueue {
  constructor() {
    this.values = [];
  }
  
  enqueue(val, priority) {
    this.values.push({ val, priority });
    this.sort();
  }
  
  dequeue() {
    return this.values.shift();
  }
  
  sort() {
    this.values.sort((a, b) => a.priority - b.priority);
  }
  
  get top() {
    return this.values[0].val;
  }
  
  get secondTop() {
    return this.values[1].val;
  }
}
  
const arr = [2, 5, 7, 3, 9, 10, 11, 1];
const pq = new PriorityQueue();//min heap priority_queue
      //adding elements to priority queue
for (let i = 0; i < arr.length; i++) {
  pq.enqueue(arr[i], arr[i]);
}
  
const t = pq.top;// smallest element will be on
    // top of pq
pq.dequeue();
const w = pq.top;
  
console.log("smallest element: ", t);
console.log("second smallest element: ", w);


Output

smallest element : 1
second smallest element : 2

Time Complexity: O(n*log(n))
In a priority queue time for adding each element is O(logn) and we are adding all the elements so the total time taken by the priority queue will be O(n*logn)

Auxiliary Space: O(n)

The extra space is used to store the elements in the priority queue.

Related Article: Minimum and Second minimum elements using minimum comparisons

Approach 4: Using list properties

Algorithm:

  • Step 1: Declare a  new list
  • Step 2: Check length of the original list is more than 2 or not.
  • Step 3: Append the smallest element from the original list into new list.
  • Step 4: Count the number times smallest element appeared in the original list, then run a loop to remove all the smallest elements from the original list.
  • Step 5: After removing all smallest elements, now find for 2nd smallest element using min function.
  • Step 6: return new list which contains the smallest element and 2nd smallest element.

Example:

C++




#include <bits/stdc++.h>
using namespace std;
  
vector<int> print2Smallest(vector<int> arr)
{
    vector<int> lst; // vector is declared
    if (unordered_set<int>(arr.begin(), arr.end()).size()
        == 1) {
        return { -1, -1 }; // checking length of array is
                           // greater than 2 or not
    }
    lst.push_back(*min_element(
        arr.begin(), arr.end())); // appending smallest
                                  // element in new vector
    int p = *min_element(arr.begin(),
                         arr.end()); // storing min element
    int c = count(arr.begin(), arr.end(),
                  p); // counting number of smallest element
    arr.erase(
        remove(arr.begin(), arr.end(), p),
        arr.end()); // removing all the smallest element
    lst.push_back(*min_element(
        arr.begin(),
        arr.end())); // appending 2nd smallest element
    return lst;
}
  
// Driver function to test above function
int main()
{
    vector<int> arr = { 12, 13, 1, 10, 34, 1 };
    vector<int> res = print2Smallest(arr);
    for (int i = 0; i < res.size(); i++) {
        cout << res[i] << " ";
    }
    return 0;
}


Java




import java.util.*;
  
public class Main {
    public static List<Integer>
    print2Smallest(List<Integer> arr)
    {
        List<Integer> lst
            = new ArrayList<>(); // List is declared
        if (new HashSet<Integer>(arr).size()
            == 1) { // Checking length of array is greater
                    // than 2 or not
            return Arrays.asList(-1, -1);
        }
        lst.add(Collections.min(
            arr)); // Appending smallest element in new list
        int p = Collections.min(arr); // Storing min element
        int c = Collections.frequency(
            arr, p); // Counting number of smallest element
        arr.removeAll(Collections.singleton(
            p)); // Removing all the smallest element
        lst.add(Collections.min(
            arr)); // Appending 2nd smallest element
        return lst;
    }
  
    // Driver function to test above function
    public static void main(String[] args)
    {
        List<Integer> arr = new ArrayList<>(
            Arrays.asList(12, 13, 1, 10, 34, 1));
        List<Integer> res = print2Smallest(arr);
        for (int i = 0; i < res.size(); i++) {
            System.out.print(res.get(i) + " ");
        }
    }
}


Python3




def print2Smallest(arr):
    lst = []  # list is declared
    if len(set(arr)) == 1# checking length of array is
        return [-1, -1]            # greater than 2 or not
  
    lst.append(min(arr))  # appending small element in new list
    p = min(arr)  # storing min element
    c = arr.count(p)  # counting number of a smallest element
    for i in range(c):
        arr.remove(p)              # removing all the smallest element
    lst.append(min(arr))  # appending 2nd smallest element
    return lst
  
  
# Driver function to test above function
arr = [12, 13, 1, 10, 34, 1]
print(print2Smallest(arr))
  
# This code is contributed by Vaibhav Kumar


Javascript




function print2Smallest(arr) {
  let lst = []; // list is declared
  if (new Set(arr).size === 1) { // checking length of array is greater than 2 or not
    return [-1, -1];
  }
  lst.push(Math.min(...arr)); // appending small element in new list
  let p = Math.min(...arr); // storing min element
  let c = arr.filter((el) => el === p).length; // counting number of a smallest element
  for (let i = 0; i < c; i++) {
    arr.splice(arr.indexOf(p), 1); // removing all the smallest element
  }
  lst.push(Math.min(...arr)); // appending 2nd smallest element
  return lst;
}
  
// Driver function to test above function
let arr = [12, 13, 1, 10, 34, 1];
console.log(print2Smallest(arr));


C#




using System;
using System.Collections.Generic;
using System.Linq;
  
public class MainClass {
    public static List<int> Print2Smallest(List<int> arr) {
        List<int> lst = new List<int>(); // List is declared
        if (new HashSet<int>(arr).Count == 1) { // Checking length of array is greater than 2 or not
            return new List<int> {-1, -1};
        }
        lst.Add(arr.Min()); // Appending smallest element in new list
        int p = arr.Min(); // Storing min element
        int c = arr.Count(x => x == p); // Counting number of smallest element
        arr.RemoveAll(x => x == p); // Removing all the smallest element
        lst.Add(arr.Min()); // Appending 2nd smallest element
        return lst;
    }
  
    // Driver function to test above function
    public static void Main() {
        List<int> arr = new List<int>{12, 13, 1, 10, 34, 1};
        List<int> res = Print2Smallest(arr);
        foreach (int i in res) {
            Console.Write(i + " ");
        }
    }
}


Output

[1, 10]

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

Please write comments if you find any bug in the above program/algorithm or other ways to solve the same problem.

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Nicole Veronica Rubhabha
Nicole Veronica Rubhabha
A highly competent and organized individual DotNet developer with a track record of architecting and developing web client-server applications. Recognized as a personable, dedicated performer who demonstrates innovation, communication, and teamwork to ensure quality and timely project completion. Expertise in C#, ASP.Net, MVC, LINQ, EF 6, Web Services, SQL Server, MySql, Web development,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments