0
0
PythonProgramBeginner · 2 min read

Python Program to Find Second Largest in Array

You can find the second largest number in an array in Python by using sorted(set(arr))[-2] or by iterating through the array to track the largest and second largest values.
📋

Examples

Input[1, 2, 3, 4, 5]
Output4
Input[10, 10, 9, 8]
Output9
Input[5, 5, 5]
OutputNo second largest element
🧠

How to Think About It

To find the second largest number, first identify the largest number in the array. Then look for the largest number that is smaller than the largest one. If all numbers are the same, there is no second largest.
📐

Algorithm

1
Get the input array.
2
Remove duplicates to avoid counting the same number twice.
3
Sort the unique numbers in ascending order.
4
Check if there are at least two unique numbers.
5
If yes, return the second last number as the second largest.
6
Otherwise, indicate that no second largest element exists.
💻

Code

python
def second_largest(arr):
    unique_nums = list(set(arr))
    if len(unique_nums) < 2:
        return "No second largest element"
    unique_nums.sort()
    return unique_nums[-2]

# Example usage
arr = [10, 10, 9, 8]
print(second_largest(arr))
Output
9
🔍

Dry Run

Let's trace the example array [10, 10, 9, 8] through the code

1

Remove duplicates

Input array: [10, 10, 9, 8] -> Unique numbers: [8, 9, 10]

2

Check length

Unique numbers length is 3, which is >= 2, so continue

3

Sort unique numbers

Sorted unique numbers: [8, 9, 10]

4

Return second largest

Second largest number is unique_nums[-2] = 9

StepUnique NumbersActionResult
1[10, 10, 9, 8]Remove duplicates[8, 9, 10]
2[8, 9, 10]Check length >= 2True
3[8, 9, 10]Sort[8, 9, 10]
4[8, 9, 10]Return second largest9
💡

Why This Works

Step 1: Remove duplicates

Using set() removes repeated numbers so we only consider unique values.

Step 2: Check if second largest exists

If there are fewer than two unique numbers, there is no second largest number.

Step 3: Sort unique numbers

Sorting helps us easily pick the second largest by accessing the second last element.

Step 4: Return result

The second largest number is the element before the largest in the sorted list.

🔄

Alternative Approaches

Iterative tracking
python
def second_largest(arr):
    first = second = float('-inf')
    for num in arr:
        if num > first:
            second = first
            first = num
        elif first > num > second:
            second = num
    return second if second != float('-inf') else "No second largest element"

print(second_largest([10, 10, 9, 8]))
This method finds the second largest in one pass without sorting, which is faster for large arrays.
Using heapq module
python
import heapq

def second_largest(arr):
    unique_nums = list(set(arr))
    if len(unique_nums) < 2:
        return "No second largest element"
    largest_two = heapq.nlargest(2, unique_nums)
    return largest_two[1]

print(second_largest([10, 10, 9, 8]))
Using heapq.nlargest is efficient for large data and directly returns the top two largest unique numbers.

Complexity: O(n log n) time, O(n) space

Time Complexity

Sorting the unique elements takes O(n log n) time, where n is the number of elements in the array.

Space Complexity

Creating a set of unique elements uses O(n) extra space.

Which Approach is Fastest?

The iterative tracking method runs in O(n) time and O(1) space, making it faster and more memory efficient than sorting.

ApproachTimeSpaceBest For
Sorting unique elementsO(n log n)O(n)Simple code, small to medium arrays
Iterative trackingO(n)O(1)Large arrays, performance critical
Heapq.nlargestO(n log k)O(n)When needing top k largest elements efficiently
💡
Always remove duplicates before finding the second largest to avoid errors.
⚠️
Beginners often forget to handle arrays with all identical elements, causing errors or wrong results.