Solution: Find the Corrupt Pair
Let's solve the Find the Corrupt Pair problem using the Cyclic Sort pattern.
We'll cover the following
Statement#
We are given an unsorted array, nums, with elements and each element is in the range inclusive. The array originally contained all the elements from to but due to a data error, one of the numbers is duplicated, which causes another number missing. Find and return the corrupt pair (missing, duplicated).
Constraints:
-
nums[i]
Solution#
The given input array is unsorted, and the numbers in the input array lie in the range to . Therefore, the cyclic sort is optimal to place the elements at their correct index. Once all the elements are in their correct position, we can easily find the pair of missing and duplicate numbers.
The steps of the above-mentioned approach are given below:
-
The first step is to place each number in its correct position during the cyclic sort. Initialize
ito 0 and iterate over the array. While traversing, we will perform the following steps:- The variable
correctis calculated asnums[i] - 1, representing the index where the current number should be placed if the array were sorted. - If the current number,
nums[i], is not equal to the number at the correct position,nums[correct], a swap is performed using theswapfunction to move the current number to its correct position. - If the numbers are already in their correct positions,
iis incremented to move to the next element.
- The variable
-
The second step is to traverse the array and detect the number that is not at its correct index. This will be the duplicated number. When we add to that index, the resulting value will be our missing number.
-
Return the pair containing missing and duplicated numbers.
Let’s look at the following illustration to get a better understanding of the solution:
1 of 10
2 of 10
3 of 10
4 of 10
5 of 10
6 of 10
7 of 10
8 of 10
9 of 10
10 of 10
Time complexity#
The time complexity of the above solution is , because it uses the cyclic sort, where is the size of the array. In the worst case, let’s assume that every element is placed at the wrong index. With every swap operation, there is at least one element that is placed in the right place. The total number of swap operations that need to be performed is .
Space complexity#
The space complexity of the above solution is , because we have used constant space.
Find the Corrupt Pair
First Missing Positive