Sign in to run and submit your work
Reading is open to everyone. Running code and saving drafts need an account so your work is yours and comes back on your next visit.
or
CODE WORKSPACE
A report shows the slowest request and the one just behind it. If the slowest time appears three times, the runner-up is the next different time, not the same time again.
Write second_largest(values). values is a list of numbers. Return the second largest value that is different from the largest, or None if there is no such value.
Function to write
second_largest(values: list[float]) -> float | NoneThe second largest value that differs from the largest, or None when fewer than two different values exist.
How to approach it
Keep two variables: the largest and the second largest. Update them as you read each value, and skip any value that equals the largest.
Sample cases
+ 3 held back until you submit
a few response times
The largest is 340, and it appears twice. The second largest different value is 210.
Input
Argument 1
[
120,
340,
95,
340,
210
]Returns
210already sorted
The largest is 4, so the answer is 3.
Input
Argument 1
[
1,
2,
3,
4
]Returns
3all the same
There is only one different value, so there is no second largest. The answer is None.
Input
Argument 1
[
5,
5,
5
]Returns
None
empty list
No values at all gives None.
Input
Argument 1
[] (empty list)
Returns
None
Constraints
[9, 9, 5] gives 5, not 9.None when there are fewer than two different values.Worked example
Take [120, 340, 95, 340, 210]. Start with no largest and no runner-up. 120 becomes the largest. 340 is bigger, so 120 becomes the runner-up and 340 the largest. 95 is smaller than 340, and not bigger than 120, so nothing changes. The second 340 equals the largest, so it is skipped. 210 is not the largest, and it is bigger than 120, so it becomes the runner-up. The answer is 210.
The trap: sorting gives [95, 120, 210, 340, 340], and the value second from the end is 340, which is the largest again.
What this tests
A single-pass update with two variables, a common warm-up in phone screens. The two details are the order of the updates and the check on the runner-up. The old largest becomes the runner-up before it is replaced, and the runner-up must be a different value. Sorting works for short lists but costs O(n log n), and interviewers often ask for one pass.
second_largest(values: list[float]) -> float | NoneSubmit for review to find out what your query gets right, what it gets wrong, and how it compares with the best working query for this exercise.
This scenario runs a full workspace — editor, canvas and results side by side. It needs a laptop or desktop to be usable. Open this page on a bigger screen to start building.