This is familiar interview question for the middle level developers. Interviewer will check the coding logic of the candidate and best solution(performance level).
In this question, there are two solutions to find the second largest number in the given array.
1) Using Sort - This is simple one, you have to sort the array in descending order and return the second element from the sorted array. Time complexity of this approach is O(nlogn)
2) Single Loop using Traversal :- Use single for loop,Inside for loop find the largest number and second condition to find the second largest number using first largest number.
Time complexity of this approach is O(n). This is the better solution compared to first one.
Let's see the below example to find the second largest number in an array,
SecondLargestNumber.java,
In this question, there are two solutions to find the second largest number in the given array.
1) Using Sort - This is simple one, you have to sort the array in descending order and return the second element from the sorted array. Time complexity of this approach is O(nlogn)
2) Single Loop using Traversal :- Use single for loop,Inside for loop find the largest number and second condition to find the second largest number using first largest number.
Time complexity of this approach is O(n). This is the better solution compared to first one.
Let's see the below example to find the second largest number in an array,
SecondLargestNumber.java,
package com.test;
public class SecondLargestNumber {
public static void main(String[] args) {
int[] arr = {2, 3, 4, 10, 28, 38, 88, 10};
int firstLargeNum = 0;
int secondLargeNum = 0;
for (int i = 0; i<arr.length; i++) {
if (arr[i] > firstLargeNum) {
secondLargeNum = firstLargeNum;
firstLargeNum = arr[i];
} else if(arr[i] > secondLargeNum && arr[i] != firstLargeNum) {
secondLargeNum = arr[i];
}
}
System.out.println("Second Largest Number is - "+secondLargeNum);
}
}
Output:-
Second Largest Number is - 38.
Related Posts:--
1) Java Code to Print the Numbers as Pyramid - Examples
2) Java Program to find the Missing Number in an Array
3) Java program to print the first n prime numbers
4) Java Program to check the given number is a palindrome or not
5) Write a Java program to print the Floyd's triangle