28. Subset XOR
β GFG solution to the Subset XOR problem: find maximum size subset from 1 to n with XOR equal to n using mathematical XOR pattern recognition. π
The problem can be found at the following link: π Question Link
π§© Problem Description
Given a positive integer n, find a subset of numbers from 1 to n (inclusive), where each number can be used at most once, such that:
The XOR of all elements in the subset is exactly
n.The size of the subset is as large as possible.
If multiple such subsets exist, choose the lexicographically smallest one.
Lexicographical Order: A subset A[] is lexicographically smaller than subset B[] if at the first index where they differ, A[i] < B[i] (based on character ASCII/Unicode values). If all elements match but one subset ends earlier, the shorter subset is considered smaller.
π Examples
Example 1
Input: n = 4
Output: [1, 2, 3, 4]
Explanation: We choose all the elements from 1 to 4. Its XOR value is equal to n (1^2^3^4 = 4).
This is the maximum possible size of the subset.Example 2
Input: n = 3
Output: [1, 2]
Explanation: 1 ^ 2 = 3. This is the smallest lexicographical answer possible with maximum
size of subset i.e 2.π Constraints
$1 \le n \le 10^5$
β
My Approach
The optimal approach uses XOR mathematical properties to determine which element to exclude:
XOR Pattern Recognition
Mathematical Insight:
XOR of consecutive numbers from 1 to n follows a pattern based on n % 4.
Pattern:
n % 4 = 0: XOR(1 to n) = n
n % 4 = 1: XOR(1 to n) = 1
n % 4 = 2: XOR(1 to n) = n + 1
n % 4 = 3: XOR(1 to n) = 0
Exclusion Strategy:
To get XOR = n, we need to exclude specific element(s).
For n % 4 = 0: Include all (XOR already = n)
For n % 4 = 1: Exclude (n-1) to get XOR = n
For n % 4 = 2: Exclude 1 to get XOR = n
For n % 4 = 3: Exclude n to get XOR = n
Implementation:
Calculate n & 3 (equivalent to n % 4) for efficiency.
Determine start and end range based on pattern.
Build result array excluding the identified element.
Lexicographical Order:
Since we're building from smallest to largest and excluding specific elements, the result is naturally lexicographically smallest.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), as we iterate through the range from 1 to n once to build the result array.
Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for variables (excluding the output array which is required for the result).
π§βπ» Code (C++)
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated