0
0
DSA Pythonprogramming~3 mins

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

Choose your learning style9 modes available
The Big Idea

Discover how a simple math trick can save you hours of tedious searching!

The Scenario

Imagine you have a big box 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 every single sock against all others.

The Problem

Checking each sock one by one against all others is slow and tiring. You might miss pairs or check the same socks many times. This manual way wastes time and can cause mistakes.

The Solution

Using XOR, a special 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 simple.

Before vs After
Before
for i in range(len(arr)):
    count = 0
    for j in range(len(arr)):
        if arr[i] == arr[j]:
            count += 1
    if count == 1:
        print(arr[i])
After
xor_all = 0
for number in arr:
    xor_all ^= number
# Further steps to separate two unique numbers
What It Enables

This method lets you find two unique items in a large group quickly and without extra memory.

Real Life Example

Finding two unique defective products in a batch where all others are identical pairs, without checking each product twice.

Key Takeaways

Manual pair checking is slow and error-prone.

XOR helps cancel out pairs and isolate unique elements.

Efficient for large data with two unique items.