Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to find runner-up score
Finding the runner-up score means identifying the second highest score in a list of participants. This is a common problem in competitive programming and data analysis.
So, if the input is like scores = [5,8,2,6,8,5,8,7], then the output will be 7 because the winner score is 8 and second largest score is 7.
Algorithm
To solve this, we will follow these steps −
- Initialize winner := -99999
- Initialize runner_up := -99999
- For each score in the list, do
- If score > winner, then
- runner_up := winner
- winner := score
- Otherwise when score < winner and score > runner_up, then
- runner_up := score
- If score > winner, then
- Return runner_up
Method 1: Using Two Variables
This approach tracks the highest and second highest scores in a single pass ?
def solve(scores):
winner = -99999
runner_up = -99999
for score in scores:
if score > winner:
runner_up = winner
winner = score
elif score < winner and score > runner_up:
runner_up = score
return runner_up
scores = [5, 8, 2, 6, 8, 5, 8, 7]
result = solve(scores)
print(f"Runner-up score: {result}")
Runner-up score: 7
Method 2: Using Set and Sorted
Remove duplicates and sort to get the second highest value ?
def find_runner_up(scores):
unique_scores = list(set(scores))
unique_scores.sort(reverse=True)
return unique_scores[1] if len(unique_scores) >= 2 else None
scores = [5, 8, 2, 6, 8, 5, 8, 7]
result = find_runner_up(scores)
print(f"Runner-up score: {result}")
Runner-up score: 7
Method 3: Using heapq for Large Datasets
For very large datasets, use heap to efficiently find the two largest elements ?
import heapq
def find_runner_up_heap(scores):
unique_scores = list(set(scores))
if len(unique_scores) < 2:
return None
# Get two largest elements
two_largest = heapq.nlargest(2, unique_scores)
return two_largest[1]
scores = [5, 8, 2, 6, 8, 5, 8, 7]
result = find_runner_up_heap(scores)
print(f"Runner-up score: {result}")
Runner-up score: 7
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Two Variables | O(n) | O(1) | Most efficient for general use |
| Set + Sort | O(n log n) | O(n) | Simple and readable |
| heapq | O(n log 2) | O(n) | Large datasets with many duplicates |
Conclusion
The two-variable approach is most efficient with O(n) time and O(1) space complexity. Use set + sort for simpler, more readable code when performance isn't critical.
