1280. Pivot Swap Count

Easy1.5 points estimatedTwo PointersArrayGreedy

A warehouse robot sorts parcel weights on a belt. It wants every parcel lighter than pivot to sit before every parcel whose weight is at least pivot, and the order inside each of the two groups does not matter. In one move the robot swaps any two parcels on the belt, not just neighbours.

Return the minimum number of swaps needed. Let c be the number of values in nums that are strictly less than pivot; after sorting, the first c positions must hold exactly those values. Each swap can repair one heavy parcel sitting in the first c positions together with one light parcel sitting after them, which two pointers can pair up. Aim for O(n) time and O(1) extra space.

Example 1

Input:
nums = [5,1,4,2], pivot = 3
Output:
1
Explanation:

Two values are below 3, and the first two slots hold 5 and 1, so one swap (5 with 2) fixes the belt.

Example 2

Input:
nums = [1,2,7,8], pivot = 5
Output:
0
Explanation:

The small values already come first, so no swap is needed.

Constraints

1 ≤ nums.length ≤ 1000

-109 ≤ nums[i], pivot ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
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…