05: Finding the 2nd highest number in an array in Java

Requirements gathering

  1. Does the array allow duplicates?
  2. If duplicates are allowed, then do you need to report duplicates? For example, in {2,4, 6, 3, 6, 5}, is 6 or 5 the second highest?

Analysis

  • If duplicates are not allowed, sort the array (Arrays.sort(…)) and get the second last element, which executes in O(nlogn)
  • If duplicates are allowed, loop through each element have two variables to store highest & second highest values. which executes in O(n)

Solution: duplicates are allowed

Output:

sec_highest=5

Java 8 way

Output:

sec_highest=5

So how about parallelizing the code?

In Java SE 8 it’s easy: just replace stream() with parallelStream().


300+ Java & Big Data Interview FAQs

16+ Java Key Areas Interview Q&As

800+ Java Interview Q&As

300+ Java & Big Data Tutorials

Top