Skip to main content

Command Palette

Search for a command to run...

Count Triplets That Can Form Two Arrays of Equal XOR

Published
2 min read
Count Triplets That Can Form Two Arrays of Equal XOR
G

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.

I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.

Given an array of integers arr.

We want to select three indices i, j and k where (0 <= i < j <= k < arr.length).

Let's define a and b as follows:

  • a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]

  • b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]

Note that ^ denotes the bitwise-xor operation.

Return the number of triplets (i, j and k) Where a == b.

LeetCode Problem - 1442

class Solution {
    public int countTriplets(int[] arr) {
        int length = arr.length; // Get the length of the input array
        int answer = 0; // Initialize a counter to keep track of the number of valid triplets

        // Loop through each possible starting point i
        for(int i = 0; i < length; i++) {
            int a = 0; // Initialize a variable to store the XOR of elements from i to j-1

            // Loop through each possible middle point j, starting from i+1
            for(int j = i + 1; j < length; j++) {
                a ^= arr[j - 1]; // Update the XOR value a by XORing with the element at j-1
                int b = 0; // Initialize a variable to store the XOR of elements from j to k

                // Loop through each possible end point k, starting from j
                for(int k = j; k < length; k++) {
                    b ^= arr[k]; // Update the XOR value b by XORing with the element at k
                    if(a == b) { // If a and b are equal, it means the condition is satisfied
                        answer++; // Increment the counter for valid triplets
                    }
                }
            }
        }

        return answer; // Return the total count of valid triplets
    }
}

More from this blog

S

Software and Performance Testing Insights

462 posts

Results-Driven Agile QA Specialist | Expert in Mobile & Web Testing | Proficient in Test Planning, Execution, and Root Cause Analysis.