Number of Ways Where Square of Number Is Equal to Product of Two Numbers - Problem
Given two arrays of integers nums1 and nums2, return the number of triplets formed (type 1 and type 2) under the following rules:
Type 1: Triplet (i, j, k) if nums1[i]² == nums2[j] * nums2[k] where 0 <= i < nums1.length and 0 <= j < k < nums2.length.
Type 2: Triplet (i, j, k) if nums2[i]² == nums1[j] * nums1[k] where 0 <= i < nums2.length and 0 <= j < k < nums1.length.
Input & Output
Example 1 — Basic Case
$
Input:
nums1 = [7,4], nums2 = [5,2,8,9]
›
Output:
1
💡 Note:
Type 1: 7² = 49, but no pairs in nums2 multiply to 49. 4² = 16, but no pairs multiply to 16. Type 2: 5² = 25, no pairs in nums1 multiply to 25. 2² = 4, no pairs multiply to 4. 8² = 64, 7×9=63≠64. 9² = 81, no pairs multiply to 81. Wait, let me recalculate: 4² = 16, and 2×8 = 16, so we have triplet (1,1,2). Total = 1.
Example 2 — Multiple Matches
$
Input:
nums1 = [1,1], nums2 = [1,1,1]
›
Output:
9
💡 Note:
Type 1: 1² = 1. Pairs in nums2 that multiply to 1: (0,1), (0,2), (1,2) = 3 pairs. Each nums1 element (2 total) can form triplets: 2×3 = 6. Type 2: 1² = 1. Pairs in nums1 that multiply to 1: (0,1) = 1 pair. Each nums2 element (3 total): 3×1 = 3. Total = 6 + 3 = 9.
Example 3 — No Matches
$
Input:
nums1 = [7,7,8,3], nums2 = [1,2,9,7]
›
Output:
2
💡 Note:
Type 1: 7² = 49, 7×7 = 49 ✓ (but 7 appears once in nums2). 8² = 64, no valid pairs. 3² = 9, 1×9 = 9 ✓. Type 2: Check each nums2 element squared against nums1 pairs. After calculation, we get 2 valid triplets total.
Constraints
- 1 ≤ nums1.length, nums2.length ≤ 1000
- -105 ≤ nums1[i], nums2[i] ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input Arrays
Two integer arrays with different elements
2
Find Matches
Look for squares that equal products of pairs
3
Count Triplets
Total number of valid triplet combinations
Key Takeaway
🎯 Key Insight: Use frequency maps to efficiently count combinations instead of checking all possible triplets
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code