Skip to content
Related Articles

Related Articles

Generate an array having sum of Bitwise OR of same-indexed elements with given array equal to K
  • Last Updated : 16 Mar, 2021

Given an array arr[] consisting of N integers and an integer K, the task is to print an array generated such that the sum of Bitwise OR of same indexed elements of the generated array with the given array is equal to K. If it is not possible to generate such an array, then print “-1”.

Examples:

Input: arr[] = {6, 6, 6, 6}, K = 34
Output: 15 7 6 6
Explanation: 
Bitwise XOR of same-indexed elements of the arrays {6, 6, 6, 6} and {15, 7, 6, 6} are:
6|15 = 15
6|7 = 7
6|6 = 6
6|6 = 6
Sum of Bitwise ORs = 15 + 7 + 6 + 6 = 34 (= K)

Input: arr[] = {1, 2, 3, 4}, K = 32
Output: 23 2 3 4

 

Approach: Follow the steps below to solve the problem:



  • First, calculate the sum of the array arr[] and store it in a variable, say sum.
  • Initialize a vector<int>, say B, to store the resultant array.
  • Update the value of K as K = K – sum.
  • If K is less than 0, print -1.
  • Traverse the array arr[] and perform the following operations:
    • Initialize a variable, say curr, to store the elements of the resultant array.
    • Traverse over the bits of the current array element.
    • Check if the current bit is set or not and 2j ≤ K or not. If found to be true, then update curr as curr = curr | (1<<j) and K = K – (1 << j).
    • Now, push the curr into the vector B.
  • Print the vector B if K is 0. Otherwise, print -1.

Below is the implementation of the above approach:

C++14




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the resultant array
void constructArr(int A[], int N, int K)
{
    // Stores the sum of the array
    int sum = 0;
 
    // Calculate sum of the array
    for (int i = 0; i < N; i++) {
        sum += A[i];
    }
 
    // If sum > K
    if (sum > K) {
 
        // Not possible to
        // construct the array
        cout << -1 << "\n";
        return;
    }
 
    // Update K
    K -= sum;
 
    // Stores the resultant array
    vector<int> B;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Stores the current element
        int curr = A[i];
 
        for (int j = 32; j >= 0 and K; j--) {
 
            // If jth bit is not set and
            // value of 2^j is less than K
            if ((curr & (1LL << j)) == 0
                and (1LL << j) <= K) {
 
                // Update curr
                curr |= (1LL << j);
 
                // Update K
                K -= (1LL << j);
            }
        }
 
        // Push curr into B
        B.push_back(curr);
    }
 
    // If K is greater than 0
    if (!K) {
 
        // Print the vector B
        for (auto it : B) {
            cout << it << " ";
        }
        cout << "\n";
    }
 
    // Otherwise
    else {
        cout << "-1"
             << "\n";
    }
}
 
// Driver Code
int main()
{
    // Input
    int arr[] = { 1, 2, 3, 4 };
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Given input
    int K = 32;
 
    // Function call to print
    // the required array
    constructArr(arr, N, K);
}

Python3




# Python 3 program for the above approach
 
# Function to print the resultant array
def constructArr(A, N, K):
   
    # Stores the sum of the array
    sum = 0
 
    # Calculate sum of the array
    for i in range(N):
        sum += A[i]
 
    # If sum > K
    if (sum > K):
       
        # Not possible to
        # construct the array
        print(-1)
        return
 
    # Update K
    K -= sum
 
    # Stores the resultant array
    B = []
 
    # Traverse the array
    for i in range(N):
       
        # Stores the current element
        curr = A[i]
        j = 32
 
        while(j >= 0 and K>0):
           
            # If jth bit is not set and
            # value of 2^j is less than K
            if ((curr & (1 << j)) == 0 and (1 << j) <= K):
               
                # Update curr
                curr |= (1 << j)
 
                # Update K
                K -= (1 << j)
            j -= 1
 
        # Push curr into B
        B.append(curr)
 
    # If K is greater than 0
    if (K == 0):
        # Print the vector B
        for it in B:
            print(it,end=" ")
        print("\n",end = "")
 
    # Otherwise
    else:
        print("-1")
 
# Driver Code
if __name__ == '__main__':
    # Input
    arr = [1, 2, 3, 4]
     
    # Size of the array
    N = len(arr)
     
    # Given input
    K = 32
     
    # Function call to print
    # the required array
    constructArr(arr, N, K)
 
# This code is contributed by ipg2016107.

 
 

Output: 
23 2 3 4

 

 

Time Complexity: O(N)
Auxiliary Space: O(N)

 

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :