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:
Count numbers in the range [L, R] having only three set bits
Next article icon

Find a number X such that XOR of given Array after adding X to each element is 0

Last Updated : 17 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of odd length N containing positive integers. The task is to find a positive integer X such that, adding X to all the elements of arr[] and then taking XOR of all the elements gives 0. Return -1 if no such X exists.

Examples: 

Input: arr[] = {2, 4, 5}
Output: 1
Explanation: Following are the operations performed in arr[] to get the desired result.
Adding 1 to each element in arr[] updates arr[] to arr[] = {3, 5, 6}
Now XOR of all the elements in arr[] is 3^5^6 = 0. 
Therefore, 1 is the required answer.  

Input: arr[] = {4, 5, 13}
Output: -1
Explanation: No such x exists for fulfilling the desired conditions. 

 

Approach: XOR of Odd number of 1’s = 1, while even number of 1’s = 0. This idea can be used to solve the given problem. Follow the steps mentioned below:

  • Initialize variable X = 0.
  • The binary representations of the array elements will be used for traversal of the elements and determining X.
  • Start traversing from the 0th bit to 63rd bit.
  • If at any bit position total number of set bits (1’s) of the array elements are odd, add that power of 2 with X.
  • If after completion of iteration there is odd number of 1 at any bit position then no such X exists. Otherwise, print X as answer.

See the illustrations below:

Illustration:

Case-1 (X possible): Take arr[] = { 2, 4, 5} 

  5th 4th 3rd 2nd 1st 0th
             
arr[0] 0 0 0 0 1 0
arr[1] 0 0 0 1 0 0
arr[2] 0 0 0 1 0 1
             
  X 0 0 0 0 0 0
  • Initially, X = 0 0 0 0 0 0, at 0th position set(1) bits are odd, so in order to make the set bits even,  flip the bits at 0th position. So, for flipping the bits just add (0 0 0 0 0 1) to all the elements of arr[] and in X.
  • Now, the table will look like the following:
  5th 4th 3rd 2nd 1st 0th
             
arr[0] 0 0 0 0 1 1
arr[1] 0 0 0 1 0 1
arr[2] 0 0 0 1 1 0
             
XOR 0 0 0 0 0 0
X 0 0 0 0 0 1
  • Now, the XOR of (arr[0]+x) ^  ( arr[1]+x) ^ arr[2]+x) = 0, result will be 0. So, print  res = X.

Take the following when no possible X

Case-2: Take example: arr[] = { 4, 5, 13 } 

  5th 4th 3rd 2nd 1st 0th
             
arr[0] 0 0 0 1 0 0
arr[1] 0 0 0 1 0 1
arr[2] 0 0 1 1 0 1
             
XOR 0 0 1 1 0 0
X 0 0 0 0 0 0

          XOR = Arr[0] ^ Arr[1] ^ Arr[2] = 1 1 0 0,   Here there are odd number of 1‘s at 2nd and 3rd bits.

  • So, add 2pow(2nd) to all elements of arr and in X, then again will take the XOR, after this the elements become:
  5th 4th 3rd 2nd 1st 0th
             
arr[0] 0 0 1 0 0 0
arr[1] 0 0 1 0 0 1
arr[2] 0 1 0 0 0 1
XOR 0 1 0 0 0 0
X 0 0 0 1 0 0

If this keeps on going the left most 1 in XOR keeps on moving left.

Below is the implementation of the above approach:

C++




// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find required result
long long solve(vector<long long>& a,
                int n)
{
    long long res = 0, j = 0, one = 1;
 
    // For 64 Bit
    while (j < 64) {
        // j is traversing each bit
        long long Xor = 0;
        long long powerOf2 = one << j;
 
        for (auto x : a)
            Xor ^= x;
 
        if (j == 63 && (Xor & powerOf2))
            return -1;
 
        if (Xor & powerOf2) {
            res += powerOf2;
            for (int i = 0; i < n; i++)
                a[i] += powerOf2;
        }
        j++;
    }
    return res;
}
 
// Driver Code
int main()
{
 
    // Size of arr[]
    int N = 3;
    vector<long long> arr = { 2, 4, 5 };
 
    cout << solve(arr, N) << '\n';
 
    return 0;
}
 
 

Java




// Java program for above approach
class GFG{
 
// Function to find required result
static long solve(int[] a,
                int n)
{
    long res = 0, j = 0, one = 1;
 
    // For 64 Bit
    while (j < 64)
    {
       
        // j is traversing each bit
        long Xor = 0;
        long powerOf2 = one << j;
 
        for (int x : a)
            Xor ^= x;
 
        if (j == 63 && (Xor & powerOf2)!=0)
            return -1;
 
        if ((Xor & powerOf2)!=0) {
            res += powerOf2;
            for (int i = 0; i < n; i++)
                a[i] += powerOf2;
        }
        j++;
    }
    return res;
}
 
// Driver Code
public static void main(String[] args)
{
 
    // Size of arr[]
    int N = 3;
    int[] arr = { 2, 4, 5 };
 
    System.out.print(solve(arr, N));
}
}
 
// This code is contributed by shikhasingrajput
 
 

Python3




# python program for above approach
 
# Function to find required result
def solve(a, n):
 
    res = 0
    j = 0
    one = 1
 
    # For 64 Bit
    while (j < 64):
                # j is traversing each bit
        Xor = 0
        powerOf2 = one << j
 
        for x in a:
            Xor ^= x
 
        if (j == 63 and (Xor & powerOf2)):
            return -1
 
        if (Xor & powerOf2):
            res += powerOf2
            for i in range(0, n):
                a[i] += powerOf2
 
        j += 1
 
    return res
 
# Driver Code
if __name__ == "__main__":
 
        # Size of arr[]
    N = 3
    arr = [2, 4, 5]
 
    print(solve(arr, N))
 
    # This code is contributed by rakeshsahni
 
 

C#




// C# program for above approach
using System;
class GFG
{
 
    // Function to find required result
    static long solve(int[] a, int n)
    {
        int res = 0, j = 0, one = 1;
 
        // For 64 Bit
        while (j < 64)
        {
 
            // j is traversing each bit
            long Xor = 0;
            long powerOf2 = one << j;
 
            foreach (int x in a)
                Xor ^= x;
 
            if (j == 63 && (Xor & powerOf2) != 0)
                return -1;
 
            if ((Xor & powerOf2) != 0)
            {
                res += (int)powerOf2;
                for (int i = 0; i < n; i++)
                    a[i] += (int)powerOf2;
            }
            j++;
        }
        return res;
    }
 
    // Driver Code
    public static void Main()
    {
 
        // Size of arr[]
        int N = 3;
        int[] arr = { 2, 4, 5 };
 
        Console.Write(solve(arr, N));
    }
}
 
// This code is contributed by gfgking
 
 

Javascript




<script>
 
// JavaScript program for above approach
 
// Function to find required result
function solve(a, n)
{
    let res = 0, j = 0, one = 1;
     
    // For 64 Bit
    while (j < 64)
    {
         
        // j is traversing each bit
        let Xor = 0;
        let powerOf2 = one << j;
     
        for(let x of a)
            Xor ^= x;
     
        if (j == 63 && (Xor & powerOf2))
            return -1;
     
        if (Xor & powerOf2)
        {
            res += powerOf2;
            for(let i = 0; i < n; i++)
                a[i] += powerOf2;
        }
        j++;
    }
    return res;
}
 
// Driver Code
 
// Size of arr[]
let N = 3;
let arr = [ 2, 4, 5 ];
 
document.write(solve(arr, N) + '<br>');
 
// This code is contributed by Potta Lokesh
 
</script>
 
 
Output
1

Time Complexity: O(N*logN)
Auxiliary Space: O(1)



Next Article
Count numbers in the range [L, R] having only three set bits
author
madhav_mohan
Improve
Article Tags :
  • Arrays
  • Bit Magic
  • DSA
  • Mathematical
  • Bit Algorithms
  • Bitwise-XOR
Practice Tags :
  • Arrays
  • Bit Magic
  • Mathematical

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