githubEdit

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 Linkarrow-up-right

🧩 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

  1. 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

  2. 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

  3. 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.

  4. 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++)

chevron-right⚑ View Alternative Approaches with Code and Analysishashtag

πŸ“Š 2️⃣ Lookup Table Approach

πŸ’‘ Algorithm Steps:

  1. Precompute which element to exclude for each n%4 case in a lookup array.

  2. Calculate n % 4 to determine the pattern.

  3. Iterate from 1 to n and exclude the predetermined element.

  4. Build result in single pass using exclusion logic.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n) - Single pass with conditional check

  • Auxiliary Space: πŸ’Ύ O(1) - Fixed size lookup array

βœ… Why This Approach?

  • Minimal branching with lookup table

  • Cache-friendly pattern access

  • Elegant solution using precomputation

πŸ“Š 3️⃣ Range Building with STL Approach

πŸ’‘ Algorithm Steps:

  1. Determine start and end points based on n%4 value.

  2. Use STL iota function to efficiently fill ranges.

  3. Handle special case for n%4=1 separately with exclusion.

  4. Optimize memory allocation by pre-sizing the result vector.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n) - Linear range generation

  • Auxiliary Space: πŸ’Ύ O(1) - Constant space for computation

βœ… Why This Approach?

  • Uses STL algorithms for efficiency

  • Minimal conditional branching

  • Optimized memory allocation with resize

πŸ†š πŸ” Comparison of Approaches

πŸš€ Approach

⏱️ Time Complexity

πŸ’Ύ Space Complexity

βœ… Pros

⚠️ Cons

🎯 Modulo Pattern

🟒 O(n)

🟒 O(1)

πŸš€ Most compact code

πŸ”§ Requires pattern knowledge

πŸ“Š Lookup Table

🟒 O(n)

🟒 O(1)

🎯 Minimal branching

πŸ”§ Extra array storage

⚑ Range Building

🟒 O(n)

🟒 O(1)

⭐ STL optimization

πŸ”§ More verbose code

πŸ† Best Choice Recommendation

🎯 Scenario

πŸŽ–οΈ Recommended Approach

πŸ”₯ Performance Rating

πŸ… Optimal performance needed

πŸ₯‡ Modulo Pattern

β˜…β˜…β˜…β˜…β˜…

πŸ”§ Code readability

πŸ₯ˆ Lookup Table

β˜…β˜…β˜…β˜…β˜†

🎯 Interview/Competitive

πŸ… Modulo Pattern

β˜…β˜…β˜…β˜…β˜…

β˜• Code (Java)

🐍 Code (Python)

🧠 Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: πŸ“¬ Any Questions?arrow-up-right. Let's make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Visitor counter

Last updated