23. Missing and Repeating
The problem can be found at the following link: Question Link
Problem Description
Given an unsorted array arr of positive integers where one number 'A' from the set {1, 2,..., n} is missing, and one number 'B' occurs twice in the array, find the numbers A and B.
Example 1:
Input:
arr[] = [2, 2]Output:
2 1Explanation:
Repeating number is 2, and the smallest positive missing number is 1.Example 2:
Input:
arr[] = [1, 3, 3]Output:
3 2Explanation:
Repeating number is 3, and the smallest positive missing number is 2.Constraints:
2 ≤ n ≤ 10^5
1 ≤ arr[i] ≤ n
My Approach
XOR Logic:
We XOR all the elements of the array and all numbers from 1 to n. The result will be
xor_all, which is the XOR of the repeating and the missing numbers.Find the rightmost set bit in
xor_all. This will help separate the missing and repeating numbers into two different sets based on whether they have the bit set or not.
Separate Sets:
Traverse the array again and XOR the elements that belong to the same set, resulting in two XOR results (
xor1andxor2). These will represent the missing and repeating numbers.
Final Step:
Determine which of
xor1orxor2is the repeating number by checking the input array, and deduce the missing number.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the size of the array. We traverse the array a constant number of times.
Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit my LinkedIn: Any Questions. Thank you for your input; together, we strive to create a space where learning is a collaborative endeavor.
⭐ Star this repository if you find it helpful or intriguing! ⭐
📍Visitor Count
Last updated