🧠
Better Approach (Index-based Swapping Using Cyclic Sort)
💡 This approach uses the problem's constraint that numbers are from 1 to n to place each number directly at its correct index, avoiding full sorting.
Intuition
Iterate through the array and swap elements to their correct positions until all elements are placed correctly.
Algorithm
- Initialize index i = 0.
- While i < n, check if element at i is at correct position (arr[i] == i+1).
- If not, swap arr[i] with arr[arr[i] - 1] to place it correctly.
- If yes, increment i.
- Repeat until all elements are placed correctly.
💡 The key is to keep swapping until the current element is at its correct index, then move forward.
def cyclic_sort(arr):
i = 0
n = len(arr)
while i < n:
correct_index = arr[i] - 1
if arr[i] != arr[correct_index]:
arr[i], arr[correct_index] = arr[correct_index], arr[i]
else:
i += 1
return arr
# Driver code
if __name__ == '__main__':
arr = [3, 1, 5, 4, 2]
print(cyclic_sort(arr))
Line Notes
i = 0Start from the first index to check placement, ensuring we scan the entire array.
correct_index = arr[i] - 1Calculate the correct index for the current element based on its value.
if arr[i] != arr[correct_index]:Check if current element is not at its correct position to decide if swap is needed.
arr[i], arr[correct_index] = arr[correct_index], arr[i]Swap to place the element at its correct index, moving closer to sorted array.
public class CyclicSort {
public static int[] cyclicSort(int[] arr) {
int i = 0;
int n = arr.length;
while (i < n) {
int correctIndex = arr[i] - 1;
if (arr[i] != arr[correctIndex]) {
int temp = arr[i];
arr[i] = arr[correctIndex];
arr[correctIndex] = temp;
} else {
i++;
}
}
return arr;
}
public static void main(String[] args) {
int[] arr = {3, 1, 5, 4, 2};
int[] sorted = cyclicSort(arr);
System.out.println(java.util.Arrays.toString(sorted));
}
}
Line Notes
int i = 0;Initialize index to start scanning the array from the beginning.
int correctIndex = arr[i] - 1;Find the correct position for the current element based on its value.
if (arr[i] != arr[correctIndex]) {Check if the element is misplaced and needs swapping.
int temp = arr[i]; arr[i] = arr[correctIndex]; arr[correctIndex] = temp;Swap elements to correct positions, moving closer to sorted array.
#include <iostream>
#include <vector>
using namespace std;
vector<int> cyclicSort(vector<int>& arr) {
int i = 0;
int n = arr.size();
while (i < n) {
int correctIndex = arr[i] - 1;
if (arr[i] != arr[correctIndex]) {
swap(arr[i], arr[correctIndex]);
} else {
i++;
}
}
return arr;
}
int main() {
vector<int> arr = {3, 1, 5, 4, 2};
vector<int> sorted = cyclicSort(arr);
for (int num : sorted) cout << num << ' ';
cout << endl;
return 0;
}
Line Notes
int i = 0;Start scanning from the first element to ensure all elements are checked.
int correctIndex = arr[i] - 1;Calculate the target index for the current element based on its value.
if (arr[i] != arr[correctIndex]) {Check if the element is not in the correct position and needs swapping.
swap(arr[i], arr[correctIndex]);Swap to place the element correctly, moving towards sorted array.
function cyclicSort(arr) {
let i = 0;
const n = arr.length;
while (i < n) {
const correctIndex = arr[i] - 1;
if (arr[i] !== arr[correctIndex]) {
[arr[i], arr[correctIndex]] = [arr[correctIndex], arr[i]];
} else {
i++;
}
}
return arr;
}
// Driver code
const arr = [3, 1, 5, 4, 2];
console.log(cyclicSort(arr));
Line Notes
let i = 0;Initialize pointer to start of array to scan all elements.
const correctIndex = arr[i] - 1;Determine the correct index for the current element based on its value.
if (arr[i] !== arr[correctIndex]) {Check if the element is misplaced and requires swapping.
[arr[i], arr[correctIndex]] = [arr[correctIndex], arr[i]];Swap elements to their correct positions, progressing towards sorted array.
Each element is swapped at most once to its correct position, resulting in linear time complexity.
💡 For n=10^5, this means about 10^5 operations, which is very efficient and suitable for large inputs.
Interview Verdict: Accepted and optimal
This approach is the best for this problem as it uses the problem constraints to achieve linear time and constant space.