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
  • Practice Bitwise Algorithms
  • MCQs on Bitwise Algorithms
  • Tutorial on Biwise Algorithms
  • Binary Representation
  • Bitwise Operators
  • Bit Swapping
  • Bit Manipulation
  • Count Set bits
  • Setting a Bit
  • Clear a Bit
  • Toggling a Bit
  • Left & Right Shift
  • Gray Code
  • Checking Power of 2
  • Important Tactics
  • Bit Manipulation for CP
  • Fast Exponentiation
Open In App
Next Article:
Replace every element of the array with BitWise XOR of all other
Next article icon

Generate an Array with XOR of even length prefix as 0 or 1

Last Updated : 28 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer N, the task is to construct an array of N distinct elements (arr[i] ≤ N+1) such that the bitwise XOR of every prefix having an even length is either 0 or 1.

Examples:

Input: N = 5
Output = 2 3 4 5 6
Explanation: XOR from arr[1] to arr[2] = XOR(2, 3) = 1
XOR from arr[1] to arr[4] = XOR(2, 3, 4, 5) = 0

Input: N = 2
Output: 2 3

 

Approach: The approach to the problem is based on the following observation

2*k XOR (2*k + 1) = 1 where k ∈ [1, ∞)

The above equation can be proved as shown below:

  • 2k is an even number whose LSB is always zero. Adding 1 in this (resulting in 2k+1) will change only one bit of the number (LSB will get transformed from zero to one).
  • Now, 2k and 2k+1 differ in only one bit at the 0th position. So, 2*k XOR 2*k+1 = 1.

So, if started from k = 1, and consecutive k's are considered the conditions will be satisfied and all the prefixes with even length will have XOR as 1 or 0(when prefix length is divisible by 4. because XOR of even number of 1 will be 0)

Follow the steps mentioned below to implement the above observation:

  • Declare a vector to store the answer.
  • Run a loop from  i = 1 to n/2 and in each iteration:
    •  store two values in the vector:
      • First Value = 2*i.
      • Second Value = 2*i + 1.
  • If N is odd, insert the last element (N + 1) in the vector because using the above method only an even number of elements can be inserted.
  • Return the vector as this is the required array.

Below is the implementation of the above approach.

C++
// C++ code to implement the approach  #include <bits/stdc++.h> using namespace std;  // Function to construct the array vector<int> construct_arr(int n) {     vector<int> ans;     for (int i = 1; i <= n / 2; i++) {         ans.push_back(2 * i);         ans.push_back(2 * i + 1);     }      // If n is odd insert the last element     if ((n % 2) != 0) {         ans.push_back(n + 1);     }     return ans; }  // Driver code int main() {     int N = 5;      // Function call     vector<int> ans = construct_arr(N);      // Print the resultant array     for (int i = 0; i < ans.size(); i++)         cout << ans[i] << " ";      return 0; } 
Java
/*package whatever //do not write package name here */ import java.io.*; import java.util.*;  class GFG  {    // Java program for the above approach    // Function to construct the array   static ArrayList<Integer> construct_arr(int n)   {     ArrayList<Integer> ans = new ArrayList<Integer>();     for (int i = 1; i <= n / 2; i++) {       ans.add(2*i);       ans.add(2*i+1);     }      // If n is odd insert the last element     if ((n % 2) != 0) {       ans.add(n + 1);     }     return ans;   }    // Driver Code   public static void main(String args[])   {     int N = 5;      // Function call     ArrayList<Integer> ans = construct_arr(N);      // Print the resultant array     for (int i = 0; i < ans.size(); i++)       System.out.print(ans.get(i) + " ");    } }  // This code is contributed by shinjanpatra. 
Python3
# python code to implement the approach  # Function to construct the array def construct_arr(n):      ans = []     for i in range(1, n//2+1):         ans.append(2 * i)         ans.append(2 * i + 1)      # If n is odd insert the last element     if ((n % 2) != 0):         ans.append(n + 1)      return ans   # Driver code if __name__ == "__main__":      N = 5      # Function call     ans = construct_arr(N)      # Print the resultant array     for i in range(0, len(ans)):         print(ans[i], end=" ")      # This code is contributed by rakeshsahni 
C#
// C# program for the above appraochh using System; using System.Collections.Generic;  class GFG {    // Function to construct the array   static List<int> construct_arr(int n)   {     List<int> ans = new List<int>();     for (int i = 1; i <= n / 2; i++) {       ans.Add(2 * i);       ans.Add(2 * i + 1);     }      // If n is odd insert the last element     if ((n % 2) != 0) {       ans.Add(n + 1);     }     return ans;   }    // Driver Code   public static void Main(string[] args)   {     int N = 5;      // Function call     List<int> ans = construct_arr(N);      // Print the resultant array     for (int i = 0; i < ans.Count; i++)       Console.Write(ans[i] + " ");   } }  // This code is contributed by phasing17 
JavaScript
<script>         // JavaScript code for the above approach          // Function to construct the array         function construct_arr(n) {             let ans = [];             for (let i = 1; i <= Math.floor(n / 2); i++) {                 ans.push(2 * i);                 ans.push(2 * i + 1);             }              // If n is odd insert the last element             if ((n % 2) != 0) {                 ans.push(n + 1);             }             return ans;         }          // Driver code          let N = 5;          // Function call         let ans = construct_arr(N);          // Print the resultant array         for (let i = 0; i < ans.length; i++)             document.write(ans[i] + " ")      // This code is contributed by Potta Lokesh     </script> 

Output
2 3 4 5 6 

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


Next Article
Replace every element of the array with BitWise XOR of all other
author
refertoyash
Improve
Article Tags :
  • Bit Magic
  • DSA
Practice Tags :
  • Bit Magic

Similar Reads

  • Generate all Binary Strings of length N with equal count of 0s and 1s
    Given an integer N, the task is to generate all the binary strings with equal 0s and 1s. If no strings are possible, print -1 Examples: Input: N = 2 Output: “01”, “10”Explanation: All possible binary strings of length 2 are: 01, 10, 11, 00. Out of these, only 2 have equal number of 0s and 1s Input:
    6 min read
  • XOR of every element of an Array with a given number K
    Given an array arr and a number K, find the new array formed by performing XOR of the corresponding element from the given array with the given number K.Examples: Input: arr[] = { 2, 4, 1, 3, 5 }, K = 5 Output: 7 1 4 6 0 Explanation: 2 XOR 5 = 7 4 XOR 5 = 1 1 XOR 5 = 4 3 XOR 5 = 6 5 XOR 5 = 0 Input:
    5 min read
  • Bitwise XOR of a submatrix of a matrix generated from a given array
    Given an array arr[] of length N, , a matrix of dimensions N * N was defined on the array arr[] where Mi, j = arri & arrj. Given four integers X, Y, S and T, the task is to find the Bitwise XOR of all the elements of the submatrix from top-left (X, Y) to bottom-right (S, T). Examples: Input: N =
    6 min read
  • Replace every element of the array with BitWise XOR of all other
    Given an array of integers. The task is to replace every element by the bitwise xor of all other elements of the array. Examples: Input: arr[] = { 2, 3, 3, 5, 5 } Output: 0 1 1 7 7 Bitwise Xor of 3, 3, 5, 5 = 0 Bitwise Xor of 2, 3, 5, 5 = 1 Bitwise Xor of 2, 3, 5, 5 = 1 Bitwise Xor of 2, 3, 3, 5 = 7
    5 min read
  • Generate permutation of [1, N] having bitwise XOR of adjacent differences as 0
    Given an integer N, the task is to generate a permutation from 1 to N such that the bitwise XOR of differences between adjacent elements is 0 i.e., | A[1]− A[2] | ^ | A[2]− A[3] | ^ . . . ^ | A[N −1] − A[N] | = 0, where |X - Y| represents absolute difference between X and Y. Examples: Input: N = 4Ou
    5 min read
  • Generate an N-length array having equal count and sum of elements of both parities
    Given an integer N (3 ≤ N ≤ 105), the task is to generate an array of N distinct positive elements such that the count and sum of elements of both parties i.e even and odd, are the same. If it is not possible to construct such an array, print -1. Examples: Input: N = 8 Output: 2, 4, 6, 8, 1, 3, 5, 1
    6 min read
  • XOR of all elements of array with set bits equal to K
    Given an array of integers and a number K. The task is to find the XOR of only those elements of the array whose total set bits are equal to K. Examples: Input : arr[] = {1, 22, 3, 10}, K=1 Output : 1 Elements with set bits equal to 1 is 1. So, XOR is also 1. Input : arr[] = {3, 4, 10, 5, 8}, K=2 Ou
    4 min read
  • Check if the XOR of an array of integers is Even or Odd
    Given an array arr containing integers of size N, the task is to check if the XOR of this array is even or odd Examples: Input: arr[] = { 2, 4, 7} Output: Odd Explanation: XOR of array = 2 ^ 4 ^ 7 = 1, which is odd Input: arr[] = { 3, 9, 12, 13, 15 } Output: Even Naive Solution: First find the XOR o
    5 min read
  • Create an array such that XOR of subarrays of length K is X
    Given three integers N, K and X, the task is to construct an array of length N, in which XOR of all elements of each contiguous sub-array of length K is X.Examples: Input: N = 5, K = 1, X = 4 Output: 4 4 4 4 4 Explanation: Each subarray of length 1 has Xor value equal to 4.Input: N = 5, K = 2, X = 4
    4 min read
  • XOR of array elements whose modular inverse with a given number exists
    Given an array arr[] of length N and a positive integer M, the task is to find the Bitwise XOR of all the array elements whose modular inverse with M exists. Examples: Input: arr[] = {1, 2, 3}, M = 4Output: 2Explanation:Initialize the value xor with 0:For element indexed at 0 i.e., 1, its mod invers
    7 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