710309. Minimum Swaps
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:
- Initialize a variable
swapsto 0. - Iterate through the array from left to right (or from right to left).
- For each element, check if it is at its correct position. If not, increment the
swapscounter and move the element to its correct position. - 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] = 5is not at its correct position (should be at index 4), incrementswapsand movearr[0]to its correct position (arr[3] = 2). Now,arr[0] = 2andarr[1] = 1, both are at their correct positions. - Move to the next element:
arr[2] = 3is not at its correct position (should be at index 2), incrementswapsand movearr[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
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;
}