710309. Minimum Swaps

Medium

Minimum Swaps

Slug: minimum-swaps-1649134975

Difficulty: Medium

Id: 710309

Topic Tags: Greedy, Algorithms

Company Tags: None

Summary

In this problem, we are given a sorted array arr of n elements and an integer k. The task is to find the minimum number of swaps required to sort the array in ascending order. A swap operation involves swapping two elements at different positions in the array.

Detailed Explanation

The approach to solve this problem is by using a greedy algorithm, where we try to maximize the number of correct placements of an element in its correct position without doing any additional work later. Here's how it works:

  1. Initialize a variable swaps to 0.
  2. Iterate through the array from left to right (or from right to left).
  3. For each element, check if it is at its correct position. If not, increment the swaps counter and move the element to its correct position.
  4. Continue this process until the end of the array.

Now, let's break down a step-by-step example:

Let's say we have an unsorted array [5, 1, 3, 2]. We want to find the minimum number of swaps required to sort it in ascending order. Here's how our algorithm would work:

  • Start from the left: arr[0] = 5 is not at its correct position (should be at index 4), increment swaps and move arr[0] to its correct position (arr[3] = 2). Now, arr[0] = 2 and arr[1] = 1, both are at their correct positions.
  • Move to the next element: arr[2] = 3 is not at its correct position (should be at index 2), increment swaps and move arr[2] to its correct position. Now, arr[0] = 1, arr[1] = 2, arr[2] = 3, all are at their correct positions.
  • The remaining elements (arr[3] = 5) is already in its correct position.

So, the minimum number of swaps required to sort this array is 2 (swapping the first two elements and then swapping the third element with itself).

Time complexity: O(n) as we are iterating through the array once. Space complexity: O(1) as we only use a constant amount of space to store the swaps counter.

Optimized Solutions

Java

View on GeeksforGeeks
public int minSwaps(int[] arr, int k) {
    int swaps = 0;
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] != i + 1) {
            swaps++;
            int correctIndex = findCorrectIndex(arr, i);
            swap(arr, i, correctIndex);
        }
    }
    return swaps;
}

private int findCorrectIndex(int[] arr, int i) {
    for (int j = i; j < arr.length; j++) {
        if (arr[j] == i + 1) {
            return j;
        }
    }
    return -1; // not found
}

private void swap(int[] arr, int i, int j) {
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.