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:
Split array into three continuous subarrays with negative, 0 and positive product respectively
Next article icon

Split an array into subarrays with maximum Bitwise XOR of their respective Bitwise OR values

Last Updated : 08 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of N integers, the task is to find the maximum Bitwise XOR of Bitwise OR of every subarray after splitting the array into subarrays(possible zero subarrays).

Examples:

Input: arr[] = {1, 5, 7}, N = 3
Output: 7
Explanation:
The given array can be expressed as the 1 subarray i.e., {1, 5, 7}.
The Bitwise XOR of the Bitwise OR of the formed subarray is 7, which is the maximum possible value.

Input: arr[] = {1, 2}, N = 2
Output: 3

Naive Approach: The simplest approach to solve the given above problem is to generate all possible combinations of breaking of subarrays using recursion and at each recursive call, find the maximum value of Bitwise XOR of Bitwise OR of all possible formed subarray and print it.

Below is the implementation of the above approach:

C++
// C++ program for the above approach  #include <bits/stdc++.h> using namespace std;  // Recursive function to find all the // possible breaking of arrays into // subarrays and find the maximum // Bitwise XOR int maxXORUtil(int arr[], int N,                int xrr, int orr) {     // If the value of N is 0     if (N == 0)         return xrr ^ orr;      // Stores the result if the new     // group is formed with the first     // element as arr[i]     int x = maxXORUtil(arr, N - 1,                        xrr ^ orr,                        arr[N - 1]);      // Stores if the result if the     // arr[i] is included in the     // last group     int y = maxXORUtil(arr, N - 1,                        xrr, orr | arr[N - 1]);      // Returns the maximum of     // x and y     return max(x, y); }  // Function to find the maximum possible // Bitwise XOR of all possible values of // the array after breaking the arrays // into subarrays int maximumXOR(int arr[], int N) {     // Return the result     return maxXORUtil(arr, N, 0, 0); }  // Driver Code int main() {     int arr[] = { 1, 5, 7 };     int N = sizeof(arr) / sizeof(arr[0]);     cout << maximumXOR(arr, N);      return 0; } 
Java
// Java program for the above approach public class GFG{      // Recursive function to find all the     // possible breaking of arrays into     // subarrays and find the maximum     // Bitwise XOR     static int maxXORUtil(int arr[], int N, int xrr,                           int orr)     {                // If the value of N is 0         if (N == 0)             return xrr ^ orr;          // Stores the result if the new         // group is formed with the first         // element as arr[i]         int x             = maxXORUtil(arr, N - 1, xrr ^ orr, arr[N - 1]);          // Stores if the result if the         // arr[i] is included in the         // last group         int y             = maxXORUtil(arr, N - 1, xrr, orr | arr[N - 1]);          // Returns the maximum of         // x and y         return Math.max(x, y);     }      // Function to find the maximum possible     // Bitwise XOR of all possible values of     // the array after breaking the arrays     // into subarrays     static int maximumXOR(int arr[], int N)     {                // Return the result         return maxXORUtil(arr, N, 0, 0);     }      // Driver code     public static void main(String[] args)     {         int arr[] = { 1, 5, 7 };         int N = arr.length;         System.out.println(maximumXOR(arr, N));     } }  // This code is contributed by abhinavjain194 
Python3
# C++ program for the above approach # Recursive function to find all the # possible breaking of arrays o # subarrays and find the maximum # Bitwise XOR def maxXORUtil(arr, N, xrr, orr):      # If the value of N is 0     if (N == 0):         return xrr ^ orr      # Stores the result if the new     # group is formed with the first     # element as arr[i]     x = maxXORUtil(arr, N - 1, xrr ^ orr, arr[N - 1])      # Stores if the result if the     # arr[i] is included in the     # last group     y = maxXORUtil(arr, N - 1, xrr, orr | arr[N - 1])      # Returns the maximum of     # x and y     return max(x, y)   # Function to find the maximum possible # Bitwise XOR of all possible values of # the array after breaking the arrays # o subarrays def maximumXOR(arr,  N):      # Return the result     return maxXORUtil(arr, N, 0, 0)   # Driver Code arr =  1, 5, 7  N = len(arr) print(maximumXOR(arr, N))  # this code is contributed by shivanisinghss2110 
C#
// C# program for the above approach using System; class GFG {      // Recursive function to find all the     // possible breaking of arrays into     // subarrays and find the maximum     // Bitwise XOR     static int maxXORUtil(int[] arr, int N, int xrr,                           int orr)     {                // If the value of N is 0         if (N == 0)             return xrr ^ orr;          // Stores the result if the new         // group is formed with the first         // element as arr[i]         int x             = maxXORUtil(arr, N - 1, xrr ^ orr, arr[N - 1]);          // Stores if the result if the         // arr[i] is included in the         // last group         int y             = maxXORUtil(arr, N - 1, xrr, orr | arr[N - 1]);          // Returns the maximum of         // x and y         return Math.Max(x, y);     }      // Function to find the maximum possible     // Bitwise XOR of all possible values of     // the array after breaking the arrays     // into subarrays     static int maximumXOR(int[] arr, int N)     {                // Return the result         return maxXORUtil(arr, N, 0, 0);     }   // Driver code static void Main() {     int[] arr = { 1, 5, 7 };         int N = arr.Length;         Console.Write(maximumXOR(arr, N)); } }  // This code is contributed by sanjoy_62. 
JavaScript
<script> // Javascript program for the above approach  // Recursive function to find all the // possible breaking of arrays into // subarrays and find the maximum // Bitwise XOR function maxXORUtil(arr,N,xrr,orr) {      // If the value of N is 0         if (N == 0)             return xrr ^ orr;           // Stores the result if the new         // group is formed with the first         // element as arr[i]         let x             = maxXORUtil(arr, N - 1, xrr ^ orr, arr[N - 1]);           // Stores if the result if the         // arr[i] is included in the         // last group         let y             = maxXORUtil(arr, N - 1, xrr, orr | arr[N - 1]);           // Returns the maximum of         // x and y         return Math.max(x, y); }  // Function to find the maximum possible // Bitwise XOR of all possible values of // the array after breaking the arrays // into subarrays function maximumXOR(arr,N) {      // Return the result     return maxXORUtil(arr, N, 0, 0); }  // Driver code let arr=[1, 5, 7 ]; let N = arr.length; document.write(maximumXOR(arr, N));  // This code is contributed by unknown2108 </script> 

Output: 
7

 

Time Complexity: O(2N)
Auxiliary Space: O(1)

Efficient Approach: The above approach can be optimized by observing the relationship between the Bitwise XOR and Bitwise OR  i.e., the value of Bitwise XOR of N elements is at most the value of Bitwise OR of N elements. Therefore, to find the maximum value, the idea is to split the group into only 1 group of the whole array.

Hence, print the value of Bitwise OR of the array elements arr[] as the resultant maximum value.

Below is the implementation of the above approach:

C++
// C++ program for the above approach  #include <bits/stdc++.h> using namespace std;  // Function to find the bitwise OR of // array elements int MaxXOR(int arr[], int N) {     // Stores the resultant maximum     // value of Bitwise XOR     int res = 0;      // Traverse the array arr[]     for (int i = 0; i < N; i++) {         res |= arr[i];     }      // Return the maximum value res     return res; }  // Driver Code int main() {     int arr[] = { 1, 5, 7 };     int N = sizeof(arr) / sizeof(arr[0]);     cout << MaxXOR(arr, N);      return 0; } 
Java
// Java program for the above approach import java.lang.*; import java.util.*;  class GFG{      // Function to find the bitwise OR of // array elements static int MaxXOR(int arr[], int N) {          // Stores the resultant maximum     // value of Bitwise XOR     int res = 0;      // Traverse the array arr[]     for(int i = 0; i < N; i++)      {         res |= arr[i];     }          // Return the maximum value res     return res; }  public static void main(String[] args) {      int arr[] = { 1, 5, 7 };     int N = arr.length;          System.out.println(MaxXOR(arr, N)); } }  // This code is contributed by offbeat 
Python3
# Python3 program for the above approach  # Function to find the bitwise OR of # array elements def MaxXOR(arr, N):          # Stores the resultant maximum     # value of Bitwise XOR     res = 0      # Traverse the array arr[]     for i in range(N):         res |= arr[i]      # Return the maximum value res     return res  # Driver Code if __name__ == '__main__':          arr = [ 1, 5, 7 ]     N = len(arr)          print (MaxXOR(arr, N))  # This code is contributed by mohit kumar 29 
C#
// C# program for the above approach using System;  class GFG {      // Function to find the bitwise OR of // array elements static int MaxXOR(int []arr, int N) {          // Stores the resultant maximum     // value of Bitwise XOR     int res = 0;      // Traverse the array arr[]     for(int i = 0; i < N; i++)      {         res |= arr[i];     }          // Return the maximum value res     return res; }  public static void Main(String[] args) {      int []arr = { 1, 5, 7 };     int N = arr.Length;          Console.Write(MaxXOR(arr, N)); } }  // This code is contributed by shivanisinghss2110 
JavaScript
<script>  // JavaScript program for the above approach  // Function to find the bitwise OR of // array elements function MaxXOR(arr, N) {          // Stores the resultant maximum     // value of Bitwise XOR     var res = 0;      // Traverse the array arr[]     for(var i = 0; i < N; i++)      {         res |= arr[i];     }          // Return the maximum value res     return res; }  // Driver code var arr = [ 1, 5, 7 ]; var N = arr.length;  document.write(MaxXOR(arr, N));  // This code is contributed by shivanisinghss2110  </script> 

Output: 
7

 

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


Next Article
Split array into three continuous subarrays with negative, 0 and positive product respectively
author
rj13to
Improve
Article Tags :
  • Bit Magic
  • Greedy
  • Mathematical
  • Competitive Programming
  • Recursion
  • DSA
  • Arrays
  • Bitwise-XOR
  • subarray
  • Bitwise-OR
  • partition
Practice Tags :
  • Arrays
  • Bit Magic
  • Greedy
  • Mathematical
  • Recursion

Similar Reads

  • Partition array into two subsets with minimum Bitwise XOR between their maximum and minimum
    Given an array arr[] of size N, the task is to split the array into two subsets such that the Bitwise XOR between the maximum of the first subset and minimum of the second subset is minimum. Examples: Input: arr[] = {3, 1, 2, 6, 4} Output: 1 Explanation: Splitting the given array in two subsets {1,
    5 min read
  • Split Array into maximum Subsets with same bitwise AND
    Given an array arr[] of size N, the task is to find the maximum number of subsets the array can be split such that the bitwise AND of the subsets is the same. Examples: Input: N = 4, arr[] = {1, 5, 2, 8}Output: 2Explanation:1st subset -> {1, 8}; bitwise AND = 0 2nd subset -> {2, 5}; bitwise AN
    10 min read
  • Find maximum product of Bitwise AND and Bitwise OR of K-size subarray
    Given an array arr[] containing N integers and an integer K, the task is to find the maximum value of the product of Bitwise AND and Bitwise OR of all elements of a K-sized subarray. Example: Input: arr[] = {1, 2, 3, 4}, K = 2Output: 6Explanation: Bitwise AND and Bitwise XOR of all K-sized subarrays
    9 min read
  • Split array into three continuous subarrays with negative, 0 and positive product respectively
    Given an array arr[] size N such that each array element is either -1, 0, or 1, the task is to check if is it possible to split the array into 3 contiguous subarrays such that the product of the first, second and third subarrays is negative, 0 and positive respectively. Examples: Input: arr[] = {-1,
    11 min read
  • Count pairs with bitwise XOR exceeding bitwise AND from a given array
    Given an array, arr[] of size N, the task is to count the number of pairs from the given array such that the bitwise AND(&) of each pair is less than its bitwise XOR(^). Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 8Explanation: Pairs that satisfy the given conditions are: (1 & 2) < (
    10 min read
  • Maximum sum of Bitwise XOR of elements with their respective positions in a permutation of size N
    Given a positive integer N, the task for any permutation of size N having elements over the range [0, N - 1], is to calculate the sum of Bitwise XOR of all elements with their respective position. For Example: For the permutation {3, 4, 2, 1, 0}, sum = (0^3 + 1^4 + 2^2 + 3^1 + 4^0) = 2. Examples: In
    7 min read
  • Find subsequences with maximum Bitwise AND and Bitwise OR
    Given an array of n elements. The task is to print the maximum sum by selecting two subsequences of the array (not necessarily different) such that the sum of bitwise AND of all elements of the first subsequence and bitwise OR of all the elements of the second subsequence is maximum. Examples: Input
    4 min read
  • Find all possible pairs with given Bitwise OR and Bitwise XOR values
    Given two positive integers A and B representing Bitwise XOR and Bitwise OR of two positive integers, the task is to find all possible pairs (x, y) such that x ^ y is equal to A and x | y is equal to B. Examples: Input: A = 5, B = 7Output:2 73 66 37 2Explanation:7( XOR )2 = 5 and 7( OR )2 = 73( XOR
    8 min read
  • Count ways to split array into three non-empty subarrays having equal Bitwise XOR values
    Given an array arr[] consisting of N non-negative integers, the task is to count the number of ways to split the array into three different non-empty subarrays such that Bitwise XOR of each subarray is equal. Examples: Input: arr[] = {7, 0, 5, 2, 7} Output: 2Explanation: All possible ways are:{{7},
    9 min read
  • Count of pairs with bitwise XOR value greater than its bitwise AND value
    Given an array arr that contains N positive Integers. Find the count of all possible pairs whose bitwise XOR value is greater than bitwise AND value Examples: Input : arr[]={ 12, 4, 15}Output: 2Explanation: 12 ^ 4 = 8, 12 & 4 = 4. so 12 ^ 4 > 12 & 4 4 ^ 15 = 11, 4 & 15 = 4. so 4 ^ 15
    4 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