VOOZH about

URL: https://www.geeksforgeeks.org/dsa/construct-a-sorted-array-such-that-setbit-in-bitwise-xor-of-any-pair-is-even/

⇱ Construct a sorted Array such that setbit in bitwise XOR of any pair is even - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Construct a sorted Array such that setbit in bitwise XOR of any pair is even

Last Updated : 23 Jul, 2025

Given an integer N(1 ≤ N ≤ 500), Construct an integer arr[] of length N, such that it should follow all the given conditions below: 

  • Each element of arr[] should be distinct.
  • Binary representation of (arr[i]^arr[j]) should contain even number of set bits for all ( 1≤i≤N ) and ( i≠j ).
  • All the elements in arr[] should be in sorted order.
  • Ai > 0 for all (1 ≤ i ≤ N).

Examples:

Input: N = 2
Output: {10, 15}
Explanation: It can be verified that all elements of arr[] 
in each output are distinct and in sorted order and 
all the possible pairs of arr[] fulfill the condition mentioned in problem statement..

Input: N = 3
Output: {3, 5, 12}

Approach: To solve the problem follow the below observation:

It can be observe from outputs that arr[] contains only elements having even parity of set bits in their binary representation. If we try to get some such type of elements under range 1 to 10 using a brute-force code we will get a mathematical series as { 3, 5, 6, 9}. 

This series is called "Evil Number" series and related to Number theory. This series follows all the given conditions of the problem. Therefore, This problem can be solve by printing first N terms of Evil Number series(Excluding 0, As Arr[i] should be greater than zero).

Follow the steps to solve the problem:

  • Print the first N terms of Evil number Series or First N integers greater than zero having even parity of set bits.

Below is the implementation for the above approach:


Output
3 5 6 9 10 12 15 17 18 20 

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

Comment
Article Tags: