Open In App

Find the maximum subset XOR of a given set

Last Updated : 20 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a set of positive integers. find the maximum XOR subset value in the given set. Expected time complexity O(n).

Examples:

Input: set[] = {2, 4, 5}
Output: 7
The subset {2, 5} has maximum XOR value
Input: set[] = {9, 8, 5}
Output: 13
The subset {8, 5} has maximum XOR value
Input: set[] = {8, 1, 2, 12, 7, 6}
Output: 15
The subset {1, 2, 12} has maximum XOR value
Input: set[] = {4, 6}
Output: 6
The subset {6} has maximum XOR value

Note: This problem is different from the maximum subarray XOR. Here we need to find a subset instead of a subarray. 

Recommended Practice

A Simple Solution is to generate all possible subsets of given set, find XOR of every subset and return the subset with maximum XOR.

Below is an Efficient Algorithm that works in O(n) time. The idea is based on below facts:

  1. Number of bits to represent all elements is fixed which is 32 bits for integer in most of the compilers.
  2. If maximum element has Most Significant Bit MSB at position i, then result is at least 2i
1. Initialize index of chosen elements as 0. Let this index be 
'index'
2. Traverse through all bits starting from most significant bit.
Let i be the current bit.
......(a) Find the maximum element with i'th bit set. If there
is no element with i'th bit set, continue to smaller
bit.
......(b) Let the element with i'th bit set be maxEle and index
of this element be maxInd. Place maxEle at 'index' and
(by swapping set[index] and set[maxInd])
......(c) Do XOR of maxEle with all numbers having i'th bit as set.
......(d) Increment index
3. Return XOR of all elements in set[]. Note that set[] is modified
in step 2.c.

Below is the implementation of this algorithm. 

C++
// C++ program to find 
// maximum XOR subset
#include<bits/stdc++.h>
using namespace std;

// Number of bits to 
// represent int
#define INT_BITS 32

// Function to return
// maximum XOR subset
// in set[]
int maxSubsetXOR(int set[], int n)
{
    // Initialize index of
    // chosen elements
    int index = 0;

    // Traverse through all
    // bits of integer 
    // starting from the most
    // significant bit (MSB)
    for (int i = INT_BITS-1; i >= 0; i--)
    {
        // Initialize index of
        // maximum element and
        // the maximum element
        int maxInd = index;
        int maxEle = INT_MIN;
        for (int j = index; j < n; j++)
        {
            // If i'th bit of set[j]
            // is set and set[j] is 
            // greater than max so far.
            if ( (set[j] & (1 << i)) != 0 
                     && set[j] > maxEle )
                maxEle = set[j], maxInd = j;
        }

        // If there was no 
        // element with i'th
        // bit set, move to
        // smaller i
        if (maxEle == INT_MIN)
        continue;

        // Put maximum element
        // with i'th bit set 
        // at index 'index'
        swap(set[index], set[maxInd]);

        // Update maxInd and 
        // increment index
        maxInd = index;

        // Do XOR of set[maxIndex]
        // with all numbers having
        // i'th bit as set.
        for (int j=0; j<n; j++)
        {
            // XOR set[maxInd] those
            // numbers which have the
            // i'th bit set
            if (j != maxInd &&
               (set[j] & (1 << i)) != 0)
                set[j] = set[j] ^ set[maxInd];
        }

        // Increment index of
        // chosen elements
        index++;
    }

    // Final result is 
    // XOR of all elements
    int res = 0;
    for (int i = 0; i < n; i++)
        res ^= set[i];
    return res;
}

// Driver program 
int main()
{
    int set[] = {9, 8, 5};
    int n = sizeof(set) / sizeof(set[0]);
    
    cout << "Max subset XOR is ";
    cout << maxSubsetXOR(set, n);
    return 0;
}
Java
// Java program to find
// maximum XOR subset
import java.util.*;

class GFG {
    
// Number of bits to
// represent int
static final int INT_BITS = 32;

// Function to return
// maximum XOR subset
// in set[]
static int maxSubarrayXOR(int set[], int n)
{
    // Initialize index of
    // chosen elements
    int index = 0;

    // Traverse through all
    // bits of integer
    // starting from the most
    // significant bit (MSB)
    for (int i = INT_BITS - 1; i >= 0; i--) 
    {
    // Initialize index of
    // maximum element and
    // the maximum element
    int maxInd = index;
    int maxEle = Integer.MIN_VALUE;
    for (int j = index; j < n; j++) {
        
        // If i'th bit of set[j]
        // is set and set[j] is
        // greater than max so far.
        if ((set[j] & (1 << i)) != 0 && set[j] > maxEle)
        {
        maxEle = set[j];
        maxInd = j;
        }
    }

    // If there was no
    // element with i'th
    // bit set, move to
    // smaller i
    if (maxEle == -2147483648)
        continue;

    // Put maximum element
    // with i'th bit set
    // at index 'index'
    int temp = set[index];
    set[index] = set[maxInd];
    set[maxInd] = temp;

    // Update maxInd and
    // increment index
    maxInd = index;

    // Do XOR of set[maxIndex]
    // with all numbers having
    // i'th bit as set.
    for (int j = 0; j < n; j++) {
        
        // XOR set[maxInd] those
        // numbers which have the
        // i'th bit set
        if (j != maxInd && (set[j] & (1 << i)) != 0)
        set[j] = set[j] ^ set[maxInd];
    }

    // Increment index of
    // chosen elements
    index++;
    }

    // Final result is
    // XOR of all elements
    int res = 0;
    for (int i = 0; i < n; i++)
    res ^= set[i];
    return res;
}

// Driver code
public static void main(String arg[]) {
    int set[] = {9, 8, 5};
    int n = set.length;

    System.out.print("Max subset XOR is ");
    System.out.print(maxSubarrayXOR(set, n));
}
}

// This code is contributed by Anant Agarwal.
Python
# Python program to find 
# maximum XOR subset

# Number of bits to 
# represent int
INT_BITS=32
 
# Function to return
# maximum XOR subset
# in set[]
def maxSubarrayXOR(set,n):

    # Initialize index of
    # chosen elements
    index = 0
 
    # Traverse through all
    # bits of integer 
    # starting from the most
    # significant bit (MSB)
    for i in range(INT_BITS-1,-1,-1):
    
        # Initialize index of
        # maximum element and
        # the maximum element
        maxInd = index
        maxEle = -2147483648
        for j in range(index,n):
        
            # If i'th bit of set[j]
            # is set and set[j] is 
            # greater than max so far.
            if ( (set[j] & (1 << i)) != 0 
                     and set[j] > maxEle ):
                
                maxEle = set[j]
                maxInd = j
        
        # If there was no 
        # element with i'th
        # bit set, move to
        # smaller i
        if (maxEle ==-2147483648):
            continue
 
        # Put maximum element
        # with i'th bit set 
        # at index 'index'
        temp=set[index]
        set[index]=set[maxInd]
        set[maxInd]=temp
 
        # Update maxInd and 
        # increment index
        maxInd = index
 
        # Do XOR of set[maxIndex]
        # with all numbers having
        # i'th bit as set.
        for j in range(n):
        
            # XOR set[maxInd] those
            # numbers which have the
            # i'th bit set
            if (j != maxInd and
               (set[j] & (1 << i)) != 0):
                set[j] = set[j] ^ set[maxInd]
        
 
        # Increment index of
        # chosen elements
        index=index + 1
    
 
    # Final result is 
    # XOR of all elements
    res = 0
    for i in range(n):
        res =res ^ set[i]
    return res

# Driver code

set= [9, 8, 5]
n =len(set)

print("Max subset XOR is ",end="")
print(maxSubarrayXOR(set, n))

# This code is contributed
# by Anant Agarwal.
C#
// C# program to find
// maximum XOR subset
using System;

class GFG
{ 
    
    // Number of bits to
    // represent int
    static int INT_BITS = 32;
    
    // Function to return
    // maximum XOR subset
    // in set[]
    static int maxSubarrayXOR(int []set, 
                              int n)
    {
        
        // Initialize index of
        // chosen elements
        int index = 0;
    
        // Traverse through all
        // bits of integer
        // starting from the most
        // significant bit (MSB)
        for (int i = INT_BITS - 1; 
                 i >= 0; i--) 
        {
            
        // Initialize index of
        // maximum element and
        // the maximum element
        int maxInd = index;
        int maxEle = int.MinValue;
        for (int j = index; j < n; j++)
        {
            
            // If i'th bit of set[j]
            // is set and set[j] is
            // greater than max so far.
            if ((set[j] & (1 << i)) != 0 &&
                 set[j] > maxEle)
            {
                maxEle = set[j];
                maxInd = j;
            }
        }
    
        // If there was no
        // element with i'th
        // bit set, move to
        // smaller i
        if (maxEle == -2147483648)
            continue;
    
        // Put maximum element
        // with i'th bit set
        // at index 'index'
        int temp = set[index];
        set[index] = set[maxInd];
        set[maxInd] = temp;
    
        // Update maxInd and
        // increment index
        maxInd = index;
    
        // Do XOR of set[maxIndex]
        // with all numbers having
        // i'th bit as set.
        for (int j = 0; j < n; j++) 
        {
        
            // XOR set[maxInd] those
            // numbers which have the
            // i'th bit set
            if (j != maxInd && (set[j] & 
               (1 << i)) != 0)
            set[j] = set[j] ^ set[maxInd];
    }

        // Increment index of
        // chosen elements
        index++;
    }

    // Final result is
    // XOR of all elements
        int res = 0;
        for (int i = 0; i < n; i++)
        res ^= set[i];
        return res;
    }
    
    // Driver code
    public static void Main() 
    {
        int []set = {9, 8, 5};
        int n = set.Length;
    
        Console.Write("Max subset XOR is ");
        Console.Write(maxSubarrayXOR(set, n));
    }
}

// This code is contributed by Sam007.
Javascript
// Javascript program to find
// maximum XOR subset    

    // Number of bits to
    // represent int
    let INT_BITS = 32;
    
    // Function to return
    // maximum XOR subset
    // in set[]
    function maxSubarrayXOR(set,n)
    {
        // Initialize index of
        // chosen elements
        let index = 0;
        
        // Traverse through all
        // bits of integer
        // starting from the most
        // significant bit (MSB)
        
        for (let i = INT_BITS - 1; i >= 0; i--) 
        {
            // Initialize index of
            // maximum element and
            // the maximum element
            let maxInd = index;
            let maxEle = Number.MIN_VALUE;
            for (let j = index; j < n; j++) {
                  
                // If i'th bit of set[j]
                // is set and set[j] is
                // greater than max so far.
                if ((set[j] & (1 << i)) != 0 && set[j] > maxEle)
                {
                maxEle = set[j];
                maxInd = j;
                }
            }
          
            // If there was no
            // element with i'th
            // bit set, move to
            // smaller i
            if (maxEle == Number.MIN_VALUE)
                continue;
          
            // Put maximum element
            // with i'th bit set
            // at index 'index'
            let temp = set[index];
            set[index] = set[maxInd];
            set[maxInd] = temp;
          
            // Update maxInd and
            // increment index
            maxInd = index;
          
            // Do XOR of set[maxIndex]
            // with all numbers having
            // i'th bit as set.
            for (let j = 0; j < n; j++) {
                  
                // XOR set[maxInd] those
                // numbers which have the
                // i'th bit set
                if (j != maxInd && (set[j] & (1 << i)) != 0)
                    set[j] = set[j] ^ set[maxInd];
            }
          
            // Increment index of
            // chosen elements
            index++;
        }
      
        // Final result is
        // XOR of all elements
        let res = 0;
        for (let i = 0; i < n; i++)
            res ^= set[i];
        return res;
        
    }
    
    // Driver code
    let set=[9, 8, 5];
    let n = set.length;
    console.log("Max subset XOR is ");
    console.log(maxSubarrayXOR(set, n));
    
    //  This code is contributed by avanitrachhadiya2155
    
PHP
<?php 
// PHP program to find maximum XOR subset

// Number of bits to represent int
$INT_BITS = 32;

// Function to return maximum XOR subset
// in set[]
function maxSubarrayXOR(&$set, $n)
{
    global $INT_BITS;
    
    // Initialize index of chosen elements
    $index = 0;

    // Traverse through all bits of integer 
    // starting from the most significant bit (MSB)
    for ($i = $INT_BITS - 1; $i >= 0; $i--)
    {
        // Initialize index of maximum element 
        // and the maximum element
        $maxInd = $index;
        $maxEle = 0;
        for ($j = $index; $j < $n; $j++)
        {
            // If i'th bit of set[j]
            // is set and set[j] is 
            // greater than max so far.
            if ( ($set[$j] & (1 << $i)) != 0 && 
                  $set[$j] > $maxEle )
            {
                $maxEle = $set[$j];
                $maxInd = $j;
            }
        }

        // If there was no element with i'th
        // bit set, move to smaller i
        if ($maxEle == 0)
        continue;

        // Put maximum element with i'th bit 
        // set at index 'index'
        $t = $set[$index];
        $set[$index] = $set[$maxInd];
        $set[$maxInd] = $t;

        // Update maxInd and increment index
        $maxInd = $index;

        // Do XOR of set[maxIndex] with all numbers 
        // having i'th bit as set.
        for ($j = 0; $j < $n; $j++)
        {
            // XOR set[maxInd] those numbers which 
            // have the i'th bit set
            if ($j != $maxInd &&
               ($set[$j] & (1 << $i)) != 0)
                $set[$j] = $set[$j] ^ $set[$maxInd];
        }

        // Increment index of chosen elements
        $index++;
    }

    // Final result is XOR of all elements
    $res = 0;
    for ($i = 0; $i < $n; $i++)
        $res ^= $set[$i];
    return $res;
}

// Driver Code
$set = array(9, 8, 5);
$n = sizeof($set);
echo "Max subset XOR is ";
echo maxSubarrayXOR($set, $n);

// This code is contributed by ita_c
?>

Output: 

Max subset XOR is 13

Time Complexity: O(n)

Auxiliary Space: O(1)

Illustration:  

Let the input set be : {9, 8, 5}
We start from 31st bit [Assuming Integers are 32 bit
long]. The loop will continue without doing anything till 4'th bit.
The 4th bit is set in set[0] i.e. 9 and this is the maximum
element with 4th bit set. So we choose this element and check
if any other number has the same bit set. If yes, we XOR that
number with 9. The element set[1], i.e., 8 also has 4'th bit
set. Now set[] becomes {9, 1, 5}. We add 9 to the list of
chosen elements by incrementing 'index'
We move further and find the maximum number with 3rd bit set
which is set[2] i.e. 5 No other number in the array has 3rd
bit set. 5 is also added to the list of chosen element.
We then iterate for bit 2 (no number for this) and then for
1 which is 1. But numbers 9 and 5 have the 1st bit set. Thus
we XOR 9 and 5 with 1 and our set becomes (8, 1, 4)
Finally, we XOR current elements of set and get the result
as 8 ^ 1 ^ 4 = 13.

Using BitMasking:

Approach:
We first find the maximum number in the input list nums using the built-in max function.

If the maximum number is 0, it means that all the numbers in the list are also 0, and so the maximum XOR value will also be 0. So we return 0.

Otherwise, we calculate the maximum bit position of the maximum number using the math.log2 function.

We initialize the ans variable to 0, which will eventually hold the maximum XOR value we find.

We also initialize a mask variable to 0, which we will use to generate a set of prefixes for each bit position.

We loop through the bit positions in descending order from the maximum bit position to 0.

In each iteration, we set the mask variable to the current bit position by left-shifting 1 by the bit position and subtracting 1. For example, if the bit position is 2, mask will be set to 0b00000100.

We generate a set of prefixes for the current bit position by applying the mask to each number in the input list using the bitwise AND operator (&). This results in a set of numbers where the rightmost bits up to the current bit position are all 0.

We initialize a candidate variable to the current ans value with the bit at the current bit position set to 1 using the bitwise OR operator (|).

We loop through each prefix in the set of prefixes we generated in step 8.

For each prefix, we check if there exists another prefix in the set that, when XORed with the candidate variable, results in another prefix in the set. If such a prefix exists, it means that we can use the candidate variable as the new ans value, since it indicates that we can form a larger XOR value by setting the bit at the current bit position to 1.

If we find such a prefix, we set the ans variable to the candidate value and break out of the loop.

We return the ans variable at the end of the loop, which should contain the maximum XOR value we found.

C++
#include <bits/stdc++.h>
using namespace std;

//this solution gets from discussion
int findMaximumXOR(int arr[], int N) {
  
    int index = 0;
    for (int i = 31; i >= 0; i--) {
        int maxElement = INT_MIN;
        int maxIndex = index;
        // Find the maximum element with the current bit set starting from the current index
        for (int j = index; j < N; j++) {
            if (arr[j] & (1 << i) && arr[j] > maxElement) {
                maxIndex = j;
                maxElement = arr[j];
            }
        }
        // If no element with the current bit set is found, continue to the next bit
        if (maxElement == INT_MIN) continue;
        // Swap the maximum element with the element at the current index
        swap(arr[index], arr[maxIndex]);
        maxIndex = index;
        // Update other elements in the array to eliminate the common prefix
        for (int j = 0; j < N; j++) {
            if (arr[j] & (1 << i) && j != maxIndex) {
                arr[j] = arr[j] ^ maxElement;
            }
        }
        // Move to the next index
        index++;
    }
    // Calculate the XOR of all elements in the array to get the maximum XOR subset value
    int ans = 0;
    for (int i = 0; i < N; i++){
      ans ^= arr[i];
    }
    return ans;
}

// Driver code
int main() {
    int set[] = {9, 8, 5};
    int n = sizeof(set)/sizeof(set[0]);
 
    cout << "Max subset XOR is " << findMaximumXOR(set,n);
}
Java
import java.util.Arrays;

public class MaximumXORSubset {

    public static int findMaximumXOR(int[] arr, int N) {

        int index = 0;
        for (int i = 31; i >= 0; i--) {
            int maxElement = Integer.MIN_VALUE;
            int maxIndex = index;

            // Find the maximum element with the current bit set starting from the current index
            for (int j = index; j < N; j++) {
                if ((arr[j] & (1 << i)) != 0 && arr[j] > maxElement) {
                    maxIndex = j;
                    maxElement = arr[j];
                }
            }

            // If no element with the current bit set is found, continue to the next bit
            if (maxElement == Integer.MIN_VALUE) {
                continue;
            }

            // Swap the maximum element with the element at the current index
            swap(arr, index, maxIndex);
            maxIndex = index;

            // Update other elements in the array to eliminate the common prefix
            for (int j = 0; j < N; j++) {
                if ((arr[j] & (1 << i)) != 0 && j != maxIndex) {
                    arr[j] ^= maxElement;
                }
            }

            // Move to the next index
            index++;
        }

        // Calculate the XOR of all elements in the array to get the maximum XOR subset value
        int ans = 0;
        for (int i = 0; i < N; i++) {
            ans ^= arr[i];
        }

        return ans;
    }

    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static void main(String[] args) {
        int[] set = {9, 8, 5};
        int n = set.length;

        System.out.println("Max subset XOR is " + findMaximumXOR(set, n));
    }
}
Python
def maxSubsetXOR(arr):
    index = 0
    for i in range(31, -1, -1):
        maxElement = float('-inf')
        maxIndex = index
        for j in range(index, len(arr)):
            if arr[j] & (1 << i) and arr[j] > maxElement:
                maxIndex = j
                maxElement = arr[j]
        if maxElement == float('-inf'):
            continue
        arr[index], arr[maxIndex] = arr[maxIndex], arr[index]
        maxIndex = index
        for j in range(len(arr)):
            if arr[j] & (1 << i) and j != maxIndex:
                arr[j] ^= maxElement
        index += 1
    ans = 0
    for num in arr:
        ans ^= num
    return ans

def findMaximumXOR(nums):
    return maxSubsetXOR(nums)

def main():
    set = [9, 8, 5]
    print("Max subset XOR is", findMaximumXOR(set))

if __name__ == "__main__":
    main()
C#
using System;

public class MaximumXORFinder
{
    public static int MaxSubsetXOR(int[] arr)
    {
        int index = 0;
        for (int i = 31; i >= 0; i--)
        {
            int maxElement = int.MinValue;
            int maxIndex = index;
            for (int j = index; j < arr.Length; j++)
            {
                if ((arr[j] & (1 << i)) != 0 && arr[j] > maxElement)
                {
                    maxIndex = j;
                    maxElement = arr[j];
                }
            }
            if (maxElement == int.MinValue)
                continue;
            Swap(ref arr[index], ref arr[maxIndex]);
            maxIndex = index;
            for (int j = 0; j < arr.Length; j++)
            {
                if ((arr[j] & (1 << i)) != 0 && j != maxIndex)
                {
                    arr[j] ^= maxElement;
                }
            }
            index++;
        }
        int ans = 0;
        foreach (int num in arr)
        {
            ans ^= num;
        }
        return ans;
    }

    public static int FindMaximumXOR(int[] nums)
    {
        return MaxSubsetXOR(nums);
    }

    private static void Swap(ref int a, ref int b)
    {
        int temp = a;
        a = b;
        b = temp;
    }

    public static void Main(string[] args)
    {
        int[] set = { 9, 8, 5};

        Console.WriteLine("Max subset XOR is " + FindMaximumXOR(set));
    }
}
Javascript
function maxSubsetXOR(arr) {
    let index = 0;
    for (let i = 31; i >= 0; i--) {
        let maxElement = Number.MIN_SAFE_INTEGER;
        let maxIndex = index;
        for (let j = index; j < arr.length; j++) {
            if ((arr[j] & (1 << i)) && arr[j] > maxElement) {
                maxIndex = j;
                maxElement = arr[j];
            }
        }
        if (maxElement === Number.MIN_SAFE_INTEGER)
            continue;
        [arr[index], arr[maxIndex]] = [arr[maxIndex], arr[index]];
        maxIndex = index;
        for (let j = 0; j < arr.length; j++) {
            if ((arr[j] & (1 << i)) && j !== maxIndex) {
                arr[j] ^= maxElement;
            }
        }
        index++;
    }
    let ans = 0;
    for (let num of arr) {
        ans ^= num;
    }
    return ans;
}

function findMaximumXOR(nums) {
    return maxSubsetXOR(nums);
}

const set = [9, 8, 5];
console.log("Max subset XOR is " + findMaximumXOR(set));

Output
Max subset XOR is 13

Time Complexity : O(nxlogm)

How does this work? 

Let us first understand a simple case when all elements have Most Significant Bits (MSBs) at different positions. The task in this particular case is simple, we need to do XOR of all elements. 
If the input contains multiple numbers with the same MSB, then it’s not obvious which of them we should choose to include in the XOR. What we do is reduce the input list into an equivalent form that doesn’t contain more than one number of the same length. By taking the maximum element, we know that the MSB of this is going to be there in output. Let this MSB be at position i. If there are more elements with i’th set (or same MSB), we XOR them with the maximum number so that the i’th bit becomes 0 in them and the problem reduces to i-1 bits. 

Note: The above method is similar to Gaussian elimination. Consider a matrix of size 32 x n where 32 is number of bits and n is number of elements in array. 



Similar Reads

Find maximum subset sum formed by partitioning any subset of array into 2 partitions with equal sum
Given an array A containing N elements. Partition any subset of this array into two disjoint subsets such that both the subsets have an identical sum. Obtain the maximum sum that can be obtained after partitioning. Note: It is not necessary to partition the entire array, that is any element might not contribute to any of the partition. Examples: In
24 min read
Sum of maximum and minimum of Kth subset ordered by increasing subset sum
Given an integer N and a set of all non-negative powers of N as S = {N0, N1, N2, N3, ... }, arrange all non-empty subsets of S in increasing order of subset-sum. The task is to find the sum of the greatest and smallest elements of the Kth subset from that ordering. Examples: Input: N = 4, K = 3Output: 5Explanation: S = {1, 4, 16, 64, ...}.Therefore
7 min read
Split Array into K non-overlapping subset such that maximum among all subset sum is minimum
Given an array arr[] consisting of N integers and an integer K, the task is to split the given array into K non-overlapping subsets such that the maximum among the sum of all subsets is minimum. Examples: Input: arr[] = {1, 7, 9, 2, 12, 3, 3}, M = 3Output: 13Explanation:One possible way to split the array into 3 non-overlapping subsets is {arr[4],
7 min read
Maximum size of subset such that product of all subset elements is a factor of N
Given an integer N and an array arr[] having M integers, the task is to find the maximum size of the subset such that the product of all elements of the subset is a factor of N. Examples: Input: N = 12, arr[] = {2, 3, 4}Output: 2Explanation: The given array 5 subsets such that the product of all elements of the subset is a factor of 12. They are {2
6 min read
Find maximum sum of Subset which is multiple of M and XOR is 0
Given an array arr[] of size N, the task is to find the maximum sum of a subset of the array such that the sum is divisible by M and the Xor of the subsequence is 0. Examples: Input: A = {2, 3, 2, 5, 5}, M = 5Output: 10Explanation: maximum sum will be by selecting subset {5, 5} which is 10, also its xor 5 ^ 5 is zero and sum is divisible by 5. {2,
11 min read
Find a non empty subset in an array of N integers such that sum of elements of subset is divisible by N
Given an array of N integers, the task is to find a non-empty subset such that the sum of elements of the subset is divisible by N. Output any such subset with its size and the indices(1-based indexing) of elements in the original array if it exists. Prerequisites: Pigeonhole PrincipleExamples: Input: arr[] = { 2, 3, 7, 1, 9 } Output: 2 1 2 The req
8 min read
Count of subarrays in range [L, R] having XOR + 1 equal to XOR (XOR) 1 for M queries
Given an array, arr[] of N positive integers and M queries which consist of two integers [Li, Ri] where 1 ? Li ? Ri ? N. For each query, find the number of subarrays in range [Li, Ri] for which (X+1)=(X?1) where X denotes the xor of a subarray. Input: arr[]= {1, 2, 9, 8, 7}, queries[] = {{1, 5}, {3, 4}}Output: 6 1Explanation: Query 1: L=1, R=5: sub
12 min read
Given a set, find XOR of the XOR's of all subsets.
The question is to find XOR of the XOR's of all subsets. i.e if the set is {1,2,3}. All subsets are : [{1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}]. Find the XOR of each of the subset and then find the XOR of every subset result.We strongly recommend you to minimize your browser and try this yourself first.This is a very simple question to sol
5 min read
Largest possible Subset from an Array such that no element is K times any other element in the Subset
Given an array arr[] consisting of N distinct integers and an integer K, the task is to find the maximum size of a subset possible such that no element in the subset is K times any other element of the subset(i.e. no such pair {n, m} should be present in the subset such that either m = n * K or n = m * K). Examples: Input: arr[] = {2, 8, 6, 5, 3},
7 min read
Minimum Subset sum difference problem with Subset partitioning
Given a set of N integers with up to 40 elements, the task is to partition the set into two subsets of equal size (or the closest possible), such that the difference between the sums of the subsets is minimized. If the size of the set is odd, one subset will have one more element than the other. If the size is even, both subsets will have the same
13 min read
Article Tags :
Practice Tags :