Python Program to find the second largest element in an array

In this article, we will write a Python program to find the second largest element in a given array.

Example

Input: arr[] = {2, 42, 13, 64, 1}
Output: 42

Input: arr[] = {2, 3, 4, 5, 5}
Output: 4

Input: arr[] = {2, 2, 2}
Output: There is no second largest element in the given array

We will solve this problem using two strategies.

Method 1: Using sort() function

In this method first, we will sort the given array in ascending order and return the second largest element which is not equal to the largest element of the array.

def second_largest_num(arr):
    arr.sort()
    n = len(arr)
    if (n<2):
        print("Invalid input")
    for i in range(n-2, -1, -1):
        if (arr[i] != arr[n-1]):
            print("The second largest element of the given array is ", arr[i])
            return
    print("There is no second largest element in the given array")

arr = [2, 42, 13, 64, 1]
print("The given array is ", str(arr))
second_largest_num(arr)

arr1 = [2, 3, 4, 5, 5]
print("The given array is ", str(arr1))
second_largest_num(arr1)

arr2 = [2, 2, 2]
print("The given array is ", str(arr2))
second_largest_num(arr2)

Output

The given array is [2, 42, 13, 64, 1]
The second largest element of the given array is 42
The given array is [2, 3, 4, 5, 5]
The second largest element of the given array is 4
The given array is [2, 2, 2]
There is no second largest element in the given array

Method 2: Find the second largest element in an array with Python

1. Use the max() method to find the maximum value.

2. Firstly, traverse the array and find the largest element of the given array.

3. Now again traverse the array and find the second largest array by comparing each element that is not equal to the largest element.

def second_largest_num(arr):
    n = len(arr)
    large = -100000
    sen_large = -100000
    for i in range(0, n):
        large = max(large, arr[i])
    
    for i in range(0, n):
        if (arr[i]!=large):
            sen_large = max(sen_large, arr[i])

    if (sen_large == -100000):
        print("There is no second largest element in the given array")
    else:
        print("The second largest element in the given array is ", sen_large)

arr = [9, 9, 9]
print("The given array is ", str(arr))
second_largest_num(arr)

arr1 = [2, 4, 178, 1278, 18, 1]
print("The given array is ", str(arr1))
second_largest_num(arr1)

arr2 = [9, 78, 78]
print("The given array is ", str(arr2))
second_largest_num(arr2)

Output

The given array is [9, 9, 9]
There is no second largest element in the given array
The given array is [2, 4, 178, 1278, 18, 1]
The second largest element in the given array is 178
The given array is [9, 78, 78]
The second largest element in the given array is 9

Also, refer:

Leave a Reply

Your email address will not be published.