3513. Number of Unique XOR Triplets I LeetCode Solution

In this guide, you will get 3513. Number of Unique XOR Triplets I LeetCode Solution with the best time and space complexity. The solution to Number of Unique XOR Triplets I problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Number of Unique XOR Triplets I solution in C++
  4. Number of Unique XOR Triplets I solution in Java
  5. Number of Unique XOR Triplets I solution in Python
  6. Additional Resources
3513. Number of Unique XOR Triplets I LeetCode Solution image

Problem Statement of Number of Unique XOR Triplets I

You are given an integer array nums of length n, where nums is a permutation of the numbers in the range [1, n].
A XOR triplet is defined as the XOR of three elements nums[i] XOR nums[j] XOR nums[k] where i <= j <= k.
Return the number of unique XOR triplet values from all possible triplets (i, j, k).

Example 1:

Input: nums = [1,2]
Output: 2
Explanation:
The possible XOR triplet values are:

(0, 0, 0) → 1 XOR 1 XOR 1 = 1
(0, 0, 1) → 1 XOR 1 XOR 2 = 2
(0, 1, 1) → 1 XOR 2 XOR 2 = 1
(1, 1, 1) → 2 XOR 2 XOR 2 = 2

The unique XOR values are {1, 2}, so the output is 2.

Example 2:

Input: nums = [3,1,2]
Output: 4
Explanation:
The possible XOR triplet values include:

(0, 0, 0) → 3 XOR 3 XOR 3 = 3
(0, 0, 1) → 3 XOR 3 XOR 1 = 1
(0, 0, 2) → 3 XOR 3 XOR 2 = 2
(0, 1, 2) → 3 XOR 1 XOR 2 = 0

The unique XOR values are {0, 1, 2, 3}, so the output is 4.

Constraints:

1 <= n == nums.length <= 105
1 <= nums[i] <= n
nums is a permutation of integers from 1 to n.

Complexity Analysis

  • Time Complexity: O(\log n)
  • Space Complexity: O(1)

3513. Number of Unique XOR Triplets I LeetCode Solution in C++

class Solution {
 public:
  int uniqueXorTriplets(vector<int>& nums) {
    const int n = nums.size();
    if (n < 3)
      return n;
    return 1 << (static_cast<int>(log2(n)) + 1);
  }
};
/* code provided by PROGIEZ */

3513. Number of Unique XOR Triplets I LeetCode Solution in Java

class Solution {
  public int uniqueXorTriplets(int[] nums) {
    final int n = nums.length;
    if (n < 3)
      return n;
    final int x = (int) (Math.log(n) / Math.log(2));
    return 1 << (x + 1);
  }
}
// code provided by PROGIEZ

3513. Number of Unique XOR Triplets I LeetCode Solution in Python

class Solution:
  def uniqueXorTriplets(self, nums: list[int]) -> int:
    n = len(nums)
    if n < 3:
      return n
    return 1 << (int(math.log2(n)) + 1)
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.