📖 Scenario: Imagine you have a list of numbers where every number appears twice except for two unique numbers that appear only once. You want to find those two unique numbers efficiently.
🎯 Goal: Build a C++ program that finds the two unique numbers in an array where every other number repeats twice, using XOR operations.
📋 What You'll Learn
Create an integer array called arr with the exact values: 2, 3, 7, 9, 2, 3
Create an integer variable called xor_all and initialize it to 0
Use a for loop with variable num to XOR all elements of arr into xor_all
Find the rightmost set bit of xor_all and store it in set_bit
Create two integer variables num1 and num2 initialized to 0
Use a for loop with variable num to separate elements of arr into two groups based on set_bit and XOR them into num1 and num2
Print the two unique numbers num1 and num2 separated by a space
💡 Why This Matters
🌍 Real World
Finding unique items in data streams or logs where duplicates are common, such as detecting unique error codes or unique user IDs.
💼 Career
Bitwise operations and XOR tricks are common in coding interviews and help optimize solutions for problems involving duplicates and unique elements.
Progress0 / 4 steps
1
Create the array with given numbers
Create an integer array called arr with the exact values: 2, 3, 7, 9, 2, 3
DSA C++
Hint
Use C++ array initialization syntax with the exact numbers given.
2
Initialize XOR accumulator variable
Create an integer variable called xor_all and initialize it to 0
DSA C++
Hint
Declare an integer variable named xor_all and set it to zero.
3
XOR all elements to find combined XOR
Use a for loop with variable num to XOR all elements of arr into xor_all
DSA C++
Hint
Use a range-based for loop to XOR each number with xor_all.
4
Find the two unique numbers and print them
Find the rightmost set bit of xor_all and store it in set_bit. Create two integer variables num1 and num2 initialized to 0. Use a for loop with variable num to separate elements of arr into two groups based on set_bit and XOR them into num1 and num2. Finally, print num1 and num2 separated by a space.
DSA C++
Hint
Use bitwise AND with negative xor_all to find the rightmost set bit. Then separate numbers into two groups and XOR each group. Print the two unique numbers.
Practice
(1/5)
1. What is the main idea behind using XOR to find two non-repeating elements in an array where every other element repeats?
easy
A. XOR counts the frequency of each element
B. XOR sorts the array to separate unique elements
C. XOR of all elements gives XOR of the two unique elements
D. XOR swaps the two unique elements in the array
Solution
Step 1: Understand XOR properties
XOR of a number with itself is 0, and XOR with 0 is the number itself.
Step 2: Apply XOR to all elements
XORing all elements cancels out repeating elements, leaving XOR of two unique elements.
Final Answer:
XOR of all elements gives XOR of the two unique elements -> Option C