Friday, April 18, 2014

Find no. with odd no of occurence in a sequence

The problem statement states that in a given sequence of number only 1 number is occurring odd no of times and rest all the numbers are occurring even no of time.
input e.g.
                  2,3,4,1,1,2,4
                  7,5,2,3,4,4,1,2,7,7,3,4,7,5

Please try this once before proceeding ahead.

We will discuss 2 approaches to solve the problem.

Approach 1 (storing no of count in a data structure) :

We can have a hash map which stores the number of occurrence of each number in the list.
Then we can count the number of occurrence and which one is odd.

Lets take an sample input as
          
2
3
1
1
4
2
3
4
3

if we try to process this input in a hash map then we can find following map




Key
Count
2
2
3
3
1
2
4
2


we can traverse the complete map to find out the count and which one is odd.

Pros:
  1. Its simple to think as well as code
Cons:
  1. It take more space
  2. 2 iterations required; 1st iteration for counting,  2nd iteration on the map to check whose count is odd

You can find the complete source code here.
For this special case when only one item is occurring odd no of time, we can use XOR operation as well.

Approach 2 (XOR operation) :

In this approach we will XOR all the items and the final output will be the number which occurs odd no of times.

e.g.


2
3
1
1
4
2
3
4
3
                                                             
here number = 2^3^1^1^4^2^3^4^3 = 3

This solutions works only when you have a single number occurring odd no of times.

You can find the complete source code here.



No comments:

Post a Comment