19. Kth Smallest Element

The problem can be found at the following link: Question Link

Problem Description

Given an array arr[] and an integer k where k is smaller than the size of the array, the task is to find the kth smallest element in the given array. It is given that all array elements are distinct.

Examples:

Input:

arr[] = [7, 10, 4, 3, 20, 15], k = 3

Output:

7

Explanation: The 3rd smallest element in the given array is 7.

Input:

arr[] = [7, 10, 4, 20, 15], k = 4

Output:

15

Explanation: The 4th smallest element in the given array is 15.

Approach

  1. Initial Setup:

    • Determine the minimum and maximum elements in the array. These values help define the range of the array elements.

    • Calculate the range of elements in the array as max_element - min_element + 1.

  2. Frequency Array:

    • Create a frequency array of size range to store the count of each element in the array.

    • Populate this frequency array by iterating through the input array and incrementing the count at the index corresponding to each element.

  3. Finding the Kth Smallest Element:

    • Iterate through the frequency array, maintaining a running count of elements encountered.

    • Once the running count reaches or exceeds k, the current index in the frequency array corresponds to the kth smallest element in the original array.

Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n + max_element), as we first scan the array to populate the frequency array, and then scan the frequency array to determine the kth smallest element.

  • Expected Auxiliary Space Complexity: O(max_element), since we use a frequency array with a size based on the range of array elements.

Code (C++)

Code (Java)

Code (Python)

Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


📍Visitor Count

Last updated