#1577
Number of Ways Where Square of Number Is Equal to Product of Two Numbers
MediumArrayHash TableMathTwo PointersHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
By using frequency maps to count occurrences of squares, we can significantly reduce the number of operations needed to find valid triplets. This allows us to check conditions in constant time.
⚙️
Algorithm
3 steps- 1Step 1: Create a frequency map for the squares of elements in nums1 and nums2.
- 2Step 2: For each unique square from nums1, calculate how many pairs from nums2 can form that square using the frequency map.
- 3Step 3: Repeat the process for squares from nums2 and count pairs from nums1.
solution.py24 lines
1# Full working Python code
2
3def countTriplets(nums1, nums2):
4 from collections import Counter
5 count = 0
6 freq1 = Counter(num ** 2 for num in nums1)
7 freq2 = Counter(num ** 2 for num in nums2)
8
9 for square in freq1:
10 for j in range(len(nums2)):
11 for k in range(j + 1, len(nums2)):
12 if nums2[j] * nums2[k] == square:
13 count += freq1[square]
14
15 for square in freq2:
16 for j in range(len(nums1)):
17 for k in range(j + 1, len(nums1)):
18 if nums1[j] * nums1[k] == square:
19 count += freq2[square]
20
21 return count
22
23# Example usage
24print(countTriplets([7,4], [5,2,8,9]))ℹ
Complexity note: The time complexity is O(n) for creating frequency maps, but we still have to check pairs which can lead to O(n²) in the worst case. However, the use of frequency maps allows us to reduce redundant calculations. The space complexity is O(n) due to the storage of frequency maps.
- 1Using frequency maps can significantly reduce redundant calculations.
- 2Understanding the conditions for valid triplets is crucial for optimizing the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.