VOOZH about

URL: https://www.geeksforgeeks.org/dsa/construct-a-list-using-the-given-q-xor-queries/

⇱ Construct a List using XOR queries - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Construct a List using XOR queries

Last Updated : 15 Jun, 2026

 Given a list s that initially contains a single value 0. Below are the q queries of the following types:

  • 0 X: Insert X in the list
  • 1 X: For every element A in S, replace it by A XOR X.

The task is to print all the element in the list in increasing order after performing the given Q queries.

Examples:

Input: queries[][] = [{0, 6}, {0, 3}, {0, 2}, {1, 4}, {1, 5} ]
Output: 1 2 3 7
Explanation: [0] (initial value) , [0 6] (add 6 to list), [0 6 3] (add 3 to list), [0 6 3 2] (add 2 to list), [4 2 7 6] (XOR each element by 4), [1 7 2 3] (XOR each element by 5), Thus sorted order after performing queries is [1 2 3 7]

Input: queries[][]= [{0, 2}, {1, 3}, {0, 5} ]
Output: 1 3 5
Explanation:  [0] (initial value), [0 2] (add 2 to list). [3 1] (XOR each element by 3), [3 1 5] (add 5 to list), Thus sorted order after performing queries is [1 3 5]

[Naive Approach] Using Direct Simulation – O(n²) Time and O(n) Space

The idea is to sequentially process each query exactly as described.

  • Initialize the list with 0 as the starting element
  • Traverse each query and insert elements for type 0 queries
  • For type 1 queries, apply XOR to every element in the list
  • After processing all queries, sort the list and return it

Output
1 2 3 7 

[Optimal Approach] Using Reverse Processing + XOR – O(n log n) Time and O(n) Space

The idea is to process the queries from right to left because type-1 queries (XOR updates) affect all previously inserted elements. Instead of updating every element repeatedly, we maintain a cumulative XOR value. While traversing backward, whenever we encounter an insertion query, we apply the current cumulative XOR to it and store the result.

  • Traverse the queries from right to left while maintaining a cumulative XOR value
  • If the query is type 1, update the cumulative XOR
  • If the query is type 0, insert the value after applying current XOR
  • Add the final cumulative XOR as the initial value and sort the result

Output
1 2 3 7 
Comment