CA 07 - Kth Smallest

Kth Smallest

 Given an integer array arr[] and an integer k, your task is to find and return the kth smallest element in the given array.

Input: arr[] = [10, 5, 4, 3, 48, 6, 2, 33, 53, 10], k = 4
Output: 5 Explanation: 4th smallest element in the given array is 5.

Input: arr[] = [7, 10, 4, 3, 20, 15], k = 3
Output: 7 Explanation: 3rd smallest element in the given array is 7.

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

CODE:

    The problem could be solved by sorting the array into a sorted array and then access the k-1 element to obtain the Kth smallest element from the array. In order to have a reduced time complexity throughout all the cases we will make use of the merge sorting method. 

Time complexity: O(nlog n )

class Solution:
   
    def merge_sort(self,arr):
        if len(arr) <= 1:
            return arr
   
        mid = len(arr) // 2
   
        left = self.merge_sort(arr[:mid])
        right = self.merge_sort(arr[mid:])
   
        return self.merge(left, right)


    def merge(self,left, right):
        result = []
        i = j = 0
   
        while i < len(left) and j < len(right):
            if left[i] < right[j]:
                result.append(left[i])
                i += 1
            else:
                result.append(right[j])
                j += 1
   
        result.extend(left[i:])
        result.extend(right[j:])
   
        return result
       
    def kthSmallest(self, arr, k):

        arr = self.merge_sort(arr)
        return arr[k-1]

But the expected time complexity is O(n log k)

To obtain this time complexity we make use of timsort. Timsort is used in sort() function. thus: 

class Solution:
       
    def kthSmallest(self, arr, k):
        arr.sort()
        return arr[k-1]


Comments

Popular posts from this blog

CA 04 - Two Sum & Sorted Two Sum

CA 05 - Reverse the array

CA 21 - Basic Select SQL Queries