Find two smallest elements in a given array

Objective: Given an array of integers, write an algorithm to find the two smallest elements in the array.


Int [] a = {
6, 8, 1, 9, 2, 10};
Output: 1, 2
Int [] a = {
6, 8, 1, 9, 2, 1, 10, 10};
Output: 1, 1
Int [] a ={6};
Output: Invalid Input, array size is less than 2


  1. Take two variables; let’s call them first and second and mark them as +∞.
  2. Iterate through the array and for each element (let’s call it current),  
    • Compare it with the first and if first is greater, assign the first value to second and assign current to first.
    • If above step is not true then current element might be a candidate of second smallest element, so check if current<second, if yes then assign it to second.

See the code below for more understanding.



Smallest and 2nd smallest elements are: 1 2

Top Companies Interview Questions..-


If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: