![]() |
VOOZH | about |
Given an array of n-elements, we have to find the largest element among them without using any conditional operator like greater than or less than.
Examples:
Input : arr[] = {5, 7, 2, 9}
Output : Largest element = 9
Input : arr[] = {15, 0, 2, 15}
Output : Largest element = 15
First Approach (Use of Hashing) : To find the largest element from the array we may use the concept the of hashing where we should maintain a hash table of all element and then after processing all array element we should find the largest element in hash by simply traversing the hash table from end.
But there are some drawbacks of this approach like in case of very large elements maintaining a hash table is either not possible or not feasible.
Better Approach (Use of Bitwise AND) : Recently we have learn how to find the largest AND value pair from a given array. Also, we know that if we take bitwise AND of any number with INT_MAX (whose all bits are set bits) then the result will be that number itself. Now, using this property we will try to find the largest element from the array without any use conditional operator like greater than or less than.
For finding the largest element we will first insert an extra element i.e. INT_MAX in array, and after that we will try to find the maximum AND value of any pair from the array. This obtained maximum value will contain AND value of INT_MAX and largest element of original array and is our required result.
Below is the implementation of above approach :
Output:
Largest element = 8
Time Complexity: O(32)
Auxiliary Space: O(N)