Find the Second Largest Element

Medium ⏱ 12 min 47% acceptance ★★★★☆ 4.4
Write second_largest(numbers) that returns the second largest distinct value in numbers without using sorted() or .sort(). Scan the list in a single pass. If fewer than 2 distinct values exist, return None.

Examples

Example 1
Input
numbers = [4, 1, 7, 7, 3]
Output
4
Explanation

Largest is 7 (even though it repeats); the next distinct value down is 4.

Example 2
Input
numbers = [5, 5, 5]
Output
None
Explanation

Only one distinct value exists.

Constraints

  • 0 <= len(numbers) <= 10^5

Topics

ListsSearching

Companies

AmazonWalmart

Hints

Hint 1

Track "largest" and "second" while scanning; update both carefully, skipping values equal to the current largest.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.