FastPrepMinimum Swaps to Group Values at Most K

Minimum Swaps to Group Values at Most K

Myntra logoMyntra● MediumINTERNONSITE INTERVIEW
Learn

Problem 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) → int

Examples

Example 1

nums = [2,1,5,6,3]k = 3return = 1

There 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 = 0

All values qualify and already form one contiguous block.

Constraints

  • 0 <= nums.length <= 10^5.
  • -10^9 <= nums[i], k <= 10^9.

More Myntra problems

See Myntra hiring insights
public int minSwapsToGroup(int[] nums, int k) {
    // Return the minimum number of arbitrary-position swaps.
}
nums[2,1,5,6,3]
k3
expected1
Checking account…