Full answer
python
def second_largest(nums):
first = second = None
for n in nums:
if first is None or n > first:
first, second = n, first
elif n != first and (second is None or n > second):
second = n
return second
for case in ([4, 9, 2, 9, 7], [5, 5], [], [3], [-1, -5, -3]):
print(case, "->", second_largest(case))
print(sorted(set([4, 9, 2, 9, 7]))[-2])Output:
text
[4, 9, 2, 9, 7] -> 7
[5, 5] -> None
[] -> None
[3] -> None
[-1, -5, -3] -> -3
7The loop keeps two values. A new maximum pushes the old one into second place; a value equal to the maximum is skipped, so duplicates of 9 do not count twice. Lists without two distinct values return None, which the caller must handle, rather than raising an IndexError deep inside. The one-line sorted(set(...))[-2] is fine for small inputs but sorts in O(n log n) and fails on short lists. Interviewers usually want the edge cases discussed: duplicates, negatives, empty input.
python
def second_largest(nums):
first = second = None
for n in nums:
if first is None or n > first:
first, second = n, first
elif n != first and (second is None or n > second):
second = n
return second
for case in ([4, 9, 2, 9, 7], [5, 5], [], [3], [-1, -5, -3]):
print(case, "->", second_largest(case))
print(sorted(set([4, 9, 2, 9, 7]))[-2])Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- Track largest and second largest in one pass
- Skip values equal to the largest
- Return None for fewer than two distinct values
- sorted(set()) works for small inputs
Common mistakes
- Returning the max again when it is duplicated
- Crashing on short lists
Follow-ups
- How would you find the k-th largest?
- What does heapq.nlargest do?
Tips
- List edge cases first