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 Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Minimum Bitwise AND operations to make any two array elements equal
Next article icon

Minimum Bitwise XOR operations to make any two array elements equal

Last Updated : 05 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of integers of size N and an integer K. One can perform the Bitwise XOR operation between any array element and K any number of times. The task is to print the minimum number of such operations required to make any two elements of the array equal. If it is not possible to make any two elements of the array equal after performing the above-mentioned operation then print -1.
Examples: 
 

Input : arr[] = {1, 9, 4, 3}, K = 3 
Output :-1 
Explanation : No possible to make any two elements equal
Input : arr[] = {13, 13, 21, 15}, K = 13 
Output :0 
Explanation : Already exists two same elements

 

Approach: The key observation is that if it is possible to make the desired array then the answer will be either 0, 1 or 2. It will never exceed 2. 
 

Because, if (x ^ k) = y 
then, performing (y ^ k) will give x again 
 

 

  1. The answer will be 0, if there are already equal elements in the array.
  2. For the answer to be 1, we will create a new array b[] which holds b[i] = (a[i] ^ K), 
    Now, for each a[i] we will check if there is any index j such that i != j and a[i] = b[j].
    If yes, then the answer will be 1.
  3. For the answer to be 2, we will check for an index i in the new array b[], If there is any index j such that i != j and b[i] = b[j]. 
    If yes, then the answer will be 2.
  4. If any of the above conditions is not satisfied then the answer will be -1.

Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the count of
// minimum operations required
int minOperations(int a[], int n, int K)
{
    unordered_map<int, bool> map;
    for (int i = 0; i < n; i++) {
 
        // Check if the initial array
        // already contains an equal pair
        if (map[a[i]])
            return 0;
        map[a[i]] = true;
    }
 
    // Create new array with XOR operations
    int b[n];
    for (int i = 0; i < n; i++)
        b[i] = a[i] ^ K;
 
    // Clear the map
    map.clear();
 
    // Check if the solution
    // is a single operation
    for (int i = 0; i < n; i++) {
 
        // If Bitwise XOR operation between
        // 'k' and a[i] gives
        // a number other than a[i]
        if (a[i] != b[i])
            map[b[i]] = true;
    }
 
    // Check if any of the a[i]
    // gets equal to any other element
    // of the array after the operation
    for (int i = 0; i < n; i++)
 
        // Single operation
        // will be enough
        if (map[a[i]])
            return 1;
 
    // Clear the map
    map.clear();
 
    // Check if the solution
    // is two operations
    for (int i = 0; i < n; i++) {
 
        // Check if the array 'b'
        // contains duplicates
        if (map[b[i]])
            return 2;
 
        map[b[i]] = true;
    }
 
    // Otherwise it is impossible to
    // create such an array with
    // Bitwise XOR operations
    return -1;
}
 
// Driver code
int main()
{
 
    int K = 3;
    int a[] = { 1, 9, 4, 3 };
    int n = sizeof(a) / sizeof(a[0]);
 
    // Function call to compute the result
    cout << minOperations(a, n, K);
 
    return 0;
}
 
 

Java




// Java implementation of the approach
import java.util.HashMap;
 
class GFG
{
    // Function to return the count of
    // minimum operations required
    static int minOperations(int[] a, int n, int k)
    {
        HashMap<Integer,
                Boolean> map = new HashMap<>();
        for (int i = 0; i < n; i++)
        {
 
            // Check if the initial array
            // already contains an equal pair
            if (map.containsKey(a[i]) &&
                map.get(a[i]))
                return 0;
            map.put(a[i], true);
        }
 
        // Create new array with XOR operations
        int[] b = new int[n];
        for (int i = 0; i < n; i++)
            b[i] = a[i] ^ k;
 
        // Clear the map
        map.clear();
 
        // Check if the solution
        // is a single operation
        for (int i = 0; i < n; i++)
        {
 
            // If Bitwise XOR operation between
            // 'k' and a[i] gives
            // a number other than a[i]
            if (a[i] != b[i])
                map.put(b[i], true);
        }
 
        // Check if any of the a[i]
        // gets equal to any other element
        // of the array after the operation
        for (int i = 0; i < n; i++)
         
            // Single operation
            // will be enough
            if (map.containsKey(a[i]) &&
                map.get(a[i]))
                return 1;
 
        // Clear the map
        map.clear();
 
        // Check if the solution
        // is two operations
        for (int i = 0; i < n; i++)
        {
 
            // Check if the array 'b'
            // contains duplicates
            if (map.containsKey(b[i]) &&
                map.get(b[i]))
                return 2;
 
            map.put(b[i], true);
        }
 
        // Otherwise it is impossible to
        // create such an array with
        // Bitwise XOR operations
        return -1;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int K = 3;
        int[] a = { 1, 9, 4, 3 };
        int n = a.length;
        System.out.println(minOperations(a, n, K));
    }
}
 
// This code is contributed by
// Vivek Kumar Singh
 
 

Python3




# Python3 implementation of the approach
 
# Function to return the count of
# minimum operations required
def minOperations(a, n, K) :
 
    map = dict.fromkeys(a, False);
    for i in range(n) :
 
        # Check if the initial array
        # already contains an equal pair
        if (map[a[i]]) :
            return 0;
        map[a[i]] = True;
 
    # Create new array with XOR operations
    b = [0] * n;
    for i in range(n) :
        b[i] = a[i] ^ K;
 
    # Clear the map
    map.clear();
 
    # Check if the solution
    # is a single operation
    for i in range(n) :
 
        # If Bitwise XOR operation between
        # 'k' and a[i] gives
        # a number other than a[i]
        if (a[i] != b[i]) :
            map[b[i]] = True;
     
    # Check if any of the a[i]
    # gets equal to any other element
    # of the array after the operation
    for i in range(n) :
 
        # Single operation
        # will be enough
        if a[i] in map :
            return 1;
 
    # Clear the map
    map.clear();
 
    # Check if the solution
    # is two operations
    for i in range(n) :
         
        # Check if the array 'b'
        # contains duplicates
        if b[i] in map :
            return 2;
 
        map[b[i]] = True;
 
    # Otherwise it is impossible to
    # create such an array with
    # Bitwise XOR operations
    return -1;
 
# Driver code
if __name__ == "__main__" :
 
    K = 3;
    a = [ 1, 9, 4, 3 ];
    n = len(a);
 
    # Function call to compute the result
    print(minOperations(a, n, K));
 
# This code is contributed by AnkitRai01
 
 

C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
     
    // Function to return the count of
    // minimum operations required
    public static int minOperations(int[] a,
                                    int n, int K)
    {
 
        Dictionary<int, Boolean> map =
                new Dictionary<int, Boolean>();
 
        for (int i = 0; i < n; i++)
        {
 
            // Check if the initial array
            // already contains an equal pair
            if (map.ContainsKey(a[i]))
                return 0;
 
            map.Add(a[i], true);
        }
 
        // Create new array with XOR operations
        int[] b = new int[n];
        for (int i = 0; i < n; i++)
            b[i] = a[i] ^ K;
 
        // Clear the map
        map.Clear();
 
        // Check if the solution
        // is a single operation
        for (int i = 0; i < n; i++)
        {
 
            // If Bitwise OR operation between
            // 'k' and a[i] gives
            // a number other than a[i]
            if (a[i] != b[i])
                map.Add(b[i], true);
        }
 
        // Check if any of the a[i]
        // gets equal to any other element
        // of the array after the operation
        for (int i = 0; i < n; i++)
        {
 
            // Single operation
            // will be enough
            if (map.ContainsKey(a[i]))
                return 1;
        }
 
        // Clear the map
        map.Clear();
 
        // Check if the solution
        // is two operations
        for (int i = 0; i < n; i++)
        {
 
            // Check if the array 'b'
            // contains duplicates
            if (map.ContainsKey(b[i]))
                return 2;
            map.Add(b[i], true);
        }
 
        // Otherwise it is impossible to
        // create such an array with
        // Bitwise OR operations
        return -1;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int K = 3;
        int[] a = { 1, 9, 4, 3 };
        int n = a.Length;
        Console.WriteLine(minOperations(a, n, K));
    }
}
 
// This code is contributed by Rajput-Ji
 
 

Javascript




<script>
 
 
// Javascript implementation of the approach
 
// Function to return the count of
// minimum operations required
function minOperations(a, n, K)
{
    var map = new Map();
    for (var i = 0; i < n; i++) {
 
        // Check if the initial array
        // already contains an equal pair
        if (map[a[i]])
            return 0;
        map[a[i]] = true;
    }
 
    // Create new array with XOR operations
    var b = Array(n);
    for (var i = 0; i < n; i++)
        b[i] = a[i] ^ K;
 
    // Clear the map
    map = new Map();
 
    // Check if the solution
    // is a single operation
    for (var i = 0; i < n; i++) {
 
        // If Bitwise XOR operation between
        // 'k' and a[i] gives
        // a number other than a[i]
        if (a[i] != b[i])
            map[b[i]] = true;
    }
 
    // Check if any of the a[i]
    // gets equal to any other element
    // of the array after the operation
    for (var i = 0; i < n; i++)
 
        // Single operation
        // will be enough
        if (map[a[i]])
            return 1;
 
    // Clear the map
    map = new Map();
 
    // Check if the solution
    // is two operations
    for (var i = 0; i < n; i++) {
 
        // Check if the array 'b'
        // contains duplicates
        if (map[b[i]])
            return 2;
 
        map[b[i]] = true;
    }
 
    // Otherwise it is impossible to
    // create such an array with
    // Bitwise XOR operations
    return -1;
}
 
// Driver code
var K = 3;
var a = [ 1, 9, 4, 3 ];
var n = a.length;
// Function call to compute the result
document.write( minOperations(a, n, K));
 
</script>   
 
 
Output: 
-1

 

Time complexity: O(n) where n is size of input array

Auxiliary space: O(n)



Next Article
Minimum Bitwise AND operations to make any two array elements equal

G

gp6
Improve
Article Tags :
  • Arrays
  • DSA
  • Hash
  • Bitwise-XOR
  • cpp-map
Practice Tags :
  • Arrays
  • Hash

Similar Reads

  • Bit Manipulation for Competitive Programming
    Bit manipulation is a technique in competitive programming that involves the manipulation of individual bits in binary representations of numbers. It is a valuable technique in competitive programming because it allows you to solve problems efficiently, often reducing time complexity and memory usag
    15+ min read
  • Count set bits in an integer
    Write an efficient program to count the number of 1s in the binary representation of an integer.Examples : Input : n = 6Output : 2Binary representation of 6 is 110 and has 2 set bits Input : n = 13Output : 3Binary representation of 13 is 1101 and has 3 set bits [Naive Approach] - One by One Counting
    15+ min read
  • Count total set bits in first N Natural Numbers (all numbers from 1 to N)
    Given a positive integer n, the task is to count the total number of set bits in binary representation of all natural numbers from 1 to n. Examples: Input: n= 3Output: 4Explanation: Numbers from 1 to 3: {1, 2, 3}Binary Representation of 1: 01 -> Set bits = 1Binary Representation of 2: 10 -> Se
    9 min read
  • Check whether the number has only first and last bits set
    Given a positive integer n. The problem is to check whether only the first and last bits are set in the binary representation of n.Examples: Input : 9 Output : Yes (9)10 = (1001)2, only the first and last bits are set. Input : 15 Output : No (15)10 = (1111)2, except first and last there are other bi
    4 min read
  • Shortest path length between two given nodes such that adjacent nodes are at bit difference 2
    Given an unweighted and undirected graph consisting of N nodes and two integers a and b. The edge between any two nodes exists only if the bit difference between them is 2, the task is to find the length of the shortest path between the nodes a and b. If a path does not exist between the nodes a and
    7 min read
  • Calculate Bitwise OR of two integers from their given Bitwise AND and Bitwise XOR values
    Given two integers X and Y, representing Bitwise XOR and Bitwise AND of two positive integers, the task is to calculate the Bitwise OR value of those two positive integers. Examples: Input: X = 5, Y = 2 Output: 7 Explanation: If A and B are two positive integers such that A ^ B = 5, A & B = 2, t
    7 min read
  • Unset least significant K bits of a given number
    Given an integer N, the task is to print the number obtained by unsetting the least significant K bits from N. Examples: Input: N = 200, K=5Output: 192Explanation: (200)10 = (11001000)2 Unsetting least significant K(= 5) bits from the above binary representation, the new number obtained is (11000000
    4 min read
  • Find all powers of 2 less than or equal to a given number
    Given a positive number N, the task is to find out all the perfect powers of two which are less than or equal to the given number N. Examples: Input: N = 63 Output: 32 16 8 4 2 1 Explanation: There are total of 6 powers of 2, which are less than or equal to the given number N. Input: N = 193 Output:
    6 min read
  • Powers of 2 to required sum
    Given an integer N, task is to find the numbers which when raised to the power of 2 and added finally, gives the integer N. Example : Input : 71307 Output : 0, 1, 3, 7, 9, 10, 12, 16 Explanation : 71307 = 2^0 + 2^1 + 2^3 + 2^7 + 2^9 + 2^10 + 2^12 + 2^16 Input : 1213 Output : 0, 2, 3, 4, 5, 7, 10 Exp
    10 min read
  • Print bitwise AND set of a number N
    Given a number N, print all the numbers which are a bitwise AND set of the binary representation of N. Bitwise AND set of a number N is all possible numbers x smaller than or equal N such that N & i is equal to x for some number i. Examples : Input : N = 5Output : 0, 1, 4, 5 Explanation: 0 &
    8 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