Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • DSA
  • Practice Bitwise Algorithms
  • MCQs on Bitwise Algorithms
  • Tutorial on Biwise Algorithms
  • Binary Representation
  • Bitwise Operators
  • Bit Swapping
  • Bit Manipulation
  • Count Set bits
  • Setting a Bit
  • Clear a Bit
  • Toggling a Bit
  • Left & Right Shift
  • Gray Code
  • Checking Power of 2
  • Important Tactics
  • Bit Manipulation for CP
  • Fast Exponentiation
Open In App
Next Article:
XOR of Bitwise OR Pairs from Two Arrays
Next article icon

XOR of Bitwise OR Pairs from Two Arrays

Last Updated : 31 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two integer arrays A[] and B[] of size N and M respectively. Another array C is formed of size N*M, containing Bitwise OR of all possible pairs of elements of A with all elements of B i.e. A[i] | B[j] for all valid i and j. Find the Bitwise XOR of array C i.e. C [0] ^ C[1] ^ .......C[N*M].

Examples:

Input: N = 1, M = 3, A[] = {2}, B[] = {5, 0, 3}
Output: 6
Explanation: (2 OR 5) XOR (2 OR 0) XOR (2 OR 3) = 6.

Input: N = 2, M = 2, A[] = {1, 2}, B[] = {4, 10}
Output: 2
Explanation: Array C = [5, 11, 6, 10]. Xor is 2

Bruteforce Approach: The basic way to solve the problem:

The naive approach would be using nested loops to formulate all the possible pairs and find out the array C by evaluating the bitwise OR of every pair. Now calculate the bitwise XOR of the array C, to obtain the results.

Time complexity: O(N*M). where N and M are the lengths of the two arrays.

Efficient approach: To solve the problem follow the below intuition:

We need to check if the ith bit is set or not in the final answer. So for that we will maintain a count array, which will conatins the number of set bits in the array B at ith bit. Now we iterate on array A if the ith bit for a element in array A is a set bit then add M to the value if not add count[i] to the value. finally if the value is odd then the ith bit is set in the final answer.

Steps to solve the problem:

  • Keep a track of count array of length 30. Where the ith index in the array i.e., count[i] denotes the number of set bits at ith position in the array B.
  • Now iterate on each bit i, for all the elements in array A do the following:
    • If ith bit is set add M i.e, length of array B to the variable value.
    • else add count[i] to the variable value.
  • If for a particular bit the the value obtained is odd then the bit is set in the final answer.
  • Return answer after performing the above step on every bit.

Implementation of the above approach:

C++
// C++ code for the above approach: #include <iostream> using namespace std;  int findORAndXOR(int A[], int B[], int N, int M) {      // Count array to keep track of set bits     int count[30] = { 0 };      // To store final answer     int ans = 0;      for (int i = 0; i < 30; i++) {         for (int j = 0; j < M; j++) {             if (B[j] & (1 << i))                 count[i]++;         }     }      for (int i = 0; i < 30; i++) {         int value = 0;         for (int j = 0; j < N; j++) {             if (A[j] & (1 << i))                 value += M;             else                 value += count[i];         }          // if value is odd. The current bit is         // set in the final answer.         if (value & 1)             ans |= (1 << i);     }      return ans; }  // Drivers code int main() {     int N = 2, M = 2;     int A[N] = { 1, 2 };     int B[M] = { 4, 10 };      // Function Call     cout << findORAndXOR(A, B, N, M);     return 0; } 
Java
// Java code for the above approach  import java.util.Arrays;  class GFG {     public static int findORAndXOR(int[] A, int[] B, int N,                                    int M)     {         // Count array to keep track of set bits         int[] count = new int[30];          // To store final answer         int ans = 0;          for (int i = 0; i < 30; i++) {             for (int j = 0; j < M; j++) {                 if ((B[j] & (1 << i)) != 0)                     count[i]++;             }         }          for (int i = 0; i < 30; i++) {             int value = 0;             for (int j = 0; j < N; j++) {                 if ((A[j] & (1 << i)) != 0)                     value += M;                 else                     value += count[i];             }              // if value is odd. The current bit is             // set in the final answer.             if ((value & 1) != 0)                 ans |= (1 << i);         }          return ans;     }      // Driver code     public static void main(String[] args)     {         int N = 2, M = 2;         int[] A = { 1, 2 };         int[] B = { 4, 10 };          // Function Call         System.out.println(findORAndXOR(A, B, N, M));     } }  // This code is contributed by Abhinav Mahajan (abhinav_m22) 
Python3
def find_OR_and_XOR(A, B):     # Count array to keep track of set bits     count = [0] * 30     ans = 0      # Counting set bits in array B     for i in range(30):         for j in range(len(B)):             if B[j] & (1 << i):                 count[i] += 1      # Calculating the final answer bit by bit     for i in range(30):         value = 0         # Computing the value for each bit position         for j in range(len(A)):             if A[j] & (1 << i):                 value += len(B)             else:                 value += count[i]          # Checking for odd value to set the bit in the final answer         if value & 1:             ans |= (1 << i)      return ans  # Driver code N = 2 M = 2 A = [1, 2] B = [4, 10]  # Function Call and printing the result print(find_OR_and_XOR(A, B)) 
C#
using System;  class GFG {     public static int FindORAndXOR(int[] A, int[] B, int N, int M)     {         // Count array to keep track of set bits         int[] count = new int[30];          // To store final answer         int ans = 0;          for (int i = 0; i < 30; i++)         {             for (int j = 0; j < M; j++)             {                 if ((B[j] & (1 << i)) != 0)                     count[i]++;             }         }          for (int i = 0; i < 30; i++)         {             int value = 0;             for (int j = 0; j < N; j++)             {                 if ((A[j] & (1 << i)) != 0)                     value += M;                 else                     value += count[i];             }              // if value is odd. The current bit is             // set in the final answer.             if ((value & 1) != 0)                 ans |= (1 << i);         }          return ans;     }      // Driver code     public static void Main(string[] args)     {         int N = 2, M = 2;         int[] A = { 1, 2 };         int[] B = { 4, 10 };          // Function Call         Console.WriteLine(FindORAndXOR(A, B, N, M));     } } 
JavaScript
// Javascript code for the above approach:  function findORAndXOR(A, B, N, M) {      // Count array to keep track of set bits     const count = Array(30).fill(0);      // To store final answer     let ans = 0;      for (let i = 0; i < 30; i++) {         for (let j = 0; j < M; j++) {             if (B[j] & (1 << i))                 count[i]++;         }     }      for (let i = 0; i < 30; i++) {         let value = 0;         for (let j = 0; j < N; j++) {             if (A[j] & (1 << i))                 value += M;             else                 value += count[i];         }          // if value is odd. The current bit is         // set in the final answer.         if (value & 1)             ans |= (1 << i);     }      return ans; }  // Drivers code const N = 2,     M = 2;  const A = [1, 2]; const B = [4, 10];  // Function Call console.log(findORAndXOR(A, B, N, M));  // This code is contributed by ragul21 

Output
2

Time Complexity: O(30 * max(N, M)). Where N and M are the lengths of array A and B respectively.
Auxillary Space: O(30). Space used for count array.


Next Article
XOR of Bitwise OR Pairs from Two Arrays

P

pavang2001
Improve
Article Tags :
  • Bit Magic
  • DSA
  • Basic Coding Problems
  • Bitwise-XOR
  • Bitwise-OR
Practice Tags :
  • Bit Magic

Similar Reads

    Bitwise XOR of Bitwise AND of all pairs from two given arrays
    Given two arrays arr1[] and arr2[] consisting of N and M integers respectively, the task is to print the Bitwise XOR of Bitwise AND of all pairs possible by selecting an element from arr1[] and arr2[]. Examples: Input: arr1[] = {1, 2, 3}, arr2[] = {6, 5}Output: 0Explanation: Bitwise AND of the pair
    10 min read
    Find XOR sum of Bitwise AND of all pairs from given two Arrays
    Given two arrays A and B of sizes N and M respectively, the task is to calculate the XOR sum of bitwise ANDs of all pairs of A and B Examples: Input: A={3, 5}, B={2, 3}, N=2, M=2Output:0Explanation:The answer is (3&2)^(3&3)^(5&2)^(5&3)=1^3^0^2=0. Input: A={1, 2, 3}, B={5, 6}, N=3, M=
    9 min read
    Sum of Bitwise AND of all pairs possible from two arrays
    Given two arrays A[] and B[] of size N and M respectively, the task is to find the sum of Bitwise AND of all possible unordered pairs (A[i], B[j]) from the two arrays. Examples: Input: A[] = {1, 2} , B[] = {3, 4} Output: 3 Explanation: Bitwise AND of all possible pairs are 1 & 3 = 1 1 & 4 =
    5 min read
    Sum of Bitwise OR of all pairs in a given array
    Given an array "arr[0..n-1]" of integers. The task is to calculate the sum of Bitwise OR of all pairs, i.e. calculate the sum of "arr[i] | arr[j]" for all the pairs in the given array where i < j. Here '|' is a bitwise OR operator. The expected time complexity is O(n). Examples: Input: arr[] = {5
    13 min read
    Number of unique pairs whose bitwise XOR and OR are same
    Given an integer N, the task is to find the number of pairs (say {a, b})from 1 to N (both inclusive) that satisfies the condition: a and b are distinct elements. The values of a | b and a ^ b are equal and a( a | b ) = b( a ^ b ) - ( a | b ) also holds true. Examples: Input: N=5Output:1Explanation:
    9 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