Combinatorial to reduce to N^2

This is an interesting problem: Tuple with Same Product - LeetCode

1726. Tuple with Same Product
Medium

Given an array nums of distinct positive integers, return the number of tuples (a, b, c, d) such that a * b = c * d where abc, and d are elements of nums, and a != b != c != d.

 

Example 1:

Input: nums = [2,3,4,6]
Output: 8
Explanation: There are 8 valid tuples:
(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)

Example 2:

Input: nums = [1,2,4,5,10]
Output: 16
Explanation: There are 16 valids tuples:
(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)
(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)
(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,4,5)
(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)

Example 3:

Input: nums = [2,3,4,6,8,12]
Output: 40

Example 4:

Input: nums = [2,3,5,7]
Output: 0

 

Constraints:

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 104
  • All elements in nums are distinct.
Accepted
7,173
Submissions
13,843

If you try to generate all permutations, you'll end up with N^4, since N=10^3, becomes intractable (10^12). But, using combinatorial you can "remove" one N^2, here is how:

1/ First compute on a cache the number of pairs that multiply to the same number - do it in N^2

2/ From this point iterate thru the cache and for each value you need to do a combinatorial "value 2 by 2", which is simply k!/(2! * (k-2)!), or simply k*(k-1)/2.

3/ But in addition to that there are 8 different permutations for each result in (2). So multiply it by 8

That should do it. Code is below, cheers, ACC.


public int TupleSameProduct(int[] nums)
{
    Hashtable count = new Hashtable();

    for (int i = 0; i < nums.Length; i++)
    {
        for (int j = i + 1; j < nums.Length; j++)
        {
            int m = nums[i] * nums[j];
            if (!count.ContainsKey(m)) count.Add(m, 0);
            count[m] = (int)count[m] + 1;
        }
    }

    int result = 0;
    foreach (int key in count.Keys)
    {
        int v = (int)count[key];
        int c = (v * (v - 1)) / 2;
        result += 8 * c;
    }

    return result;
}

Comments

Popular posts from this blog

Advent of Code - Day 6, 2024: BFS and FSM

Golang vs. C#: performance characteristics (simple case study)

Advent of Code - Day 7, 2024: Backtracking and Eval