Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Find Kth Largest Element

Select the kth largest list position with Python sorted. Students validate a one-based rank, convert it to an index, and retain repeated values as ranks.

AdvancedPhase 4 - Level 5: Logical & AppliedExample 11 of 14
find-kth-largest-element.py
1# Take array
2n = int(input("Enter array size: "))
3arr = []
4for i in range(n):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7k = int(input("Enter k: "))
8
9# Sort in descending order
10arr_sorted = sorted(arr, reverse=True)
11
12if 1 <= k <= len(arr_sorted):
13 print(f"{k}th largest: {arr_sorted[k-1]}")
14else:
15 print("Invalid k")

Output

Enter array size: 5
Element 1: 10
Element 2: 5
Element 3: 20
Element 4: 15
Element 5: 8
Enter k: 2
2th largest: 15

In this one

  • Convert ranks to indexes
  • Validate both rank bounds
  • Retain duplicate positions

How it works

  1. 1

    Create a descending sorted copy.

  2. 2

    Require k between one and its length.

  3. 3

    Select index k - 1 or report invalid rank.

Edge cases

What happens for k = 0?

What happens for k = 0?

It must be rejected as an invalid one-based rank.

Are duplicate values skipped?

Are duplicate values skipped?

No. They occupy separate sorted positions.

What's going on

sorted(arr, reverse=True) creates a descending copy. A valid rank k selects position k - 1 because indexes begin at zero.

Repeated values keep their separate positions, so [9, 9, 7] has second-largest position nine. The rank must be at least one as well as no larger than the list length; otherwise negative indexing could produce an unintended answer.

What happens for k = 0? It must be rejected as an invalid one-based rank.

Are duplicate values skipped? No. They occupy separate sorted positions.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which index corresponds to rank three?

Pick an answer to check it.

Question 2

What happens for k = 0?

Pick an answer to check it.

Questions people ask

What happens for k = 0?

It must be rejected as an invalid one-based rank.

Are duplicate values skipped?

No. They occupy separate sorted positions.

Which index corresponds to rank three?

2.