Find Second Smallest Number in an Array : Java Code

Given an input array of unsorted integers. Write a code to find second smallest number in an array.

For example :

arr = {-1, 7, 1, 34, 18}

The second smallest number in this array is 1.

find smallest number in array java

In this tutorial, I am going to explain multiple approaches to solve this problem. Also, we will write it’s java code.

Let’s discuss how we can find second lowest number in an array by sorting and without sorting an array.

Programming video tutorials

METHOD 1: Find second smallest number by sorting an array

The easiest approach is to sort the array.  After sorting an array, the element present at 1st index is the second smallest number in an array.

Bubble Sort Program in Java

Insertion Sort Program in Java

For sorting either we can write our own sort method using Sorting algorithms or we can use java inbuilt sort method.

The time complexity of sorting an array is O(nlogn).

NOTE: If the element of an array is repeated then this approach won’t work.

To understand this let’s take an example.

int num[] = {1, 9, 5, 1, 8, -1, 3, -1};

So what will be the second smallest number if we can use above method (sort and pick the element at 1st index). The element is -1 which is wrong.

How we can improve our previous approach?

The best approach is to traverse an array once to find second smallest number. Let’s implement this approach.

Find Second Smallest Number of an Array

Find Second Smallest Number of an Array

Find Second Smallest Number in an Array  without Sorting – Java Code

Let’s discuss how we can solve this problem in a single traversal using two variables (smallest and secondSmallest).

Here are the following steps –

i) Declare two variables smallest and secondSmallest. Initialize them with Integer.MAX_VALUE.

ii) Traverse an array and do the following checks –

a) If current element is smaller than the smallest. Then, update the value of smallest variable.

b) If current element is greater than smallest and less than secondSmallest than update the value of secondSmallest.

The time complexity of this approach is O(n).

Java Program to Find Second Largest Number in an Array

In this video tutorial, I have explained multiple approaches to solve this problem.

Tagged . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.