Tuple with Same Product — LeetCode 1726 Python Solution
- Problem
- #1726
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an array nums of distinct positive integers, return the number of tuples (a, b, c, d) such that a * b = c * d where a, b, c, and d are elements of nums, and a != b != c != d.
Example
- Input
- nums = [2,3,4,6]
- Output
- 8
- Explanation
- There are 8 valid tuples:
Python solution
class Solution:
def tupleSameProduct(self, nums: List[int]) -> int:
cnt = defaultdict(int)
for i in range(1, len(nums)):
for j in range(i):
x = nums[i] * nums[j]
cnt[x] += 1
return sum(v * (v - 1) // 2 for v in cnt.values()) << 3Complexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(n^2) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1726. Tuple with Same Product is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1726. Tuple with Same Product?
- LeetCode 1726. Tuple with Same Product is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1726. Tuple with Same Product?
- The Python solution on this page runs in O(n^2).
- What is the space complexity of LeetCode 1726. Tuple with Same Product?
- The Python solution on this page uses O(n^2) auxiliary space.
- What topics does LeetCode 1726. Tuple with Same Product cover?
- LeetCode 1726. Tuple with Same Product is tagged Array, Hash Table and Counting on LeetCode.