Problem · Array
Minimum Swaps to Group Values at Most K
Learn this problemProblem statement
You are given an integer array nums and an integer k. A value is qualifying when it is at most k.
In one operation, you may swap values at any two positions. Return the minimum swaps required to place all qualifying values in one contiguous block. If there are zero or one qualifying values, return 0.
Function
minSwapsToGroup(nums: int[], k: int) → intExamples
Example 1
nums = [2,1,5,6,3]k = 3return = 1There are three qualifying values. The window [2, 1, 5] contains one nonqualifying value, so one arbitrary-position swap is sufficient.
Example 2
nums = [1,2,3]k = 3return = 0All values qualify and already form one contiguous block.
Constraints
0 <= nums.length <= 10^5.-10^9 <= nums[i], k <= 10^9.