DEV Community

Lokeshwaran S
Lokeshwaran S

Posted on

Kth Smallest Element - CA07

My Thinking and Approach


Introduction

In this problem, I was given an array of integers and asked to find the kth smallest element in the array.

The kth smallest element is based on the sorted order of the array.


Problem Statement

  • Given an array of integers arr

  • Given an integer k

  • Find the kth smallest element

  • Note:

    • The kth smallest is based on sorted order

My Initial Thought

At first, I considered:

  • Sorting the array
  • Returning the element at index k - 1

This approach is simple and works correctly.


Key Observation

Sorting gives the correct answer:

  • After sorting:

    • 1st smallest → index 0
    • kth smallest → index k - 1

Optimized Approach

I decided to:

  • Sort the array
  • Return the element at index k - 1

Logic:

  • Sort the array in ascending order
  • Return arr[k - 1]

My Approach (Step-by-Step)

  1. Sort the array
  2. Find the element at index k - 1
  3. Return that element

Code (Python)

def kthSmallest(arr, k):
    arr.sort()
    return arr[k - 1]
Enter fullscreen mode Exit fullscreen mode

Example Walkthrough

Input:

arr = [10, 5, 4, 3, 48, 6, 2, 33, 53, 10], k = 4
Enter fullscreen mode Exit fullscreen mode

Steps:

  • Sort → [2, 3, 4, 5, 6, 10, 10, 33, 48, 53]
  • 4th smallest → index 3 → value = 5

Output:

5
Enter fullscreen mode Exit fullscreen mode

Complexity Analysis

Type Complexity
Time Complexity O(n log n)
Space Complexity O(1)

Key Takeaways

  • Sorting helps in finding order-based elements
  • Indexing plays an important role
  • Simple approach is often sufficient

Conclusion

This problem helped me understand how sorting can be used to solve order-based problems like finding the kth smallest element.

It is simple and effective for most cases.


Top comments (0)