Python Program for Third largest element in an array of distinct elements
Last Updated :
27 Feb, 2023
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
OutputThe 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
OutputThe 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])
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])
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)
OutputThe 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!
Similar Reads
Python Program for Last duplicate element in a sorted array
We have a sorted array with duplicate elements and we have to find the index of last duplicate element and print index of it and also print the duplicate element. If no such element found print a message. Examples: Input : arr[] = {1, 5, 5, 6, 6, 7} Output : Last index: 4 Last duplicate item: 6 Inpu
2 min read
Python Program for Least frequent element in an array
Given an array, find the least frequent element in it. If there are multiple elements that appear least number of times, print any one of them.Examples : Input : arr[] = {1, 3, 2, 1, 2, 2, 3, 1} Output : 3 3 appears minimum number of times in given array. Input : arr[] = {10, 20, 30} Output : 10 or
3 min read
Python3 Program for Check for Majority Element in a sorted array
Question: Write a function to find if a given integer x appears more than n/2 times in a sorted array of n integers. Basically, we need to write a function say isMajority() that takes an array (arr[] ), arrayâs size (n) and a number to be searched (x) as parameters and returns true if x is a majorit
7 min read
Python Program for Number of local extrema in an array
You are given an array on n-elements. An extrema is an elements which is either greater than its both of neighbors or less than its both neighbors. You have to calculate the number of local extrema in given array. Note : 1st and last elements are not extrema.Examples : Input : a[] = {1, 5, 2, 5} Out
2 min read
Python3 Program for Maximize elements using another array
Given two arrays with size n, maximize the first array by using the elements from the second array such that the new array formed contains n greatest but unique elements of both the arrays giving the second array priority (All elements of second array appear before first array). The order of appeara
4 min read
Python program to find N largest elements from a list
Given a list of integers, the task is to find N largest elements assuming size of list is greater than or equal o N. Examples : Input : [4, 5, 1, 2, 9] N = 2 Output : [9, 5] Input : [81, 52, 45, 10, 3, 2, 96] N = 3 Output : [81, 96, 52] A simple solution traverse the given list N times. In every tra
5 min read
Python program to test if all elements in list are maximum of K apart
Given a list of numbers, the task is to write a Python program to test if all elements are maximum of K apart. Examples: Input : test_list = [475, 503, 425, 520, 470, 500], K = 100Output : True Explanation : Maximum element is 520 and minimum is 425, 520-425 = 95, which is less than 100, hence eleme
5 min read
Python Program to extracts elements from the list with digits in increasing order
Given a List of elements, extract all elements which have digits that are increasing in order. Input : test_list = [1234, 7373, 3643, 3527, 148, 49] Output : [1234, 148, 49] Explanation : All elements have increasing digits.Input : test_list = [12341, 7373, 3643, 3527, 1481, 491] Output : [] Explana
5 min read
Python3 Program for Search an element in a sorted and rotated array
An element in a sorted array can be found in O(log n) time via binary search. But suppose we rotate an ascending order sorted array at some pivot unknown to you beforehand. So for instance, 1 2 3 4 5 might become 3 4 5 1 2. Devise a way to find an element in the rotated array in O(log n) time. Examp
8 min read
Python Program to Find k maximum elements of array in original order
Given an array arr[] and an integer k, we need to print k maximum elements of given array. The elements should printed in the order of the input.Note : k is always less than or equal to n. Examples: Input : arr[] = {10 50 30 60 15} k = 2 Output : 50 60 The top 2 elements are printed as per their app
3 min read