VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-array-whose-elements-are-xor-of-adjacent-elements-in-given-array/

⇱ Find array whose elements are XOR of adjacent elements in given array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find array whose elements are XOR of adjacent elements in given array

Last Updated : 23 Jul, 2025

Given an array arr[] consisting of N integers, the task is to re-construct an array arr[] such that the values in arr[] are obtained by doing XOR of the adjacent elements in the array. Print the array elements.

Examples:

Input: arr[ ] = {10, 11, 1, 2, 3} 
Output: 1 10 3 1 3 
Explanation: 
At index 0, arr[0] xor arr[1] = 1
At index 1, arr[1] xor arr[2] = 10
At index 2, arr[2] xor arr[3] = 3
...
At index 4, No element is left So, it will remain as it is.
New Array will be {1, 10, 3, 1, 3}

Input: arr[ ] = {5, 9, 7, 6}
Output: 12 14 1 6 
Explanation: 
At index 0, arr[0] xor arr[1] = 12
At index 1, arr[1] xor arr[2] = 14
At index 2, arr[2] xor arr[3] = 1
At index 3, No element is left So, it will remain as it is.
New Array will be {12, 14, 1, 6}

Approach: The main idea to solve the given problem is to perform the following steps:

  1. Traverse the given array arr[] from the 0th index to (N - 2)th index.
  2. For each element arr[i] at ith position calculate arr[i] ^ arr[i+1] and store it at position i.

Below is the implementation of the above approach:


Output
1 10 3 1 3 


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


 

Comment
Article Tags: