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 XOR of each array element with all other array elements
Next article icon

Sum of Bitwise XOR of elements of an array with all elements of another array

Last Updated : 28 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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 11
Explanation:
For Q[0] ( = 3): Sum =  5 ^ 3 + 2 ^ 3 + 3 ^ 3 = 7.
For Q[1] ( = 8): Sum = 5 ^ 8 + 2 ^ 8 + 3 ^ 8 = 34.
For Q[2] ( = 7): Sum = 5 ^ 7 + 2 ^ 7 + 3 ^ 7 = 11.

Input: arr[ ] = {2, 3, 4}, Q[ ] = {1, 2}
Output: 10 7

Naive Approach: The simplest approach to solve the problem is to traverse the array Q[] and for each array element, calculate the sum of its Bitwise XOR with all elements of the array arr[]. 

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

Efficient Approach: Follow the steps below to optimize the above approach:

  • Initialize an array count[], of size 32. to store the count of set bits at each position of the elements of the array arr[].
  • Traverse the array arr[].
  • Update the array count[] accordingly. In a 32-bit binary representation, if the ith bit is set, increase the count of set bits at that position.
  • Traverse the array Q[] and for each array element, perform the following operations:
    • Initialize variables, say sum = 0, to store the required sum of Bitwise XOR .
    • Iterate over each bit positions of the current element.
    • If current bit is set, add count of elements with ith bit not set * 2i to sum.
    • Otherwise, add count[i] *  2i.
    • Finally, print the value of 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 calculate sum of Bitwise // XOR of elements of arr[] with k int xorSumOfArray(int arr[], int n, int k, int count[]) {      // Initialize sum to be zero     int sum = 0;     int p = 1;      // Iterate over each set bit     for (int i = 0; i < 31; i++) {          // Stores contribution of         // i-th bet to the sum         int val = 0;          // If the i-th bit is set         if ((k & (1 << i)) != 0) {              // Stores count of elements             // whose i-th bit is not set             int not_set = n - count[i];              // Update value             val = ((not_set)*p);         }         else {              // Update value             val = (count[i] * p);         }          // Add value to sum         sum += val;          // Move to the next         // power of two         p = (p * 2);     }      return sum; }  void sumOfXors(int arr[], int n, int queries[], int q) {      // Stores the count of elements     // whose i-th bit is set     int count[32];      // Initialize count to 0     // for all positions     memset(count, 0, sizeof(count));      // Traverse the array     for (int i = 0; i < n; i++) {          // Iterate over each bit         for (int j = 0; j < 31; j++) {              // If the i-th bit is set             if (arr[i] & (1 << j))                  // Increase count                 count[j]++;         }     }      for (int i = 0; i < q; i++) {         int k = queries[i];         cout << xorSumOfArray(arr, n, k, count) << " ";     } }  // Driver Code int main() {     int arr[] = { 5, 2, 3 };     int queries[] = { 3, 8, 7 };      int n = sizeof(arr) / sizeof(int);     int q = sizeof(queries) / sizeof(int);      sumOfXors(arr, n, queries, q);      return 0; } 
Java
// Java Program for the above approach import java.util.Arrays;  class GFG{  // Function to calculate sum of Bitwise // XOR of elements of arr[] with k static int xorSumOfArray(int arr[], int n,                           int k, int count[]) {          // Initialize sum to be zero     int sum = 0;     int p = 1;      // Iterate over each set bit     for(int i = 0; i < 31; i++)      {                  // Stores contribution of         // i-th bet to the sum         int val = 0;          // If the i-th bit is set         if ((k & (1 << i)) != 0)          {                          // Stores count of elements             // whose i-th bit is not set             int not_set = n - count[i];              // Update value             val = ((not_set)*p);         }         else         {                          // Update value             val = (count[i] * p);         }          // Add value to sum         sum += val;          // Move to the next         // power of two         p = (p * 2);     }     return sum; }  static void sumOfXors(int arr[], int n,                        int queries[], int q) {          // Stores the count of elements     // whose i-th bit is set     int []count = new int[32];      // Initialize count to 0     // for all positions     Arrays.fill(count,0);      // Traverse the array     for(int i = 0; i < n; i++)      {                  // Iterate over each bit         for(int j = 0; j < 31; j++)          {                          // If the i-th bit is set             if  ((arr[i] & (1 << j)) != 0)                  // Increase count                 count[j]++;         }     }      for(int i = 0; i < q; i++)     {         int k = queries[i];         System.out.print(             xorSumOfArray(arr, n, k, count) + " ");     } }  // Driver Code public static void main(String args[]) {     int arr[] = { 5, 2, 3 };     int queries[] = { 3, 8, 7 };     int n = arr.length;     int q = queries.length;      sumOfXors(arr, n, queries, q); } }  // This code is contributed by SoumikMondal 
Python3
# Python3 Program for the above approach  # Function to calculate sum of Bitwise # XOR of elements of arr[] with k def xorSumOfArray(arr, n, k, count):          # Initialize sum to be zero     sum = 0     p = 1      # Iterate over each set bit     for i in range(31):                  # Stores contribution of         # i-th bet to the sum         val = 0          # If the i-th bit is set         if ((k & (1 << i)) != 0):                          # Stores count of elements             # whose i-th bit is not set             not_set = n - count[i]              # Update value             val = ((not_set)*p)          else:                          # Update value             val = (count[i] * p)          # Add value to sum         sum += val          # Move to the next         # power of two         p = (p * 2)      return sum  def sumOfXors(arr, n, queries, q):          # Stores the count of elements     # whose i-th bit is set     count = [0 for i in range(32)]      # Traverse the array     for i in range(n):                  # Iterate over each bit         for j in range(31):                          # If the i-th bit is set             if (arr[i] & (1 << j)):                                  # Increase count                 count[j] += 1      for i in range(q):         k = queries[i]                  print(xorSumOfArray(arr, n, k, count), end = " ")  # Driver Code if __name__ == '__main__':          arr = [ 5, 2, 3 ]     queries = [ 3, 8, 7 ]     n = len(arr)     q = len(queries)          sumOfXors(arr, n, queries, q)  # This code is contributed by SURENDRA_GANGWAR 
C#
// C# Program for the above approach using System;  public class GFG{      // Function to calculate sum of Bitwise // XOR of elements of arr[] with k static int xorSumOfArray(int []arr, int n, int k, int []count) {      // Initialize sum to be zero     int sum = 0;     int p = 1;      // Iterate over each set bit     for (int i = 0; i < 31; i++) {          // Stores contribution of         // i-th bet to the sum         int val = 0;          // If the i-th bit is set         if ((k & (1 << i)) != 0) {              // Stores count of elements             // whose i-th bit is not set             int not_set = n - count[i];              // Update value             val = ((not_set)*p);         }         else {              // Update value             val = (count[i] * p);         }          // Add value to sum         sum += val;          // Move to the next         // power of two         p = (p * 2);     }      return sum; }  static void sumOfXors(int []arr, int n, int []queries, int q) {      // Stores the count of elements     // whose i-th bit is set     int []count = new int[32];      // Initialize count to 0     // for all positions          for(int i = 0; i < 32; i++)         count[i] = 0;              // Traverse the array     for (int i = 0; i < n; i++) {          // Iterate over each bit         for (int j = 0; j < 31; j++) {              // If the i-th bit is set             if ((arr[i] & (1 << j)) != 0)                  // Increase count                 count[j]++;         }     }      for (int i = 0; i < q; i++) {         int k = queries[i];         Console.Write(xorSumOfArray(arr, n, k, count) + " ");     } }  // Driver Code static public void Main () {     int []arr = { 5, 2, 3 };     int []queries = { 3, 8, 7 };      int n = arr.Length;     int q = queries.Length;      sumOfXors(arr, n, queries, q); } }  // This code is contributed by AnkThon 
JavaScript
<script>  // Javascript program for the above approach  // Function to calculate sum of Bitwise // XOR of elements of arr[] with k function xorSumOfArray(arr, n, k, count) {          // Initialize sum to be zero     var sum = 0;     var p = 1;      // Iterate over each set bit     for(var i = 0; i < 31; i++)      {                  // Stores contribution of         // i-th bet to the sum         var val = 0;          // If the i-th bit is set         if ((k & (1 << i)) != 0)          {                          // Stores count of elements             // whose i-th bit is not set             var not_set = n - count[i];              // Update value             val = ((not_set)*p);         }         else         {                          // Update value             val = (count[i] * p);         }          // Add value to sum         sum += val;          // Move to the next         // power of two         p = (p * 2);     }     return sum; }  function sumOfXors(arr, n, queries, q) {          // Stores the count of elements     // whose i-th bit is set     var count = new Array(32);      // Initialize count to 0     // for all positions     count.fill(0);      // Traverse the array     for(var i = 0; i < n; i++)      {                  // Iterate over each bit         for(var j = 0; j < 31; j++)          {                          // If the i-th bit is set             if (arr[i] & (1 << j))                  // Increase count                 count[j]++;         }     }      for(var i = 0; i < q; i++)     {         var k = queries[i];         document.write(xorSumOfArray(             arr, n, k, count) + " ");     } }  // Driver code var arr = [ 5, 2, 3 ]; var queries = [ 3, 8, 7 ]; var n = arr.length; var q = queries.length;  sumOfXors(arr, n, queries, q);  // This code is contributed by SoumikMondal  </script> 

Output: 
7 34 11

 

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


 


Next Article
Sum of Bitwise XOR of each array element with all other array elements
author
elitecoder
Improve
Article Tags :
  • Bit Magic
  • Mathematical
  • Competitive Programming
  • Data Structures
  • DSA
  • Arrays
  • setBitCount
  • Bitwise-XOR
Practice Tags :
  • Arrays
  • Bit Magic
  • Data Structures
  • Mathematical

Similar Reads

  • Sum of Bitwise OR of each array element of an array with all 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 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 = 3Output: 7 8 9Explanation: For arr[0]: Sum = arr1[0]|arr2[0] + arr1[
    11 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
  • 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
  • Maximum possible XOR of every element in an array with another array
    Two arrays A and B consisting of N elements are given. The task is to compute the maximum possible XOR of every element in array A with array B. Examples: Input : A : 7 3 9 12 B : 1 3 5 2 Output : 6 6 12 15 Explanation : 1 xor 7 = 6, 5 xor 3 = 6, 5 xor 9 = 12, 3 xor 12 = 15. A naive approach to solv
    12 min read
  • XOR of all elements of array with set bits equal to K
    Given an array of integers and a number K. The task is to find the XOR of only those elements of the array whose total set bits are equal to K. Examples: Input : arr[] = {1, 22, 3, 10}, K=1 Output : 1 Elements with set bits equal to 1 is 1. So, XOR is also 1. Input : arr[] = {3, 4, 10, 5, 8}, K=2 Ou
    4 min read
  • Construct an array from XOR of all elements of array except element at same index
    Given an array A[] having n positive elements. The task to create another array B[] such as B[i] is XOR of all elements of array A[] except A[i].Examples : Input : A[] = {2, 1, 5, 9} Output : B[] = {13, 14, 10, 6} Input : A[] = {2, 1, 3, 6} Output : B[] = {4, 7, 5, 0} Recommended PracticeXOR of all
    5 min read
  • Replace every element of the array with BitWise XOR of all other
    Given an array of integers. The task is to replace every element by the bitwise xor of all other elements of the array. Examples: Input: arr[] = { 2, 3, 3, 5, 5 } Output: 0 1 1 7 7 Bitwise Xor of 3, 3, 5, 5 = 0 Bitwise Xor of 2, 3, 5, 5 = 1 Bitwise Xor of 2, 3, 5, 5 = 1 Bitwise Xor of 2, 3, 3, 5 = 7
    5 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