Problem · Array

Minimum Swaps to Group Values at Most K

Learn this problem
MediumMyntra logoMyntraINTERNONSITE INTERVIEW

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

drafts saved locally
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