Open In App

Python Program for Third largest element in an array of distinct elements

Last Updated : 27 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of n integers, find the third largest element. All the elements in the array are distinct integers. 

Example: 

Input: arr[] = {1, 14, 2, 16, 10, 20}
Output: The third Largest element is 14

Explanation: Largest element is 20, second largest element is 16 
and third largest element is 14

Input: arr[] = {19, -10, 20, 14, 2, 16, 10}
Output: The third Largest element is 16

Explanation: Largest element is 20, second largest element is 19 
and third largest element is 16

Naive Approach: 

The task is to first find the largest element, followed by the second-largest element and then excluding them both find the third-largest element. The basic idea is to iterate the array twice and mark the maximum and second maximum element and then excluding them both find the third maximum element, i.e the maximum element excluding the maximum and second maximum.

Algorithm: 

  • First, iterate through the array and find maximum.
  • Store this as first maximum along with its index.
  • Now traverse the whole array finding the second max, excluding the maximum element.
  • Finally, traverse the array the third time and find the third largest element i.e., excluding the maximum and second maximum. 

Below is the implementation of the above approach:

Python3




# Python 3 program to find
# third Largest element in
# an array of distinct elements
import sys
def thirdLargest(arr, arr_size):
 
    # There should be
    # atleast three elements
    if (arr_size < 3):
     
        print(" Invalid Input ")
        return
     
 
    # Find first
    # largest element
    first = arr[0]
    for i in range(1, arr_size):
        if (arr[i] > first):
            first = arr[i]
 
    # Find second
    # largest element
    second = -sys.maxsize
    for i in range(0, arr_size):
        if (arr[i] > second and
            arr[i] < first):
            second = arr[i]
 
    # Find third
    # largest element
    third = -sys.maxsize
    for i in range(0, arr_size):
        if (arr[i] > third and
            arr[i] < second):
            third = arr[i]
 
    print("The Third Largest",
          "element is", third)
 
# Driver Code
arr = [12, 13, 1,
       10, 34, 16]
n = len(arr)
thirdLargest(arr, n)
 
# This code is contributed
# by Smitha


Output

The Third Largest element is 13

Time Complexity: O(n), As the array is iterated thrice and is done in a constant time.
Auxiliary Space: O(1),  No extra space is needed as the indices can be stored in constant space.

Efficient Approach:

The problem deals with finding the third largest element in the array in a single traversal. The problem can be cracked by taking help of a similar problem- finding the second maximum element. So the idea is to traverse the array from start to end and to keep track of the three largest elements up to that index (stored in variables). So after traversing the whole array, the variables would have stored the indices (or value) of the three largest elements of the array.

Algorithm: 

  • Create three variables, first, second, third, to store indices of three largest elements of the array. (Initially all of them are initialized to a minimum value).
  • Move along the input array from start to the end.
  • For every index check if the element is larger than first or not. Update the value of first, if the element is larger, and assign the value of first to second and second to third. So the largest element gets updated and the elements previously stored as largest becomes second largest, and the second largest element becomes third largest.
  • Else if the element is larger than the second, then update the value of second,and the second largest element becomes third largest.
  • If the previous two conditions fail, but the element is larger than the third, then update the third.
  • Print the value of third after traversing the array from start to end.

Below is the implementation of the above approach:

Python3




# Python3 program to find
# third Largest element in
# an array
import sys
def thirdLargest(arr, arr_size):
 
    # There should be
    # atleast three elements
    if (arr_size < 3):
     
        print(" Invalid Input ")
        return
     
    # Initialize first, second
    # and third Largest element
    first = arr[0]
    second = -sys.maxsize
    third = -sys.maxsize
 
    # Traverse array elements
    # to find the third Largest
    for i in range(1, arr_size):
     
        # If current element is
        # greater than first,
        # then update first,
        # second and third
        if (arr[i] > first):
         
            third = second
            second = first
            first = arr[i]
         
 
        # If arr[i] is in between
        # first and second
        elif (arr[i] > second):
         
            third = second
            second = arr[i]
         
        # If arr[i] is in between
        # second and third
        elif (arr[i] > third):
            third = arr[i]
     
    print("The third Largest" ,
                  "element is", third)
 
# Driver Code
arr = [12, 13, 1,
       10, 34, 16]
n = len(arr)
thirdLargest(arr, n)
 
# This code is contributed
# by Smitha


Output

The third Largest element is 13

Time complexity: O(n) as it makes a single linear scan of the list to find the third largest element. The operations performed in each iteration have a constant time complexity, so the overall complexity is O(n). 
Auxiliary space: O(1) as the code only uses a constant amount of extra space.

Method: Using slicing method 

Python3




arr = [12, 13, 1,10, 34, 16]
arr.sort()
print(arr[-3])


Output

13

Time Complexity: O(n*log(n)), As the array is iterated once and is done in a constant time
Auxiliary space: O(1), No extra space is needed as the indices can be stored in constant space.

Method : Using sort() and positive indexing

Python3




arr = [12, 13, 1,10, 34, 16]
arr.sort(reverse=True)
print(arr[2])


Output

13

Time Complexity: O(n)
Auxiliary space: O(1)

Method: Set Approach:

We can convert the array into a set to remove duplicates and then find the maximum element in the set. Next, we can remove this element from the set and repeat this process two more times to find the third maximum element. 

Python3




def thirdLargestSet(arr, arr_size):
    # Check if array has at least 3 elements
    if arr_size < 3:
        print("Invalid Input")
        return
     
    # Convert array to set to remove duplicates
    arr_set = set(arr)
     
    # Find the maximum element in the set
    first_max = max(arr_set)
     
    # Remove the first maximum element from the set
    arr_set.remove(first_max)
     
    # Find the second maximum element in the set
    second_max = max(arr_set)
     
    # Remove the second maximum element from the set
    arr_set.remove(second_max)
     
    # Find the third maximum element in the set
    third_max = max(arr_set)
     
    print("The Third Largest element is", third_max)
 
# Driver code
arr = [12, 13, 1, 10, 34, 16]
n = len(arr)
thirdLargestSet(arr, n)


Output

The Third Largest element is 13

Time complexity: O(n), where n is the number of elements in the array.
Auxiliary space: O(n), where n is the number of elements in the array. 

Please refer complete article on Third largest element in an array of distinct elements for more details!



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads