DEV Community

Cover image for Athlete Sort - HackerRank Solution in Python
Deepak Raj
Deepak Raj

Posted on • Originally published at codeperfectplus.com on

Athlete Sort - HackerRank Solution in Python

Athlete sort - HackerRank is medium difficulty problem of python based on sorting and nested list. It is part of python practice problems of HackerRank. In this post we will see how we can solve this challenge in Python

Problem Statement and Explanation

In this problem statement we have to sort the given spreadsheet with respect to the Kth column. The spreadsheet consists of N rows and M columns. We have to print the sorted table.

Suppose the given spreadsheet is

Sr. No. Age Marks Height Weight Roll No. class
1 10 12 170 40 3 8
2 12 12 180 50 1 9
3 8 10 160 45 2 7

and we have to sort the spreadsheet with respect to the Kth column. Suppose K = 1 then the sorted spreadsheet will be based on the Age column.

Sr. No. Age Marks Height Weight Roll No. class
3 8 10 160 45 2 7
1 10 12 170 40 3 8
2 12 12 180 50 1 9

Input Format

  • The first line contains N and M separated by a space.
  • The next N lines contains M elements separated by a space.
  • In the last line we have to enter the value of K.

Output Format

  • Print the N lines of the sorted table. Each line should contain the space separated elements.

Constraints

  • 1 <= N, M <= 1000
  • 0 <= K < M
  • X <= 100 where X is any element in the table.

Note : K is indexed from 0 to M-1 i.e. the first column is indexed as 0.

There are two solution provided in this post. First one is the using the inbuilt sort() and lambda function and the second one is using nested loops and comparing the values. If the first value is greater than the second value then we will swap the values.

After sorting the spreadsheet we have to print the sorted spreadsheet. The output of the above spreadsheet will be in console as



7 1 0
10 2 5
6 5 9
9 9 9
1 23 12



Enter fullscreen mode Exit fullscreen mode

Athlete Sort HackerRank Solution in Python

Time Complexity of the Solution

  • The time complexity of the above first solution is O(n log n) because we are using the inbuilt sort() function which has the time complexity of O(n log n).

  • The time complexity of the above second solution is O(n^2) because we are using the nested loops and comparing the values. If the first value is greater than the second value then we will swap the values.

Image description

Problem statement is taken from Hackerrank, and the solutions are implemented by CodePerfectPlus team

Other Article By Author

30 Days of Code SubReddit

Top comments (0)