Grokking the Coding Interview: Patterns for Coding Questions

0% completed

Kth Smallest Number (easy)

Problem Statement

Given an unsorted array of numbers, find Kth smallest number in it.

Please note that it is the Kth smallest number in the sorted order, not the Kth distinct element.

Note: For a detailed discussion about different approaches to solve this problem, take a look at Kth Smallest Number.

Example 1:

Input: [1, 5, 12, 2, 11, 5], K = 3
Output: 5
Explanation: The 3rd smallest number is '5', as the first two smaller numbers are [1, 2].

Example 2:

.....

.....

.....

Like the course? Get enrolled and start learning!
M

Mitch

· 4 years ago

For the python solution in Kth Smallest Number, why is it that we are negating the values as we push them to the maxHeap?

Image

Show 2 replies
Mohammed Dh Abbas

Mohammed Dh Abbas

· 2 years ago

Max Heap is the wrong approach "we are asking the smallest". my solution

def findKthSmallestNumber(self, nums, k): min_heap = [] for item in nums: heappush(min_heap, item) for i in range(k): out = heappop(min_heap) if i == k - 1: return out
Show 1 reply