Second Largest Number In Array Java

In this tutorial, we are going to write a Java program to find the Second Largest Number In an Array. This is an important problem, and it’s generally asked in interviews.

There are various ways to find the second largest number in array Java. We will discuss each of them with examples.

  • Using Sorting technique
  • Using Two Traverse of array
Post Type:Java Programs Examples
Published On:www.softwaretestingo.com
Applicable For:Freshers & Experience
Get Updates:Join Our Telegram Group

Find the Second Largest Number In the Array Using the Sorting Technique

The goal is to sort the array in descending order and then return the second element that is not equal to the largest element from the sorted array.

package com.softwaretestingo.interviewprograms;
import java.util.Arrays;
public class SecondLargestNoEx1 
{
	static void FindSecondlargest(int arr[], int arr_size)
	{
		int i, first, second;

		// When array having less then 2 elements
		if (arr_size < 2)
		{
			System.out.printf(" Invalid Input ");
			return;
		}

		// Sort the array
		Arrays.sort(arr);

		// Start from second last element as the largest element is at last
		for (i = arr_size - 2; i >= 0; i--)
		{
			// If the element is not equal to largest element
			if (arr[i] != arr[arr_size - 1])
			{
				System.out.printf("The second largest " + "element is %d\n", arr[i]);
				return;
			}
		}

		System.out.printf("There is no second " + "largest element\n");
	}
	public static void main(String[] args) 
	{
		int arr[] = {12, 35, 1, 10, 34, 1};
		int n = arr.length;
		FindSecondlargest(arr, n);
	}
}

Another Way to Find the Second Largest Number In the Array is using the sorting technique.

package com.softwaretestingo.interviewprograms;
import java.util.Arrays;
public class SecondLargestNoEx2 
{
	public static void main(String[] args) 
	{
		int array[] = {10, 20, 25, 63, 96, 57};
		int size = array.length;
		Arrays.sort(array);
		System.out.println("sorted Array ::"+Arrays.toString(array));
		int res = array[size-2];
		System.out.println("2nd largest element is ::"+res);
	}
}

Find the Second Largest Number In the Array Using Two Traverse of the array

package com.softwaretestingo.interviewprograms;
public class SecondLargestNoEx3 
{
	public static int getSecondLargest(int[] a) 
	{
		int temp;
		//sort the array
		for (int i = 0; i < a.length; i++) 
		{
			for (int j = i + 1; j < a.length; j++) 
			{
				if (a[i] > a[j]) 
				{
					temp = a[i];
					a[i] = a[j];
					a[j] = temp;
				}
			}
		}
		//return second largest element
		return a[a.length - 2];
	}
	public static void main(String[] args) 
	{
		int a[] = { 11,10,4, 15, 16, 13, 2 };
		System.out.println("Second Largest: " +getSecondLargest(a));
	}
}

Another Method

package com.softwaretestingo.interviewprograms;
public class SecondLargestNoEx3 
{
	static void secondLargest(int arr[], int arr_size)
	{
		int i, first, second;

		if (arr_size < 2)
		{
			System.out.printf(" Invalid Input ");
			return;
		}

		int largest = second = Integer.MIN_VALUE;

		// Find the largest element
		for(i = 0; i < arr_size; i++)
		{
			largest = Math.max(largest, arr[i]);
		}

		// Find the second largest element
		for(i = 0; i < arr_size; i++)
		{
			if (arr[i] != largest)
				second = Math.max(second, arr[i]);
		}
		if (second == Integer.MIN_VALUE)
			System.out.printf("There is no second " +
					"largest element\n");
		else
			System.out.printf("The second largest " +
					"element is %d\n", second);
	}

	public static void main(String[] args) 
	{
		int arr[] = { 12, 35, 1, 10, 34, 1 };
		int n = arr.length;

		secondLargest(arr, n);
	}
}

Second Largest Number In Array Java

When someone asks about Java programs in interviews, first of all, we need to analyze the coding assignment and break it down. Now, for this particular assignment, there are a couple of things that we need to take into account. So, in order to find the Second Largest Number In an Array, we know one thing: we must go through every element within the Array.

  • We must iterate through the entire list, and we also need to be able to keep track of the second-highest number.
  • We also need to be able to keep track of the highest number. This will ensure that we calculate the proper values for each iteration of this loop.
  • We need to know how to store the values of the above numbers as we iterate through this list. This basically means we need to be able to set up conditional statements that check for the highest and second-highest values.

Approach

First, take the number of elements that the user wants to enter in the array as input. Then, initialize an array with that size and take input from users. After taking input from the user, we will use the approach below to find the second-highest number in an array.

  • We’ll initialize two integers—the largest and the second largest. Both integers will be set to the possible minimum integer value (i.e., Integer.MIN_VALUE).
  • This is the optional step where we print all the elements of the array.
  • The main logic for finding the second-highest or second-maximized number in the array is very simple. Whenever the current element of the array is greater than the value present in the integer largest, then set the largest value to the second largest and the current element to the largest. If the current element is less than the largest but greater than the second largest, then we will assign the current element to the second largest. We will repeat this process until we reach the last element of the array.

If you have traversed the complete array list, then we will be able to find the second-largest number in the array. Here is the example program:

package com.softwaretestingo.interviewprograms;
import java.util.Arrays;
import java.util.Scanner;
public class SecondLargestNoEx4 
{
	public static void main(String[] args) 
	{
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter array size :");
		Integer numberOfElements = scanner.nextInt();
		int arr[] = new int[numberOfElements];
		System.out.println("Enter array elements :");
		for (int i = 0; i < arr.length; i++) 
		{
			arr[i] = scanner.nextInt();
		}
		System.out.println("Array elements are" + Arrays.toString(arr));
		int largest = Integer.MIN_VALUE;
		int secondLargest = Integer.MIN_VALUE;
		for (int i = 0; i < arr.length; i++) 
		{
			if (arr[i] > largest) 
			{
				secondLargest = largest;
				largest = arr[i];
			} else if (arr[i] > secondLargest && arr[i] != largest) 
			{
				secondLargest = arr[i];
			}
		}
		if (secondLargest == Integer.MIN_VALUE) 
		{
			System.out.println("There is no second highest/largest element in the array");
		} else 
		{
			System.out.println("Second highest element in array is :" + secondLargest);
		}
		scanner.close();
	}
}

Second Lowest Number In Array Java [ Using Loops ]

As we discussed how to find the second largest element in the array, we were also sometimes asked to find the second highest and second lowest elements of the array in interviews.

  • Declare two variables, say first = INT_MAX and second = INT_MAX, to hold the first and second smallest elements, respectively.
  • Now, iterate over the entire array, i.e, from index 0 to n-1
  • Inside the loop, check if (arr[i]<first), then set second = first and first = arr[i].
  • Else check if(second > arr[i]) then set second = arr[i]
  • After complete iteration, print the value of the second.
package com.softwaretestingo.interviewprograms;
public class SecondLowestNoEx1 
{
	static int secSmallest(int arr[], int n)
	{
		int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE;

		for (int i=0; i < n; i++)
		{
			if(arr[i] < first)
			{
				second = first; first = arr[i]; 
			} 
			else if(second>arr[i])
				second = arr[i];
		}

		return second;

	}
	public static void main(String[] args) 
	{
		int arr[] = {12, 13, 1, 10, 34, 10};
		int n = arr.length;
		System.out.print("Second Lowest Number: " +secSmallest(arr, n)); 
	}
}

Second Lowest Number In Array Java [ Using Two Loops ]

We can also find out the second lowest number by using two loops.

  • Take a variable, say smallest = Integer.MAX_VALUE
  • Run a loop over the entire array and check if (arr[i]<smallest)
  • Then set smallest = arr[i].
  • Declare another variable say sec_smallest = Integer.MAX_VALUE
  • Run a loop and check if arr[i] != smallest and arr[i] < sec_smallest
  • Then print(sec_smallest) after completing the iteration.
package com.softwaretestingo.interviewprograms;
public class SecondLowestNoEx2 
{
	static int secLowest(int arr[], int n)
	{
		// assigning first element as smallest temporarily
		int smallest = arr[0];

		// we find the smallest element here
		for (int i=0; i < n; i++){
			if(arr[i] < smallest)
				smallest = arr[i];
		}

		// temporarily assinging largest max value
		int sec_smallest = Integer.MAX_VALUE;


		// finding second smallest here
		for (int i=0; i < n; i++){
			if(arr[i] != smallest && arr[i] < sec_smallest)
				sec_smallest = arr[i];
		}

		return sec_smallest;

	}
	public static void main(String[] args) 
	{
		int arr[] = {12, 13, 1, 10, 34, 10};
		int n = arr.length;
		System.out.print("Second Lowest Number: " +secLowest(arr, n)); 
	}
}

Find the Second Smallest and Second Largest Element in an array

We can find the Second Smallest and Second Largest elements by using 3 methods:

Solution 1: Brute Force Approach

You can use this approach when there are no duplicates. So for this approach, you have to follow the below steps:

  • Sort the array in ascending order
  • The element present at the second index is the second smallest element
  • The element present at the second index from the end is the second-largest element
package com.softwaretestingo.interviewprograms;
import java.util.Arrays;
public class SecondSmallestSecondLargestEx1 
{
	static private void getElements(int[] arr, int n)
	{
		if (n == 0 || n==1)
		{
			System.out.print(-1);
			System.out.print(" ");
			System.out.print(-1);
			System.out.print("\n");
		}
		Arrays.sort(arr);
		int small = arr[1];
		int large = arr[n - 2];
		System.out.println("Second smallest is "+small);
		System.out.println("Second largest is "+large);
	}
	public static void main(String[] args) 
	{
		int[] arr = {1, 2, 4, 6, 7, 5};
		int n = arr.length;
		getElements(arr, n);		
	}
}

Solution 2:

We definitely want to avoid sorting the whole array if we can help it – doing so would increase our time complexity. Is there some way we can get our answer without having to sort everything?

  • Find the smallest and largest element in the array in a single traversal
  • After this, we once again traverse the array and find an element that is just greater than the smallest element we just found.
  • Similarly, we would find the largest element, which is just smaller than the largest element we just found
  • Indeed, this is our second smallest and second largest element.
package com.softwaretestingo.interviewprograms;
public class SecondSmallestSecondLargestEx2 
{
	static private void getElements(int[] arr, int n)
	{
		if (n == 0 || n==1)
		{
			System.out.print(-1);
			System.out.print(" ");
			System.out.print(-1);
			System.out.print("\n");
		}
		int small = Integer.MAX_VALUE;
		int second_small = Integer.MAX_VALUE;
		int large = Integer.MIN_VALUE;
		int second_large = Integer.MIN_VALUE;
		int i;
		for (i = 0;i < n;i++)
		{
			small = Math.min(small,arr[i]);
			large = Math.max(large,arr[i]);
		}
		for (i = 0;i < n;i++)
		{
			if (arr[i] < second_small && arr[i] != small)
			{
				second_small = arr[i];
			}
			if (arr[i] > second_large && arr[i] != large)
			{
				second_large = arr[i];
			}
		}

		System.out.println("Second smallest is "+second_small);
		System.out.println("Second largest is "+second_large);
	}

	public static void main(String[] args) 
	{
		int[] arr = {11, 22, 54, 96, 37, 55};
		int n = arr.length;
		getElements(arr, n);	
	}
}

Solution 3:

In our previous solution, we were able to reduce the time complexity to O(N) by doing two traversals. However, there is another more efficient way, requiring only a single traversal to find the answer. By using smart comparisons, we can eliminate the need for a second traversal.

Second Smallest Algo:

  • If the current element is smaller than ‘small’, then we update second_small and small variables
  • Else if the current element is smaller than ‘second_small’, then we update the variable ‘second_small’
  • Once we traverse the entire array, we would find the second smallest element in the variable second_small.
  • Here’s a quick demonstration of the same.

Second Largest Algo:

  • If the current element is larger than ‘large’, then update second_large and large variables
  • Otherwise, if the current element is larger than ‘second_large’, then we update the variable second_large.
  • Once we traverse the entire array, we would find the second largest element in the variable second_large.
  • Here’s a quick demonstration of the same.
package com.softwaretestingo.interviewprograms;
public class SecondSmallestSecondLargestEx3 
{
	static private int secondSmallest(int[] arr, int n)
	{
		if (n < 2)
		{
			return -1;
		}
		int small = Integer.MAX_VALUE;
		int second_small = Integer.MAX_VALUE;
		int i;
		for (i = 0; i < n; i++)
		{
			if (arr[i] < small)
			{
				second_small = small;
				small = arr[i];
			}
			else if (arr[i] < second_small && arr[i] != small)
			{
				second_small = arr[i];
			}
		}
		return second_small;
	}
	static private int secondLargest(int[] arr, int n)
	{
		if(n<2)
			return -1;
		int large = Integer.MIN_VALUE;
		int second_large = Integer.MIN_VALUE;
		int i;
		for (i = 0; i < n; i++)
		{
			if (arr[i] > large)
			{
				second_large = large;
				large = arr[i];
			}

			else if (arr[i] > second_large && arr[i] != large)
			{
				second_large = arr[i];
			}
		}
		return second_large;
	}
	public static void main(String[] args) 
	{
		int[] arr = {18, 22, 46, 77, 77, 53};
		int n = arr.length;
		int sS = secondSmallest(arr, n);
		int sL = secondLargest(arr, n);
		System.out.println("Second smallest is "+sS);
		System.out.println("Second largest is "+sL);	
	}
}

Get the Second Highest/Lowest Number using Streams

package com.softwaretestingo.interviewprograms;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class SecondSmallestSecondLargestEx4 
{
	public static void main(String[] args) 
	{
		List<Integer> list=Arrays.asList(11,6,2,978,78,45,87,23,9,11,76,56);
		
		//Print Second Highest
		int sechH=list.stream().sorted(Collections.reverseOrder()).distinct().limit(2).skip(1).findFirst().get();
		System.out.println("Second Highest Number: "+sechH);
		
		int sechHH=list.stream().sorted(Collections.reverseOrder()).distinct().skip(1).findFirst().get();
		System.out.println("Second Highest Number: "+sechHH);
		
		//Print Second Lowest
		int secL=list.stream().sorted().distinct().skip(1).findFirst().get();
		System.out.println("Second lowest Number: "+secL);
	}
}

Conclusion:

We believe that in this blog post, we tried to cover all the possible ways to find the second largest and second smallest element from the array list. We hope these Java program examples will be informative and helpful.

If you found this tutorial helpful, be sure to share it with others who might find it informative. And don’t forget to leave your thoughts in the comment section below! If you’re on the hunt for more interview programs, visit our interview category.

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment