Problem 231939 · easy · Level 02 Linear Data Structures

Runner-Up Score

lists · traversal

A Python list is an array: its values sit side by side in memory, so nums[i] is instant and a for loop visits every element once. Most array problems are solved by one careful pass while remembering a little state.

A quiz night's scoreboard holds every team's score in nums. The runner-up prize goes to the second largest value: the highest score that is strictly lower than the winning score. Ties do not change this: several teams may share the winning score, and several may share the runner-up score, but a repeated score is still only one score. When every team has the same score, or there are fewer than two scores, there is no runner-up: return None.

Examples

Input:  nums = [3, 1, 4, 1, 5]
Output: 4
Explanation: the distinct values are 1, 3, 4, 5; the second largest is 4.
Input:  nums = [2, 2, 2]
Output: None
Explanation: there is only one distinct value.
Input:  nums = [9, 4, 9, 7, 7]
Output: 7
Explanation: the maximum 9 appears twice, but a second 9 is not a second largest value. The largest value below 9 is 7 (it appears twice too).
Input:  nums = [1, 2]
Output: 1

Constraints

  • 0 <= len(nums) <= 1000
  • -10**4 <= nums[i] <= 10**4

Goals

  • Walk a list once while keeping track of the best values seen so far
  • Handle duplicates and lists that are too short to have an answer
Starting Python…