Thursday, 30 May 2019

Java program to find second largest number in an array

       This is a common interview question for mid-level Java developers. Interviewers use this question to evaluate a candidate's problem-solving skills, coding logic, and ability to write an efficient, optimized solution.

In this post, we will discuss two different approaches to find the second largest number in a given array, along with their implementations and performance considerations.


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.


No comments:

Post a Comment