Find Element Which Appears Only Once and Every Other Element Appears Twice Using Bit Manipulation

Given an array with all integers repeated except 1, the only once occurring element can be found using Bitwise XOR ( ^ ).

Bitwise XOR ( ^ ) takes 2 parameters, If both bits of 2 different bit patterns are different, then the XOR of both bits is 1, otherwise 0.

2 most important properties of XOR is a^0=a, a^a=0

Start XOR the entire array, Since a^a=0, hence all duplicates will cancel out each other, only once occurring integer will remain.

package org.wesome.dsalgo;

public class SingleOccurrenceElement {
    static int findSingleElement(int[] arr) {
        int res = arr[0];
        for (int i = 1; i < arr.length; i++)
            res = res ^ arr[i];
        return res;
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class SingleOccurrenceElementTest {
    @Test
    void findSingleElementTest1() {
        int[] arr = new int[]{1, 1, 2, 2, 3, 4, 4, 5, 5};
        Assertions.assertEquals(3, SingleOccurrenceElement.findSingleElement(arr));
    }

    @Test
    void findSingleElementTest2() {
        int[] arr = new int[]{-1, -1, -2, -2, -3, -4, -4, -5, -5};
        Assertions.assertEquals(-3, SingleOccurrenceElement.findSingleElement(arr));
    }
}
plugins {
    id 'java'
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

 

follow us on