2 of 6
Write a function third_largest(nums) that returns the 3rd largest element in a list.
Use heapq!
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
heapq.nlargest(k, nums) returns the k largest elements in descending order.
The 3rd largest is the last element of heapq.nlargest(3, nums).
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!
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
β 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