Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Sum of Bitwise AND of each array element with the elements of another array
Next article icon

Sum of Bitwise OR of each array element of an array with all elements of another array

Last Updated : 11 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two arrays arr1[] of size M and arr2[] of size N, the task is to find the sum of bitwise OR of each element of arr1[] with every element of the array arr2[].

Examples:

Input: arr1[] = {1, 2, 3}, arr2[] = {1, 2, 3}, M = 3, N = 3
Output: 7 8 9
Explanation: 
For arr[0]: Sum = arr1[0]|arr2[0] + arr1[0]|arr2[1] + arr1[0]|arr2[2], Sum = 1|1 + 1|2 + 1|3 = 7
For arr[1], Sum = arr1[1]|arr2[0] + arr1[1]|arr2[1] + arr1[1]|arr2[2], Sum= 2|1 + 2|2 + 2|3 = 8
For arr[2], Sum = arr1[2]|arr2[0] + arr1[2]|arr2[1] + arr1[2]|arr2[2], Sum = 3|1 + 3|2 + 3|3 = 9

Input: arr1[] = {2, 4, 8, 16}, arr2[] = {2, 4, 8, 16}, M = 4, N = 4
Output: 36 42 54 78

 

Naive Approach: The simplest0 approach to solve this problem to traverse the array arr1[] and for each array element in the array arr[], calculate Bitwise OR of each element in the array arr2[]. 

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

Efficient Approach: To optimize the above approach, the idea is to use Bit Manipulation to solve the above problem.

  • According to the Bitwise OR property, while performing the operation, the ith bit will be set bit only when either of both numbers has a set bit at the ith position, where 0 ≤ i <32.
  • Therefore, for a number in arr1[], if the ith bit is not a set bit, then the ith place will contribute a sum of K * 2i , where K is the total number in arr2[] having set bit at the ith position.
  • Otherwise, if the number has a set bit at the ith place, then it will contribute a sum of N * 2i.

Follow the steps below to solve the problem:

  1. Initialize an integer array, say frequency[], to store the count of numbers in arr2[] having set-bit at ith position ( 0 ≤ i < 32).
  2. Traverse the array arr2[] and represent each array element in its binary form and increment the count in the frequency[] array by one at the positions having set bit in the binary representations.
  3. Traverse the array arr1[].
    1. Initialize an integer variable, say bitwise_OR_sum with 0.
    2. Traverse in the range [0, 31] using variable j.
    3. If the jth bit is set in the binary representation of arr2[i], then increment bitwise_OR_sum by N * 2j. Otherwise, increment by frequency[j] * 2j
    4. Print the sum obtained bitwise_OR_sum.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to compute sum of Bitwise OR
// of each element in arr1[] with all
// elements of the array arr2[]
void Bitwise_OR_sum_i(int arr1[], int arr2[],
                      int M, int N)
{
 
    // Declaring an array of
    // size 32 to store the
    // count of each bit
    int frequency[32] = { 0 };
 
    // Traverse the array arr1[]
    for (int i = 0; i < N; i++) {
 
        // Current bit position
        int bit_position = 0;
        int num = arr1[i];
 
        // While num exceeds 0
        while (num) {
 
            // Checks if i-th bit
            // is set or not
            if (num & 1) {
 
                // Increment the count at
                // bit_position by one
                frequency[bit_position] += 1;
            }
 
            // Increment bit_position
            bit_position += 1;
 
            // Right shift the num by one
            num >>= 1;
        }
    }
 
    // Traverse in the arr2[]
    for (int i = 0; i < M; i++) {
 
        int num = arr2[i];
 
        // Store the ith bit value
        int value_at_that_bit = 1;
 
        // Total required sum
        int bitwise_OR_sum = 0;
 
        // Traverse in the range [0, 31]
        for (int bit_position = 0;
             bit_position < 32;
             bit_position++) {
 
            // Check if current bit is set
            if (num & 1) {
 
                // Increment the Bitwise
                // sum by N*(2^i)
                bitwise_OR_sum
                    += N * value_at_that_bit;
            }
            else {
                bitwise_OR_sum
                    += frequency[bit_position]
                       * value_at_that_bit;
            }
 
            // Right shift num by one
            num >>= 1;
 
            // Left shift valee_at_that_bit by one
            value_at_that_bit <<= 1;
        }
 
        // Print the sum obtained for ith
        // number in arr1[]
        cout << bitwise_OR_sum << ' ';
    }
 
    return;
}
 
// Driver Code
int main()
{
 
    // Given arr1[]
    int arr1[] = { 1, 2, 3 };
 
    // Given arr2[]
    int arr2[] = { 1, 2, 3 };
 
    // Size of arr1[]
    int N = sizeof(arr1) / sizeof(arr1[0]);
 
    // Size of arr2[]
    int M = sizeof(arr2) / sizeof(arr2[0]);
 
    // Function Call
    Bitwise_OR_sum_i(arr1, arr2, M, N);
 
    return 0;
}
 
 

Java




// Java program for the above approach
import java.util.*;
  
class GFG{
      
// Function to compute sum of Bitwise OR
// of each element in arr1[] with all
// elements of the array arr2[]
static void Bitwise_OR_sum_i(int arr1[], int arr2[],
                             int M, int N)
{
     
    // Declaring an array of
    // size 32 to store the
    // count of each bit
    int frequency[] = new int[32];
    Arrays.fill(frequency, 0);
  
    // Traverse the array arr1[]
    for(int i = 0; i < N; i++)
    {
         
        // Current bit position
        int bit_position = 0;
        int num = arr1[i];
  
        // While num exceeds 0
        while (num != 0)
        {
             
            // Checks if i-th bit
            // is set or not
            if ((num & 1) != 0)
            {
                 
                // Increment the count at
                // bit_position by one
                frequency[bit_position] += 1;
            }
  
            // Increment bit_position
            bit_position += 1;
  
            // Right shift the num by one
            num >>= 1;
        }
    }
  
    // Traverse in the arr2[]
    for(int i = 0; i < M; i++)
    {
         
        int num = arr2[i];
  
        // Store the ith bit value
        int value_at_that_bit = 1;
  
        // Total required sum
        int bitwise_OR_sum = 0;
  
        // Traverse in the range [0, 31]
        for(int bit_position = 0;
                bit_position < 32;
                bit_position++)
        {
  
            // Check if current bit is set
            if ((num & 1) != 0)
            {
                 
                // Increment the Bitwise
                // sum by N*(2^i)
                bitwise_OR_sum += N * value_at_that_bit;
            }
            else
            {
                bitwise_OR_sum += frequency[bit_position] *
                                  value_at_that_bit;
            }
  
            // Right shift num by one
            num >>= 1;
  
            // Left shift valee_at_that_bit by one
            value_at_that_bit <<= 1;
        }
  
        // Print the sum obtained for ith
        // number in arr1[]
        System.out.print(bitwise_OR_sum + " ");
    }
    return;
}
  
// Driver code
public static void main(String[] args)
{
     
    // Given arr1[]
    int arr1[] = { 1, 2, 3 };
  
    // Given arr2[]
    int arr2[] = { 1, 2, 3 };
  
    // Size of arr1[]
    int N = arr1.length;
  
    // Size of arr2[]
    int M = arr2.length;
  
    // Function Call
    Bitwise_OR_sum_i(arr1, arr2, M, N);
}
}
 
// This code is contributed by susmitakundugoaldanga
 
 

Python3




# Python3 program for the above approach
  
# Function to compute sum of Bitwise OR
# of each element in arr1[] with all
# elements of the array arr2[]
def Bitwise_OR_sum_i(arr1, arr2, M, N):
  
    # Declaring an array of
    # size 32 to store the
    # count of each bit
    frequency = [0] * 32
  
    # Traverse the array arr1[]
    for i in range(N):
  
        # Current bit position
        bit_position = 0
        num = arr1[i]
  
        # While num exceeds 0
        while (num):
  
            # Checks if i-th bit
            # is set or not
            if (num & 1 != 0):
  
                # Increment the count at
                # bit_position by one
                frequency[bit_position] += 1
             
            # Increment bit_position
            bit_position += 1
  
            # Right shift the num by one
            num >>= 1
             
    # Traverse in the arr2[]
    for i in range(M):
        num = arr2[i]
  
        # Store the ith bit value
        value_at_that_bit = 1
  
        # Total required sum
        bitwise_OR_sum = 0
  
        # Traverse in the range [0, 31]
        for bit_position in range(32):
  
            # Check if current bit is set
            if (num & 1 != 0):
  
                # Increment the Bitwise
                # sum by N*(2^i)
                bitwise_OR_sum += N * value_at_that_bit
             
            else:
                bitwise_OR_sum += (frequency[bit_position] *
                                   value_at_that_bit)
             
            # Right shift num by one
            num >>= 1
  
            # Left shift valee_at_that_bit by one
            value_at_that_bit <<= 1
         
        # Print the sum obtained for ith
        # number in arr1[]
        print(bitwise_OR_sum, end = " ")
     
    return
 
# Driver Code
 
# Given arr1[]
arr1 = [ 1, 2, 3 ]
  
# Given arr2[]
arr2 = [ 1, 2, 3 ]
  
# Size of arr1[]
N = len(arr1)
  
# Size of arr2[]
M = len(arr2)
  
# Function Call
Bitwise_OR_sum_i(arr1, arr2, M, N)
 
# This code is contributed by code_hunt
 
 

C#




// C# program for the above approach
using System;
class GFG
{
      
// Function to compute sum of Bitwise OR
// of each element in arr1[] with all
// elements of the array arr2[]
static void Bitwise_OR_sum_i(int[] arr1, int[] arr2,
                             int M, int N)
{
      
    // Declaring an array of
    // size 32 to store the
    // count of each bit
    int[] frequency = new int[32];
    for(int i = 0; i < 32; i++)
    {
        frequency[i] = 0;
    }
 
    // Traverse the array arr1[]
    for(int i = 0; i < N; i++)
    {
          
        // Current bit position
        int bit_position = 0;
        int num = arr1[i];
   
        // While num exceeds 0
        while (num != 0)
        {
              
            // Checks if i-th bit
            // is set or not
            if ((num & 1) != 0)
            {
                  
                // Increment the count at
                // bit_position by one
                frequency[bit_position] += 1;
            }
   
            // Increment bit_position
            bit_position += 1;
   
            // Right shift the num by one
            num >>= 1;
        }
    }
   
    // Traverse in the arr2[]
    for(int i = 0; i < M; i++)
    {        
        int num = arr2[i];
   
        // Store the ith bit value
        int value_at_that_bit = 1;
   
        // Total required sum
        int bitwise_OR_sum = 0;
   
        // Traverse in the range [0, 31]
        for(int bit_position = 0;
                bit_position < 32;
                bit_position++)
        {
   
            // Check if current bit is set
            if ((num & 1) != 0)
            {
                  
                // Increment the Bitwise
                // sum by N*(2^i)
                bitwise_OR_sum += N * value_at_that_bit;
            }
            else
            {
                bitwise_OR_sum += frequency[bit_position] *
                                  value_at_that_bit;
            }
   
            // Right shift num by one
            num >>= 1;
   
            // Left shift valee_at_that_bit by one
            value_at_that_bit <<= 1;
        }
   
        // Print the sum obtained for ith
        // number in arr1[]
        Console.Write(bitwise_OR_sum + " ");
    }
    return;
}
  
// Driver Code
public static void Main()
{
   
    // Given arr1[]
    int[] arr1 = { 1, 2, 3 };
   
    // Given arr2[]
    int[] arr2 = { 1, 2, 3 };
   
    // Size of arr1[]
    int N = arr1.Length;
   
    // Size of arr2[]
    int M = arr2.Length;
   
    // Function Call
    Bitwise_OR_sum_i(arr1, arr2, M, N);
}
}
 
// This code is contributed by sanjoy_62
 
 

Javascript




<script>
// Javascript program for the above approach
 
// Function to compute sum of Bitwise OR
// of each element in arr1[] with all
// elements of the array arr2[]
function Bitwise_OR_sum_i(arr1, arr2, M, N) {
 
    // Declaring an array of
    // size 32 to store the
    // count of each bit
    let frequency = new Array(32).fill(0);
 
    // Traverse the array arr1[]
    for (let i = 0; i < N; i++) {
 
        // Current bit position
        let bit_position = 0;
        let num = arr1[i];
 
        // While num exceeds 0
        while (num) {
 
            // Checks if i-th bit
            // is set or not
            if (num & 1) {
 
                // Increment the count at
                // bit_position by one
                frequency[bit_position] += 1;
            }
 
            // Increment bit_position
            bit_position += 1;
 
            // Right shift the num by one
            num >>= 1;
        }
    }
 
    // Traverse in the arr2[]
    for (let i = 0; i < M; i++) {
 
        let num = arr2[i];
 
        // Store the ith bit value
        let value_at_that_bit = 1;
 
        // Total required sum
        let bitwise_OR_sum = 0;
 
        // Traverse in the range [0, 31]
        for (let bit_position = 0; bit_position < 32; bit_position++) {
 
            // Check if current bit is set
            if (num & 1) {
 
                // Increment the Bitwise
                // sum by N*(2^i)
                bitwise_OR_sum += N * value_at_that_bit;
            }
            else {
                bitwise_OR_sum += frequency[bit_position] * value_at_that_bit;
            }
 
            // Right shift num by one
            num >>= 1;
 
            // Left shift valee_at_that_bit by one
            value_at_that_bit <<= 1;
        }
 
        // Print the sum obtained for ith
        // number in arr1[]
        document.write(bitwise_OR_sum + ' ');
    }
 
    return;
}
 
// Driver Code
 
 
// Given arr1[]
let arr1 = [1, 2, 3];
 
// Given arr2[]
let arr2 = [1, 2, 3];
 
// Size of arr1[]
let N = arr1.length;
 
// Size of arr2[]
let M = arr2.length;
 
// Function Call
Bitwise_OR_sum_i(arr1, arr2, M, N);
 
 
// This code is contributed by _saurabh_jaiswal
</script>
 
 
Output: 
7 8 9

 

Time Complexity: O(N*32)
Auxiliary Space: O(1) because size of frequency array is constant



Next Article
Sum of Bitwise AND of each array element with the elements of another array

N

nk14646
Improve
Article Tags :
  • Arrays
  • Bit Magic
  • DSA
  • prefix
  • setBitCount
Practice Tags :
  • Arrays
  • Bit Magic

Similar Reads

  • Sum of Bitwise XOR of elements of an array with all elements of another array
    Given an array arr[] of size N and an array Q[], the task is to calculate the sum of Bitwise XOR of all elements of the array arr[] with each element of the array q[]. Examples: Input: arr[ ] = {5, 2, 3}, Q[ ] = {3, 8, 7}Output: 7 34 11Explanation:For Q[0] ( = 3): Sum = 5 ^ 3 + 2 ^ 3 + 3 ^ 3 = 7.For
    9 min read
  • Sum of Bitwise AND of each array element with the elements of another array
    Given two arrays arr1[] of size M and arr2[] of size N, the task is to find the sum of bitwise AND of each element of arr1[] with the elements of the array arr2[]. Examples: Input: arr1[] = {1, 2, 3}, arr2[] = {1, 2, 3}, M = 3, N = 3Output: 2 4 6Explanation:For elements at index 0 in arr1[], Sum = a
    11 min read
  • Sum of Bitwise XOR of each array element with all other array elements
    Given an array arr[] of length N, the task for every array element is to print the sum of its Bitwise XOR with all other array elements. Examples: Input: arr[] = {1, 2, 3}Output: 5 4 3Explanation:For arr[0]: arr[0] ^ arr[0] + arr[0] ^ arr[1] + arr[0] ^ arr[2] = 1^1 + 1^2 + 1^3 = 0 + 3 + 2 = 5For arr
    9 min read
  • Check if each element of an Array is the Sum of any two elements of another Array
    Given two arrays A[] and B[] consisting of N integers, the task is to check if each element of array B[] can be formed by adding any two elements of array A[]. If it is possible, then print “Yes”. Otherwise, print “No”. Examples: Input: A[] = {3, 5, 1, 4, 2}, B[] = {3, 4, 5, 6, 7} Output: Yes Explan
    6 min read
  • Sum of Bitwise OR of every array element paired with all other array elements
    Given an array arr[] consisting of non-negative integers, the task for each array element arr[i] is to print the sum of Bitwise OR of all pairs (arr[i], arr[j]) ( 0 ≤ j ≤ N ). Examples: Input: arr[] = {1, 2, 3, 4}Output: 12 14 16 22Explanation:For i = 0 the required sum will be (1 | 1) + (1 | 2) + (
    11 min read
  • Rearrange an array to maximize sum of Bitwise AND of same-indexed elements with another array
    Given two arrays A[] and B[] of sizes N, the task is to find the maximum sum of Bitwise AND of same-indexed elements in the arrays A[] and B[] that can be obtained by rearranging the array B[] in any order. Examples: Input: A[] = {1, 2, 3, 4}, B[] = {3, 4, 1, 2}Output: 10Explanation: One possible wa
    15 min read
  • Find last element in Array formed from bitwise AND of array elements
    Given an array A[] of size N, the task is to find the last remaining element in a new array B containing all pairwise bitwise AND of elements from A i.e., B consists of N?(N ? 1) / 2 elements, each of the form Ai & Aj for some 1 ? i < j ? N. And we can perform the following operation any numb
    6 min read
  • Check if an array element is concatenation of two elements from another array
    Given two arrays arr[] and brr[] consisting of N and M positive integers respectively, the task is to find all the elements from the array brr[] which are equal to the concatenation of any two elements from the array arr[]. If no such element exists, then print "-1". Examples: Input: arr[] = {2, 34,
    8 min read
  • Generate an array having sum of Bitwise OR of same-indexed elements with given array equal to K
    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: Inpu
    7 min read
  • Check if original Array Sum is Odd or Even using Bitwise AND of Array
    Given an integer N denoting the size of an array and the bitwise AND (K) of all elements of the array. The task is to determine whether the total sum of the elements is odd or even or cannot be determined. Examples: Input: N = 1, K = 11Output: OddExplanation: As there is only one element in the arra
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences