If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.
In this post, we will see how to find the second largest number in an array.
Problem :
Given an unsorted array, you need to find the second largest element in the array in o(n)
time complexity.
For example:
Second largest element in the array : 6
Solution:
You can sort the array and then return second last element in the array but it will be done in o(nlogn) time,
Algorithm:
- Initialize highest and secondHighest with minimum possible value.
- Iterate over array.
- If current element is greater than highest
- Assign secondHighest = highest
- Assign highest = currentElement
- Else if current element is greater than secondHighest
- Assign secondHighest =current element.
Java Program to find second largest number in array:
FindSecondLargestMain.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package org.arpit.java2blog; public class FindSecondLargestMain { public static void main(String args[]) { int[] arr1={7,5,6,1,4,2}; int secondHighest=findSecondLargestNumberInTheArray(arr1); System.out.println("Second largest element in the array : "+ secondHighest); } public static int findSecondLargestNumberInTheArray(int array[]) { // Initialize these to the smallest value possible int highest = Integer.MIN_VALUE; int secondHighest = Integer.MIN_VALUE; // Loop over the array for (int i = 0; i < array.length; i++) { // If current element is greater than highest if (array[i] > highest) { // assign second highest element to highest element secondHighest = highest; // highest element to current element highest = array[i]; } else if (array[i] > secondHighest && array[i]!=highest) // Just replace the second highest secondHighest = array[i]; } // After exiting the loop, secondHighest now represents the second // largest value in the array return secondHighest; } } |
That’s all about how to find second largest number in an array.
I love your blog. Thanks a ton to you. One of the best website to get ready for interviews.
Hi, this code will fail if an array contains duplicate which is also happened to be largest element.
Example: arr[] = {7, 8, 8, 1, 4, 2}
Missed the edge case!! Thank you for bringing it up. Fixed it.
If we change else id condition code works fine all cases,
else if (array[i] > secondHighest && array[i] != highest){
secondHighest = array[i];
}