VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-mex-of-given-xor-sequence/

⇱ Find the MEX of given XOR sequence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the MEX of given XOR sequence

Last Updated : 23 Jul, 2025

Given two integers N and M. The task is to determine the MEX (Minimal Excluded) of the following sequence: N ^ 0, N ^ 1, N ^ 2... N ^ M, where ^ is the Bitwise XOR operator.

Examples:

Input: N = 4, M = 2
Output: 0
Explanation: The sequence will be: 4 ^ 0, 4 ^ 1, 4 ^ 2 = 4, 5, 6. So, the MEX will be 0.

Input: N = 5, M = 7
Output:
Explanation: The sequence will be: 5 ^ 0, 5 ^ 1, 5 ^ 2, 5 ^ 3, 5 ^ 4, 5 ^ 5, 5 ^ 6, 5 ^ 7 = 5, 4, 7, 6, 1, 0, 3, 2. So, the MEX will be 8.

Approach: To solve the problem, follow the below idea:

The problem is to find whether a number K is present in the sequence N ^ 0, N ^ 1, N ^ 2 ... N ^ M. If K is present in the sequence, then there must be an integer X (X <= M), such that N ^ X = K. We can also write N ^ X = K as N ^ K = X. So, now if we want to find whether a number K is present in the sequence N ^ 0, N ^ 1, N ^ 2 ... N ^ M, we can simply check N ^ K <= M.

Now, the problem has been reduced to find the smallest number K such that N ^ K >= M + 1. For simplicity, let's consider P=M + 1. So, we need to find the smallest K such that N ^ K >= P.

We can build P bit by bit starting from the highest bit and moving towards the lowest bit.

  • If Pi = 1 and Ni = 1, then set Ki = 0, as Ni ^ 0 >= Pi.
  • If Pi = 0 and Ni = 0, then set Ki = 0, as Ni ^ 0 >= Pi.
  • If Pi = 0 and Ni = 1, then set Ki = 0, we can break here by setting the remaining bits of K off as no matter what the remaining bits of N are N ^ K > P.
  • If Pi = 0 and Ni = 1, then set Ki = 1 as we want to have Ni ^ 1 >= Pi.

Step-by-step algorithm:

  • Run a loop from i = 31 to 0 to iterate from Most Significant Bit to Least Significant Bit.
  • Start building K bit by bit according to the above conditions.
  • Finally return K as the final answer.

Below is the implementation of the approach:


Output
8

Time Complexity: O(log (max(N, M))), where N and M are given as input.
Auxiliary Space: O(1)

Comment