Posts

Showing posts from July, 2014

Finding third largest element in an array using Java

Hi everyone, in this blog post, I am writing a Java program to find the third largest element in an array. When we are asked to write a program about finding the third largest element in an array, the trivial solution which comes to our mind is sorting the array and returning the third element from the end. But sorting an array is of time complexity O(nlogn) and   a program always requires to minimize the total time complexity and space complexity. We can do the above program in time O(n). The logic of the program is as follows: Initialize three variables as firstLargest , secondLargest and thirdLargest to Integer.MIN_VALUE Iterate the loop of elements in the array. For each number , check the following steps If firstLargest is less than the number , assign thirdLargest to secondLargest , secondLargest to firstLargest and firstLargest to the number . Else if secondLargest is less than the number and if number not equal to firstLargest , then assign thirdLargest to