Problem Statement — Given an array count the no. of distinct pairs of elements such that their AND(&) is an exact power of 2.
array size <= 1e5 and 1 <= a[i] <= 2^12
Example — array -> [10 7 8 2 3] ; answer = 6
# | User | Rating |
---|---|---|
1 | tourist | 4009 |
2 | jiangly | 3831 |
3 | Radewoosh | 3646 |
4 | jqdai0815 | 3620 |
4 | Benq | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | gamegame | 3386 |
10 | ksun48 | 3373 |
# | User | Contrib. |
---|---|---|
1 | cry | 164 |
1 | maomao90 | 164 |
3 | Um_nik | 163 |
4 | atcoder_official | 160 |
5 | -is-this-fft- | 158 |
6 | awoo | 157 |
7 | adamant | 156 |
8 | TheScrasse | 154 |
8 | nor | 154 |
10 | Dominater069 | 153 |
Problem Statement — Given an array count the no. of distinct pairs of elements such that their AND(&) is an exact power of 2.
array size <= 1e5 and 1 <= a[i] <= 2^12
Example — array -> [10 7 8 2 3] ; answer = 6
Name |
---|
if bitwise and of x and y is a power of 2 then abs(x-y) must be a power of 2. so build a set of the given array first. then for each element p in the set, search the number of occurences of element p+pow(2,i) in the set for each i satisfying 0<=i<=12 and p&pow(2,i)=0.
sorry it is totally wrong
First keep the count of each number present in the array.
Simply brute force every pair (x,y) such that 1<=x<=y<=2^12 and check the bitwise AND of each pair.
If it is a power of 2, then do the following:
Case 1: if(x!=y)
then add count(x)*count(y) to the answer
Case 2: if(x==y)
then add (count(x)*(count(x)-1))/2 to the answer
Thanks, this solution is pretty simple
Time complexity??
Its O(2^24) which is nearly 10^7 operations which is fine.
what if the question has (1 <= a[i] <= 2^20) as constraints for each element, then what approach do we use to avoid TLE.
see this. Sos dp.
can you please provide the question link? (i wanted to check if my solution works or not).
The question is from HackerRank certification test.
I think we can use a trie and search for the required no. of pairs. Iterate over all the elements of the array. For a given no. in array there will be 12 possibilities of placing a 1 (not exactly 12, depends upon the position of 1s in the the selected numbers) , and traverse the trie and sum the total no. of such numbers which will make every bits 0 except one bit. I hope it will pass the time constraint!! If you want to study trie then follow this link: https://www.hackerearth.com/practice/data-structures/advanced-data-structures/trie-keyword-tree/tutorial/ Read whole advanced data structures, that will be quite beneficial for you!!