![]() |
VOOZH | about |
Given an unsorted array arr[] of size n, containing elements from the range 1 to n, it is known that one number in this range is missing, and another number occurs twice in the array, find both the duplicate number and the missing number.
Examples:
Input: arr[] = [3, 1, 3]
Output: [3, 2]
Explanation: 3 is occurs twice and 2 is missing.Input: arr[] = [4, 3, 6, 2, 1, 1]
Output: [1, 5]
Explanation: 1 is occurs twice and 5 is missing.
Table of Content
The idea is to use a frequency array to keep track of how many times each number appears in the original array. Since we know the numbers should range from 1 to n with each appearing exactly once, any number appearing twice is our repeating number, and any number with zero frequency is our missing number.
3 2
The main idea is to use the input array itself for tracking: it negates the value at the index corresponding to each element to mark it as visited. If it encounters a value that has already been negated, it identifies that number as the repeating one. In a second pass, it finds the index that remains positive, which corresponds to the missing number.
3 2
The idea is to use mathematical equations based on the sum and sum of squares of numbers from 1 to n. The difference between expected and actual sums will give us one equation, and the difference between expected and actual sum of squares will give us another equation. Solving these equations yields our missing and repeating numbers.
Illustration:
Note: This method can cause arithmetic overflow as we calculate the sum of squares (or product) and sum of all array elements.
3 2
An Alternate way to make two equations:
The idea is to use XOR operations to isolate the missing and repeating numbers. By XORing all array elements with numbers 1 to n, we get the XOR of our missing and repeating numbers. Then, using a set bit in this XOR result, we can divide all numbers into two groups, which helps us separate the missing and repeating numbers.
Refer to Find the two numbers with odd occurrences in an unsorted array to understand how groups will be created.
Step by step approach:
xorVal & ~(xorVal-1).3 2