Skip to content

Commit 28d779a

Browse files
committed
Sync LeetCode submission Runtime - 321 ms (82.46%), Memory - 46.4 MB (65.40%)
1 parent de5c710 commit 28d779a

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<p>Given an array <code>nums</code> of <strong>distinct</strong> positive integers, return <em>the number of tuples </em><code>(a, b, c, d)</code><em> such that </em><code>a * b = c * d</code><em> where </em><code>a</code><em>, </em><code>b</code><em>, </em><code>c</code><em>, and </em><code>d</code><em> are elements of </em><code>nums</code><em>, and </em><code>a != b != c != d</code><em>.</em></p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
6+
<pre>
7+
<strong>Input:</strong> nums = [2,3,4,6]
8+
<strong>Output:</strong> 8
9+
<strong>Explanation:</strong> There are 8 valid tuples:
10+
(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
11+
(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)
12+
</pre>
13+
14+
<p><strong class="example">Example 2:</strong></p>
15+
16+
<pre>
17+
<strong>Input:</strong> nums = [1,2,4,5,10]
18+
<strong>Output:</strong> 16
19+
<strong>Explanation:</strong> There are 16 valid tuples:
20+
(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)
21+
(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)
22+
(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)
23+
(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)
24+
</pre>
25+
26+
<p>&nbsp;</p>
27+
<p><strong>Constraints:</strong></p>
28+
29+
<ul>
30+
<li><code>1 &lt;= nums.length &lt;= 1000</code></li>
31+
<li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
32+
<li>All elements in <code>nums</code> are <strong>distinct</strong>.</li>
33+
</ul>
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Approach 3: Product Frequency Hash Map
2+
3+
# Time: O(n^2)
4+
# Space: O(n^2)
5+
6+
class Solution:
7+
def tupleSameProduct(self, nums: List[int]) -> int:
8+
n = len(nums)
9+
10+
pair_products_freq = {}
11+
total_num_of_tuples = 0
12+
13+
for first_idx in range(n):
14+
for second_idx in range(first_idx + 1, n):
15+
product_val = nums[first_idx] * nums[second_idx]
16+
17+
pair_products_freq[product_val] = pair_products_freq.get(product_val, 0) + 1
18+
19+
20+
for product_freq in pair_products_freq.values():
21+
pairs_of_equal_product = (product_freq - 1) * product_freq // 2
22+
23+
total_num_of_tuples += 8 * pairs_of_equal_product
24+
25+
return total_num_of_tuples
26+

0 commit comments

Comments
 (0)