Statementâ–¼
Given an array, nums
, of nums[i]
is in the range nums
.
Constraints:
n= nums.length
1≤n≤103 1≤ nums[i]
≤n
Solution
A cyclic sort is optimal for placing elements in their correct positions when dealing with an input array where elements range from
After correctly positioning the elements, scan the array to detect any discrepancies. If an element does not match its expected index, it indicates a missing number.
The steps of the algorithm are given below:
Step 1: Place each element in its correct position
Iterate through the array from the first index (
i = 0
). For each elementnums[i]
, determine its correct position in the array, which should be at indexnums[i] - 1
.Check if the element is already in its correct position:
If
nums[i]
is not equal tonums[nums[i] - 1]
, swapnums[i]
with the element at its correct position. This ensures that the current element is moved to the correct index, and the element that was previously there is now atnums[i]
, ready to be checked and potentially moved.If
nums[i]
is already in the correct position (i.e.,nums[i] == nums[nums[i] - 1]
), simply move to the next index by incrementingi
.
Continue this process until all elements are in their correct positions or until the entire array has been traversed.
Step 2: Identify missing numbers
Iterate through the array again.
For each index
i
, check ifnums[i]
equalsi + 1
.If
nums[i]
is not equal toi + 1
, it means thati + 1
is missing from the array, so appendi + 1
to themissing_numbers
list.
Let’s look at the following illustration to get a better understanding of the solution: