Skip to content
Related Articles

Related Articles

Minimizing array sum by applying XOR operation on all elements of the array
  • Last Updated : 27 Apr, 2021

Given an array arr[] of N integer elements, the task is to choose an element X and apply XOR operation on every element of the array with X such that the array sum is minimized.
 

Input: arr[] = {3, 5, 7, 11, 15} 
Output: 26 
Binary representation of the array elements are {0011, 0101, 0111, 1011, 1111} 
We take xor of every element with 7 in order to minimize the sum. 
3 XOR 7 = 0100 (4) 
5 XOR 7 = 0010 (2) 
7 XOR 7 = 0000 (0) 
11 XOR 7 = 1100 (12) 
15 XOR 7 = 1000 (8) 
Sum = 4 + 2 + 0 + 12 + 8 = 26
Input: arr[] = {1, 2, 3, 4, 5} 
Output: 14 
 

 

Approach: The task is to find the element X with which we have to take xor of each element. 
 

  • Convert each number into binary form and update the frequency of bit (0 or 1) in an array corresponding to the position of each bit in the element in the array.
  • Now, Traverse the array and check whether the element at index is more than n/2 (for ‘n’ elements, we check whether the set bit appears more than n/2 at index), and subsequently, we obtain element ‘X’
  • Now, take xor of ‘X’ with all the elements and return the sum.

Below is the implementation of the above approach: 
 



C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
const int MAX = 25;
 
// Function to return the minimized sum
int getMinSum(int arr[], int n)
{
    int bits_count[MAX], max_bit = 0, sum = 0, ans = 0;
 
    memset(bits_count, 0, sizeof(bits_count));
 
    // To store the frequency
    // of bit in every element
    for (int d = 0; d < n; d++) {
        int e = arr[d], f = 0;
        while (e > 0) {
            int rem = e % 2;
            e = e / 2;
            if (rem == 1) {
                bits_count[f] += rem;
            }
            f++;
        }
        max_bit = max(max_bit, f);
    }
 
    // Finding element X
    for (int d = 0; d < max_bit; d++) {
        int temp = pow(2, d);
        if (bits_count[d] > n / 2)
            ans = ans + temp;
    }
 
    // Taking XOR of elements and finding sum
    for (int d = 0; d < n; d++) {
        arr[d] = arr[d] ^ ans;
        sum = sum + arr[d];
    }
    return sum;
}
 
// Driver code
int main()
{
    int arr[] = { 3, 5, 7, 11, 15 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << getMinSum(arr, n);
 
    return 0;
}

Java




// Java implementation of the approach
class GFG {
 
    static int MAX = 25;
 
    // Function to return the minimized sum
    static int getMinSum(int arr[], int n)
    {
        int bits_count[] = new int[MAX],
            max_bit = 0, sum = 0, ans = 0;
 
        // To store the frequency
        // of bit in every element
        for (int d = 0; d < n; d++) {
            int e = arr[d], f = 0;
            while (e > 0) {
                int rem = e % 2;
                e = e / 2;
                if (rem == 1) {
                    bits_count[f] += rem;
                }
                f++;
            }
            max_bit = Math.max(max_bit, f);
        }
 
        // Finding element X
        for (int d = 0; d < max_bit; d++) {
            int temp = (int)Math.pow(2, d);
            if (bits_count[d] > n / 2)
                ans = ans + temp;
        }
 
        // Taking XOR of elements and finding sum
        for (int d = 0; d < n; d++) {
            arr[d] = arr[d] ^ ans;
            sum = sum + arr[d];
        }
        return sum;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 3, 5, 7, 11, 15 };
        int n = arr.length;
        System.out.println(getMinSum(arr, n));
    }
}
 
// This code has been contributed by 29AjayKumar

Python3




# Python3 implementation of the approach
 
MAX = 25;
 
# Function to return the minimized sum
def getMinSum(arr, n) :
    bits_count = [0]* MAX
    max_bit = 0; sum = 0; ans = 0;
 
    # To store the frequency
    # of bit in every element
    for d in range(n) :
        e = arr[d]; f = 0;
        while (e > 0) :
            rem = e % 2;
            e = e // 2;
            if (rem == 1) :
                bits_count[f] += rem;
                 
            f += 1
             
        max_bit = max(max_bit, f);
     
 
    # Finding element X
    for d in range(max_bit) :
        temp = pow(2, d);
         
        if (bits_count[d] > n // 2) :
            ans = ans + temp;
 
 
    # Taking XOR of elements and finding sum
    for d in range(n) :
        arr[d] = arr[d] ^ ans;
        sum = sum + arr[d];
     
    return sum
     
 
# Driver code
if __name__ == "__main__" :
 
    arr = [ 3, 5, 7, 11, 15 ];
    n = len(arr);
 
    print(getMinSum(arr, n))
 
# This code is contributed by Ryuga

C#




// C# implementation of the approach
using System;
 
class GFG {
 
    static int MAX = 25;
 
    // Function to return the minimized sum
    static int getMinSum(int[] arr, int n)
    {
        int[] bits_count = new int[MAX];
        int max_bit = 0, sum = 0, ans = 0;
 
        // To store the frequency
        // of bit in every element
        for (int d = 0; d < n; d++) {
            int e = arr[d], f = 0;
            while (e > 0) {
                int rem = e % 2;
                e = e / 2;
                if (rem == 1) {
                    bits_count[f] += rem;
                }
                f++;
            }
            max_bit = Math.Max(max_bit, f);
        }
 
        // Finding element X
        for (int d = 0; d < max_bit; d++) {
            int temp = (int)Math.Pow(2, d);
            if (bits_count[d] > n / 2)
                ans = ans + temp;
        }
 
        // Taking XOR of elements and finding sum
        for (int d = 0; d < n; d++) {
            arr[d] = arr[d] ^ ans;
            sum = sum + arr[d];
        }
        return sum;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int[] arr = { 3, 5, 7, 11, 15 };
        int n = arr.Length;
        Console.WriteLine(getMinSum(arr, n));
    }
}
 
/* This code contributed by PrinciRaj1992 */

Javascript




<script>
// Javascript implementation of the approach
 
const MAX = 25;
 
// Function to return the minimized sum
function getMinSum(arr, n)
{
    let bits_count = new Array(MAX).fill(0),
    max_bit = 0, sum = 0, ans = 0;
 
    // To store the frequency
    // of bit in every element
    for (let d = 0; d < n; d++) {
        let e = arr[d], f = 0;
        while (e > 0) {
            let rem = e % 2;
            e = parseInt(e / 2);
            if (rem == 1) {
                bits_count[f] += rem;
            }
            f++;
        }
        max_bit = Math.max(max_bit, f);
    }
 
    // Finding element X
    for (let d = 0; d < max_bit; d++) {
        let temp = Math.pow(2, d);
        if (bits_count[d] > parseInt(n / 2))
            ans = ans + temp;
    }
 
    // Taking XOR of elements and finding sum
    for (let d = 0; d < n; d++) {
        arr[d] = arr[d] ^ ans;
        sum = sum + arr[d];
    }
    return sum;
}
 
// Driver code
    let arr = [ 3, 5, 7, 11, 15 ];
    let n = arr.length;
 
    document.write(getMinSum(arr, n));
 
</script>
Output: 
26

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live and Geeks Classes Live USA

My Personal Notes arrow_drop_up
Recommended Articles
Page :