Algorithm Bit Algorithms: Coding PYTHON

Python programming-Find the Number Occurring Odd Number of Times

Python programming Find the Number Occurring Odd Number of Times - Bit Algorithm - Given array of positive integers. All numbers occur even number of times

Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space.

Example:
I/P = [1, 2, 3, 2, 3, 1, 3] O/P = 3

Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

A Simple Solution is to run two nested loops. The outer loop picks all elements one by one and inner loop counts number of occurrences of the element picked by outer loop. Time complexity of this solution is O(n2).

A Better Solution is to use Hashing. Use array elements as key and their counts as value. Create an empty hash table. One by one traverse the given array elements and store counts. Time complexity of this solution is O(n). But it requires extra space for hashing.

The Best Solution is to do bitwise XOR of all the elements. XOR of all elements gives us odd occurring element. Please note that XOR of two elements is 0 if both elements are same and XOR of a number x with 0 is x.

Below are implementations of this best approach.

Program:

Python Programming
# Python program to find the element occurring odd number of times
 
def getOddOccurrence(arr):
 
    # Initialize result
    res = 0
     
    # Traverse the array
    for element in arr:
        # XOR with the result
        res = res ^ element
 
    return res
 
# Test array
arr = [ 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2]
 
print "%d" % getOddOccurrence(arr)

Output:

5


Time Complexity:
O(n)

See also  Optimal Substructure Property

About the author

Venkatesan Prabu

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Add Comment

Click here to post a comment