Given an array where every element Occurs three times, except one element which occurs only once. Find the element that occurs once. The expected time complexity is O(n) and O(1) extra space.

0

 Given an array where every element Occurs three times, except one element which occurs only once. Find the element that occurs once. The expected time complexity is O(n) and O(1) extra space.




Cpp Program Code:



In this code, the findSingleElement function takes an array arr and its length n as input and returns the element that occurs only once.

The algorithm is implemented using two variables ones and twos to keep track of the count of set bits at each position in the numbers we have seen so far. The bitwise AND and OR operations are used to update these variables for each number in the array.

At the end of the loop, the common bit mask is computed using the bitwise complement of the AND operation of ones and twos. Finally, the function returns ones, which should be the element that occurs only once in the array.

Python Program code:

In this code, the find_single_element function takes an array arr as input and returns the element that occurs only once.

The algorithm is implemented using two variables ones and twos to keep track of the count of set bits at each position in the numbers we have seen so far. The bitwise AND and OR operations are used to update these variables for each number in the array.

At the end of the loop, the common bit mask is computed using the bitwise complement of the AND operation of ones and twos. Finally, the function returns ones, which should be the element that occurs only once in the array.

Post a Comment

0Comments
Post a Comment (0)