C++ Solution || Using Maps
Code\ncpp []\nclass Solution {\n    // Function to count the number of valid triplets where square of a number from `A`\n    // is equal to the product of two n
# Code\n```cpp []\nclass Solution {\n    // Function to count the number of valid triplets where square of a number from `A`\n    // is equal to the product of two numbers from `B`\n    int count(vector<int> &A, vector<int> &B) {\n        int ans = 0;\n        unordered_map<int, int> freqMap;\n\n        // Build a frequency map for elements in array `B`\n        for (int num : B) {\n            freqMap[num]++;\n        }\n\n        // For each element `a` in `A`, check if its square can be written\n        // as the product of two numbers from `B`\n        for (int a : A) {\n            long target = (long)a * a; // Square of `a` (use long to prevent overflow)\n            \n            // Check for each number `b` in `B` (using the frequency map)\n            for (auto &[b, count] : freqMap) {\n                // If the target is not divisible by `b`, skip this iteration\n                if (target % b != 0) continue;\n                \n                // Calculate the other factor needed to get the product as the target\n                int otherFactor = target / b;\n\n                // If `otherFactor` exists in the map\n                if (freqMap.count(otherFactor)) {\n                    // If `b` and `otherFactor` are the same, count the valid pairs (combination)\n                    if (b == otherFactor) {\n                        // Choose 2 from `count` occurrences of `b` (because b*b = target)\n                        ans += count * (count - 1);\n                    } else {\n                        // If `b` and `otherFactor` are different, count the valid pairs\n                        ans += count * freqMap[otherFactor];\n                    }\n                }\n            }\n        }\n        \n        // Each valid pair is counted twice, so divide the result by 2\n        return ans / 2;\n    }\n\npublic:\n    // Main function to find the total number of valid triplets\n    int numTriplets(vector<int>& A, vector<int>& B) {\n        // Count triplets for both `A` -> `B` and `B` -> `A`\n        return count(A, B) + count(B, A);\n    }\n};\n\n```
['C++']