← Back to Heaps
πŸ₯‰

Find the 3rd Largest

2 of 6

Exercise 1: Find the 3rd Largest Element πŸ₯‰

Your Task

Write a function third_largest(nums) that returns the 3rd largest element in a list.

Use heapq!


Examples

print(third_largest([5, 3, 8, 1, 4, 2, 7])) # Output: 5 print(third_largest([10, 20, 30])) # Output: 10 print(third_largest([1, 1, 2, 3, 4])) # Output: 2

Hints

πŸ’‘ Hint 1

heapq.nlargest(k, nums) returns the k largest elements in descending order.

πŸ’‘ Hint 2

The 3rd largest is the last element of heapq.nlargest(3, nums).

βœ… Solution
import heapq def third_largest(nums): return heapq.nlargest(3, nums)[-1]

Why this works: heapq.nlargest(3, nums) gives you [largest, 2nd, 3rd]. The last item [-1] is the 3rd largest!


Bonus Challenge 🌟

What if the list has fewer than 3 elements? Modify your function to return None in that case.

print(third_largest([5, 2])) # Output: None
πŸ’»

Try it yourself

Code: Find the 3rd Largest

Loading Python runtime…
Python …
Loading...
Output
Click "Run" to execute your code...
ℹ️ About this Python environment

βœ… Standard library: heapq, collections, itertools, math, random, functools, datetime, bisect

βœ… Functions, classes, recursion, print()

❌ No file system, subprocess, OS access, or network requests

❌ No pip install (all supported modules are pre-loaded)

⏱️ 5 second execution time limit