FastPrepMinimum Swaps to Sort an Array

Minimum Swaps to Sort an Array

Postman logoPostman● MediumFULLTIMEOA
Learn

Problem statement

Given an array values of distinct integers, return the minimum number of swaps of any two positions needed to arrange the array in strictly increasing order.

Function

minimumSwaps(values: int[]) → int

Examples

Example 1

values = [4,3,1,2]return = 3

One optimal sequence swaps the values at positions 0 and 2, then positions 1 and 3, then positions 2 and 3, producing [1,2,3,4].

Example 2

values = [1,5,4,3,2]return = 2

Swap 5 with 2, then swap 4 with 3.

Constraints

  • 1 ≤ values.length ≤ 2 × 10^5
  • -10^9 ≤ values[i] ≤ 10^9
  • All values are distinct.

More Postman problems

See Postman hiring insights
public int minimumSwaps(int[] values) {
    // write your code here
}
values[4,3,1,2]
expected3
Checking account…