Bird
0
0
DSA Cprogramming~3 mins

Why Two Non Repeating Elements in Array Using XOR in DSA C?

Choose your learning style9 modes available
The Big Idea

Discover how a simple XOR trick can instantly spot two unique items hidden among many pairs!

The Scenario

Imagine you have a box full of socks where every sock has a matching pair except for two unique socks. You want to find those two unique socks quickly without checking each pair one by one.

The Problem

Manually checking each sock against all others is slow and tiring. You might miss pairs or check the same socks multiple times, making it easy to make mistakes and waste time.

The Solution

Using XOR, a simple math trick, you can quickly find the two unique socks by combining all socks in a way that pairs cancel out, leaving only the unique ones. This method is fast and error-free.

Before vs After
Before
for (int i = 0; i < n; i++) {
  for (int j = i + 1; j < n; j++) {
    if (arr[i] == arr[j]) {
      // mark as paired
    }
  }
}
// find unpaired elements
After
int xor_all = 0;
for (int i = 0; i < n; i++) {
  xor_all ^= arr[i];
}
// Use xor_all to find two unique elements
What It Enables

This technique lets you find two unique elements in a list instantly, even if the list is very large.

Real Life Example

Finding two unique defective products in a large batch where every other product is identical and paired.

Key Takeaways

Manual pair checking is slow and error-prone.

XOR cancels out pairs, revealing unique elements.

Efficient for large data sets with two unique items.