Find the Runner Up Score | Hackerrank Solution

Introduction

In this post, I am going to write a program in python to find the runner-up score which is a hackerrank solution. In other words, we have to find the second largest element in the list in python.

You may be wondering that this is a very easy program. Believe me guys, this is not so simple. Actually, this is a practice program that is given on the Hackerrank website.

In this program, we will read the scores of participants. After that, we will display the runner up the score. Before moving further, let us see the actual outputs that we need.

Input 1

5
2 3 6 6 5

Output 1

5

In the above input, the first line means the number of participants. So there are five participants If we write a program as a beginner, then we will print 6 as the second-largest element because there are two 6s. But the answer is 5.

I hope you got my point. Now, let us see the actual python program.

Python Program to Find the Runner Up Score

n = int(input())
arr = map(int, input().split())
list1 = list(arr)
list1.sort(reverse = True)
n = len(list1)
for i in range(1, n):
    if list1[0] != list1[i]:
        smx = list1[i]
        break
print(smx)

Using the above python program, you can find the runner up score. The first two lines are given in the hackerrank challenge. See the following steps.

  1. First two lines are reading the inputs.
  2. The variable n and arr are storing number of participants and their scores respectively.
  3. In the third line, we are converting arr object to the list using variable list1.
  4. Now, I have sorted the list in the descending order.
  5. Using for loop and if statement, I am going to find the runner up score. How? I have already sorted the list in descending order, but there is a possibility that I will get two top scores at the beginning. So, using if statement, I am comparing each and every number that they are same or not. If they are not same, that means I got my output. I will store that value in the variable smx.

I hope you have understood the program. Now, let us see one more input and output for better understanding.

Input 2

10
6 6 6 6 6 6 6 6 6 5

Output 2

5

Thank you.

1 thought on “Find the Runner Up Score | Hackerrank Solution”

  1. Hello. Good work! want to mention, with this solution, HackerRank gives you the length of list1 as n in the provided first line. You are reassigning n unnecessarily. Also, I find that if you set high_score = list1[0] you then only have to look for the first result that is less than high_score and print it immediately and break. See below:

    scores = list(arr)
    scores.sort(reverse = True)
    high_score = scores[0]
    for score in scores:
    if score < high_score:
    print(score)
    break

    Reply

Leave a Comment