![]() |
VOOZH | about |
Given an array A[] of length N along with an integer X. Then the task is to output the subsequence such that the cumulative AND of all elements that are present in the subsequence is equal to X. If such a subsequence is present, then print it else print -1.
Examples:
Input: N = 3, A[] = {67, 44, 23}, X = 7
Output: -1
Explanation: It can be verified that no such subsequence exists such that the bitwise AND of that subsequence is equal to 7. Therefore, output is -1.Input: N = 5, A[] = {2, 8, 5, 4, 3}, X = 1
Output: {5, 3}
Explanation: The bitwise AND of 5 and 3 is 1.
Approach: To solve the problem follow the below idea:
The idea for the solving the problem is: Bitwise AND equal to X can be made only and only by those elements in which set bits are same as which are present in X. So, the simple intuition comes that, iterate over the given array A[] and collect all the elements of A[] into a list such that Bitwise AND of element with X is equal to X. After that find cumulative Bitwise AND of all elements present in list, If it is equal to X then output elements present in list else -1.
Steps were taken to solve the problem:
Below is the code to implement the approach:
[5, 3]
Time Complexity: O(N)
Auxiliary Space: O(N), an ArrayList is created to store relevant elements, The maximum size of ArrayList can be equal to A[].