1350. Partition Around the Kth

Medium3.5 points estimatedQuickselectArrayTwo Pointers

A leaderboard tool receives n scores in nums and an index k (0-based). Rearrange nums in place so that nums[k] holds exactly the value that index k would hold if the whole array were sorted ascending, every element at an index before k is less than or equal to nums[k], and every element at an index after k is greater than or equal to it. The two sides do not need to be sorted internally, and any rearrangement of the same values that satisfies these conditions is accepted, so the order outside position k does not matter. Nothing is returned: the modified nums is your answer. Aim for expected O(n) time and O(1) extra space, which a quickselect with a three-way partition achieves.

Example 1

Input:
nums = [9,4,7,1,8], k = 2
Output:
[1,4,7,8,9]
Explanation:

The sorted values are 1, 4, 7, 8, 9, so nums[2] must hold 7, with smaller values before it and larger ones after it.

Example 2

Input:
nums = [5,5,5,5], k = 3
Output:
[5,5,5,5]
Explanation:

All four values are equal, so any arrangement already satisfies the rule.

Example 3

Input:
nums = [-3,10,-3,0,6,6], k = 4
Output:
[-3,-3,0,6,6,10]
Explanation:

Sorted, the values are -3, -3, 0, 6, 6, 10, so nums[4] must hold 6, with nothing larger than 6 before it and nothing smaller after it.

Constraints

1 ≤ n ≤ 1000

0 ≤ k < n

-109 ≤ nums[i] ≤ 109

How this problem is judged

Answers
Any valid answer is accepted. A checker tests yours against the problem's rules.
Graded
Your answer is read from nums after your method returns.

Expected complexity

Time
O(n) expected
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…