Python - Given an integer list, find the third maximum number if it exists

Finding the third maximum number in an integer list requires tracking the three largest distinct values. Python provides several approaches: using a tracking algorithm, built-in functions, or set operations to handle duplicates.

Using Tracking Variables

This approach maintains three variables to track the largest, second largest, and third largest values ?

def third_max_num(numbers):
    result = [float('-inf'), float('-inf'), float('-inf')]
    
    for num in numbers:
        if num not in result:
            if num > result[0]: 
                result = [num, result[0], result[1]]
            elif num > result[1]: 
                result = [result[0], num, result[1]]
            elif num > result[2]: 
                result = [result[0], result[1], num]
    
    if float('-inf') in result:
        return max(numbers)
    else:
        return result[2]

numbers = [45, 31, 78, 9, 0, 54, 12, 18]
print("The list is:")
print(numbers)
print("The third maximum number is:")
print(third_max_num(numbers))
The list is:
[45, 31, 78, 9, 0, 54, 12, 18]
The third maximum number is:
45

Using Set and Sorted

This method removes duplicates with a set and sorts to find the third maximum ?

def find_third_max(numbers):
    unique_nums = sorted(set(numbers), reverse=True)
    
    if len(unique_nums) < 3:
        return max(numbers)
    else:
        return unique_nums[2]

numbers = [45, 31, 78, 9, 0, 54, 12, 18]
result = find_third_max(numbers)
print(f"Third maximum: {result}")

# Test with duplicates
numbers_with_duplicates = [10, 10, 5, 3, 3, 1]
result2 = find_third_max(numbers_with_duplicates)
print(f"Third maximum (with duplicates): {result2}")
Third maximum: 45
Third maximum (with duplicates): 1

Using heapq Module

The heapq module provides an efficient way to find the largest elements ?

import heapq

def third_max_heapq(numbers):
    unique_nums = list(set(numbers))
    
    if len(unique_nums) < 3:
        return max(unique_nums)
    
    # Get 3 largest elements
    largest_three = heapq.nlargest(3, unique_nums)
    return largest_three[2]

numbers = [45, 31, 78, 9, 0, 54, 12, 18]
result = third_max_heapq(numbers)
print(f"Third maximum using heapq: {result}")
Third maximum using heapq: 45

Comparison

Method Time Complexity Space Complexity Best For
Tracking Variables O(n) O(1) Memory efficiency
Set + Sorted O(n log n) O(n) Readability
heapq.nlargest O(n log k) O(n) Large datasets

Conclusion

Use the tracking variables approach for optimal performance with O(1) space complexity. The set and sorted method is more readable, while heapq is efficient for finding top-k elements in large datasets.

Updated on: 2026-03-26T02:51:34+05:30

457 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements