Intermediate Level

Implement the kthSmallestValue method that returns the kth smallest value from the array.

The input contains an integer array nums, its length size, and an integer k. Your task is to return the kth smallest value in the array.

The value of k is 1-based. That means k = 1 returns the smallest value, k = 2 returns the second smallest value, and so on. Duplicate values are counted as separate positions.

Example 1

Input
nums (int[]) = [7,10,4,3,20,15]
size (int) = 6
k (int) = 3
Returns (int) 7

Example 2

Input
nums (int[]) = [1,1,2]
size (int) = 3
k (int) = 2
Returns (int) 1

Example 3

Input
nums (int[]) = [5]
size (int) = 1
k (int) = 1
Returns (int) 5

The simple way is to sort the array in ascending order.

After sorting, the smallest value is at index 0. Since k is 1-based, the kth smallest value is at index k - 1.

Pseudocode:

function kthSmallestValue(nums, size, k):
    sort nums in ascending order
    return nums[k - 1]
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.