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]

Try It Yourself
redirect icon

[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
C++
#include <bits/stdc++.h>
using namespace std;

// Function to return required list
// after performing all the queries
vector<int> constructList(vector<vector<int>> &queries)
{
    // Initially list contains only 0
    vector<int> s = {0};

    // Process each query one by one
    for (int i = 0; i < queries.size(); i++)
    {
        int type = queries[i][0];
        int x = queries[i][1];

        // Query type 0: Insert x
        if (type == 0)
        {
            s.push_back(x);
        }
        
        // Query type 1: Apply XOR to all elements
        else
        {
            for (int j = 0; j < s.size(); j++)
            {
                s[j] = s[j] ^ x;
            }
        }
    }

    // Sort the final list
    sort(s.begin(), s.end());

    return s;
}

// Driver code
int main()
{
    vector<vector<int>> queries = {
        {0, 6}, {0, 3}, {0, 2}, {1, 4}, {1, 5}
    };

    vector<int> ans = constructList(queries);

    for (int x : ans)
        cout << x << " ";

    return 0;
}
Java
import java.util.*;

class GFG {

    // Function to return required list
    // after performing all the queries
    static ArrayList<Integer> constructList(int[][] queries)
    {
        // Initially list contains only 0
        ArrayList<Integer> ans = new ArrayList<>();
        ans.add(0);

        // Process each query one by one
        for (int i = 0; i < queries.length; i++)
        {
            int type = queries[i][0];
            int x = queries[i][1];

            // Query type 0: Insert x
            if (type == 0)
            {
                ans.add(x);
            }
            // Query type 1: Apply XOR to all elements
            else
            {
                for (int j = 0; j < ans.size(); j++)
                {
                    ans.set(j, ans.get(j) ^ x);
                }
            }
        }

        // Sort the final list
        Collections.sort(ans);

        return ans;
    }

    public static void main(String[] args)
    {
        int[][] queries = {
            {0, 6}, {0, 3}, {0, 2}, {1, 4}, {1, 5}
        };

        ArrayList<Integer> ans = constructList(queries);

        for (int x : ans)
            System.out.print(x + " ");
    }
}
Python
# Function to return required list
# after performing all the queries
def constructList(queries):

    # Initially list contains only 0
    s = [0]

    # Process each query one by one
    for i in range(len(queries)):
        type_, x = queries[i]

        # Query type 0: Insert x
        if type_ == 0:
            s.append(x)
        # Query type 1: Apply XOR to all elements
        else:
            for j in range(len(s)):
                s[j] = s[j] ^ x

    # Sort the final list
    s.sort()

    return s


# Driver code
queries = [
    [0, 6], [0, 3], [0, 2], [1, 4], [1, 5]
]

ans = constructList(queries)
print(*ans)
C#
using System;
using System.Collections.Generic;

class GFG {

    // Function to return required list
    // after performing all the queries
    static List<int> constructList(int[,] queries)
    {
        // Initially list contains only 0
        List<int> ans = new List<int>();
        ans.Add(0);

        int n = queries.GetLength(0);

        // Process each query one by one
        for (int i = 0; i < n; i++)
        {
            int type = queries[i, 0];
            int x = queries[i, 1];

            // Query type 0: Insert x
            if (type == 0)
            {
                ans.Add(x);
            }
            // Query type 1: Apply XOR to all elements
            else
            {
                for (int j = 0; j < ans.Count; j++)
                {
                    ans[j] = ans[j] ^ x;
                }
            }
        }

        // Sort the final list
        ans.Sort();

        return ans;
    }

    // Driver code
    public static void Main()
    {
        int[,] queries = {
            {0, 6}, {0, 3}, {0, 2}, {1, 4}, {1, 5}
        };

        List<int> ans = constructList(queries);

        foreach (int x in ans)
            Console.Write(x + " ");
    }
}
JavaScript
// Function to return required list
// after performing all the queries
function constructList(queries)
{
    // Initially list contains only 0
    let s = [0];

    // Process each query one by one
    for (let i = 0; i < queries.length; i++)
    {
        let type = queries[i][0];
        let x = queries[i][1];

        // Query type 0: Insert x
        if (type === 0)
        {
            s.push(x);
        }
        // Query type 1: Apply XOR to all elements
        else
        {
            for (let j = 0; j < s.length; j++)
            {
                s[j] = s[j] ^ x;
            }
        }
    }

    // Sort the final list
    s.sort((a, b) => a - b);

    return s;
}

// Driver code
let queries = [
    [0, 6], [0, 3], [0, 2], [1, 4], [1, 5]
];

let ans = constructList(queries);
console.log(ans.join(" "));

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
C++
#include <bits/stdc++.h>
using namespace std;

// Function to return required list
// after performing all the queries
vector<int> constructList(vector<vector<int>> &queries)
{
    // Store cumulative Bitwise XOR
    int xr = 0;

    // Initialize final list to return
    vector<int> ans;

    int n = queries.size();

    // Perform each query
    for (int i = n - 1; i >= 0; i--) 
    {
        if (queries[i][0] == 0)
            ans.push_back(queries[i][1] ^ xr);
        else
            xr ^= queries[i][1];
    }

    // The initial value of 0
    ans.push_back(xr);

    // Sort the list
    sort(ans.begin(), ans.end());

    // Return final list
    return ans;
}

int main()
{
    vector<vector<int>> queries = {
        {0, 6}, {0, 3}, {0, 2}, {1, 4}, {1, 5}
    };
    vector<int> ans = constructList(queries);
    for (int x : ans)
        cout << x << " ";
    return 0;
}
Java
import java.util.*;

class GFG {

    // Function to return required list
    // after performing all the queries
    static ArrayList<Integer> constructList(int[][] queries)
    {
        // Store cumulative Bitwise XOR
        int xr = 0;

        // Initialize final list to return
        ArrayList<Integer> ans = new ArrayList<>();

        int n = queries.length;

        // Perform each query
        for (int i = n - 1; i >= 0; i--) 
        {
            if (queries[i][0] == 0)
                ans.add(queries[i][1] ^ xr);
            else
                xr ^= queries[i][1];
        }

        // The initial value of 0
        ans.add(xr);

        // Sort the list
        Collections.sort(ans);
        // Return final list
        return ans;
    }

    public static void main(String[] args)
    {
        int[][] queries = {
            {0, 6}, {0, 3}, {0, 2}, {1, 4}, {1, 5}
        };
        int[] ans = constructList(queries);

        for (int x : ans)
            System.out.print(x + " ");
    }
}
Python
# Function to return required list
# after performing all the queries
def constructList(queries):

    # Store cumulative Bitwise XOR
    xr = 0

    # Initialize final list to return
    ans = []

    n = len(queries)

    # Perform each query
    for i in range(n - 1, -1, -1):
        if queries[i][0] == 0:
            ans.append(queries[i][1] ^ xr)
        else:
            xr ^= queries[i][1]

    # The initial value of 0
    ans.append(xr)
    
    ans.sort()
    return ans

if __name__ == "__main__":
queries = [
    [0, 6], [0, 3], [0, 2], [1, 4], [1, 5]
]

ans = constructList(queries)
print(*ans)
C#
using System;
using System.Collections.Generic;

class GFG {

    // Function to return required list
    // after performing all the queries
    static List<int> constructList(int[,] queries)
    {
        // Store cumulative Bitwise XOR
        int xr = 0;

        // Initialize final list to return
        List<int> ans = new List<int>();

        int n = queries.GetLength(0);

        // Perform each query
        for (int i = n - 1; i >= 0; i--) 
        {
            if (queries[i, 0] == 0)
                ans.Add(queries[i, 1] ^ xr);
            else
                xr ^= queries[i, 1];
        }

        // The initial value of 0
        ans.Add(xr);

        ans.Sort();
        return ans;
    }

    public static void Main()
    {
        int[,] queries = {
            {0, 6}, {0, 3}, {0, 2}, {1, 4}, {1, 5}
        };

        List<int> ans = constructList(queries);

        foreach (int x in ans)
            Console.Write(x + " ");
    }
}
JavaScript
// Function to return required list
// after performing all the queries
function constructList(queries)
{
    // Store cumulative Bitwise XOR
    let xr = 0;

    // Initialize final list to return
    let ans = [];

    let n = queries.length;

    // Perform each query
    for (let i = n - 1; i >= 0; i--) 
    {
        if (queries[i][0] === 0)
            ans.push(queries[i][1] ^ xr);
        else
            xr ^= queries[i][1];
    }

    // The initial value of 0
    ans.push(xr);

    ans.sort((a, b) => a - b);
    return ans;
}

// Driver Code
let queries = [
    [0, 6], [0, 3], [0, 2], [1, 4], [1, 5]
];

let ans = constructList(queries);
console.log(ans.join(" "));

Output
1 2 3 7 
Comment