Tutorialspoint
Problem
Solution
Submissions

Find the Kth Smallest Element in a List

Certification: Intermediate Level Accuracy: 100% Submissions: 4 Points: 5

Write a Python function to find the Kth smallest element in a given list of integers.

Example 1
  • Input: nums = [7, 10, 4, 3, 20, 15], K = 3
  • Output: 7
  • Explanation:
    • Step 1: Sort the list [7, 10, 4, 3, 20, 15] in ascending order: [3, 4, 7, 10, 15, 20].
    • Step 2: Find the element at index K-1 (since indexing starts at 0): element at index 2 is 7.
    • Step 3: Return 7 as the 3rd smallest element.
Example 2
  • Input: nums = [1, 2, 3, 4, 5], K = 1
  • Output: 1
  • Explanation:
    • Step 1: Sort the list [1, 2, 3, 4, 5] in ascending order: [1, 2, 3, 4, 5].
    • Step 2: Find the element at index K-1 (since indexing starts at 0): element at index 0 is 1.
    • Step 3: Return 1 as the 1st smallest element.
Constraints
  • 1 <= len(list) <= 10^5
  • 1 <= K <= len(list)
  • -10^9 <= list[i] <= 10^9
  • Time Complexity: O(n log n) or better
  • Space Complexity: O(n)
ListTutorialspointPwC
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Sort the list and return the Kth element: sorted_list = sorted(lst); return sorted_list[K-1]
  • Use a min-heap to efficiently find the Kth smallest element: import heapq; heapq.nsmallest(K, lst)[-1]
  • Handle edge cases where K is out of bounds or the list is empty.

Steps to solve by this approach:

 Step 1: Check for edge cases: empty list or invalid k value

 Step 2: Sort the input list in ascending order
 Step 3: Access the (k-1)th element in the sorted list
 Step 4: Return the element at index (k-1)
 Step 5: This works because after sorting, the kth smallest element is at index (k-1)
 Step 6: Handle invalid inputs by returning None for impossible cases
 Step 7: Return the kth smallest element found in the sorted list

Submitted Code :