Solution: Cyclic Sort
Let’s solve the Cyclic Sort problem using the Cyclic Sort pattern.
We'll cover the following
Statement
You are given an integer array, nums
of size
Constraints:
nums.length
Each element in
nums
is unique and within the range.
Solution
The essence of this solution lies in sorting the given array in place using the cyclic sort pattern, which is useful for sorting arrays where numbers fall within a fixed range
Now, let’s look at the solution steps below:
We initialize a pointer,
i = 0
, to iterate through the array.We iterate through
nums
, and for each elementnums[i]
, we determine its correct index ascorrect = nums[i] - 1
.If
nums[i]
is not at its correct index (nums[i] != nums[correct]
), we swapnums[i]
withnums[correct]
, placing the current number in its correct position. However, we do not incrementi
after swapping because the new element at the indexi
may still be out of place. So, the process repeats untilnums[i]
is correctly positioned.Otherwise, if
nums[i]
is already in the correct place, we incrementi
and move to the next element.This process continues until all elements are in their correct indexes, ensuring the array is fully sorted.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.