Find the number occurring odd number of times in an array

In this post, we will see how to find number occurring odd number of times in the array.

Problem:

You are given a array of integer. All numbers occur even number of times except one. You need to find the number which occurs odd number of time. You need to solve it with o(n) time complexity and o(1) space complexity.
For example:

1

2

3

4

intarray[]=newint[]{20,40,50,40,50,20,30,30,50,20,40,40,20};

Number which occurs odd number of times is:50

Solution:

Solution 1: Use two for loops and compare elements:

This is brute force solution for this problem but it takes o(n*n) time complexity.

Solution 2 : Use Hashing

You can use key as number and count as value and whenever key is repeated , you can increment counter by 1.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

intgetOddTimesElementHashing(intar[])

{

inti;

HashMap<Integer,Integer>elements=newHashMap<Integer,Integer>();

for(i=0;i<ar.length;i++)

{

intelement=ar[i];

if(elements.get(element)==null)

{

elements.put(element,1);

}

else

elements.put(element,elements.get(element)+1);

}

for(Entry<Integer,Integer>entry:elements.entrySet()){

if(entry.getValue()%2==1)

{

returnentry.getKey();

}

}

return-1;

}

but above solution takes o(n) of space complexity.

Solution 3: Use XOR operation:

You can do bitwise XOR operation for all elements and it will give you element which occurs odd number of times in the end.

1

2

3

4

5

6

7

8

9

10

11

12

intgetOddTimesElement(intar[])

{

inti;

intresult=0;

for(i=0;i<ar.length;i++)

{

result=result^ar[i];

}

returnresult;

}

Above algorithms solves the problem with O(n) time complexity and o(1) space complexity and this is best solution for above program.

Java program to find the number occurring odd number of times in an array:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

packageorg.arpit.java2blog;

//Java program to find the element occurring odd number of times

publicclassNumberOddTimesMain

{

intgetOddTimesElement(intar[])

{

inti;

intresult=0;

for(i=0;i<ar.length;i++)

{

// XOR operation

result=result^ar[i];

}

returnresult;

}

publicstaticvoidmain(String[]args)

{

NumberOddTimesMain occur=newNumberOddTimesMain();

intarray[]=newint[]{20,40,50,40,50,20,30,30,50,20,40,40,20};

System.out.println("Number which occurs odd number of times is : "+occur.getOddTimesElement(array));