#3566

Partition Array into Two Equal Product Subsets

Medium
ArrayBit ManipulationRecursionEnumeration
LeetCode ↗

Approaches

💡

Intuition

Time Space

We can generate all possible subsets of the array and check if any two non-empty subsets have the same product equal to the target. This is straightforward but inefficient.

⚙️

Algorithm

3 steps
  1. 1Step 1: Generate all possible subsets of the array using bit manipulation.
  2. 2Step 2: For each subset, calculate its product.
  3. 3Step 3: Check if there exists another subset with the same product equal to target.
solution.py21 lines
1from itertools import combinations
2
3def can_partition(nums, target):
4    n = len(nums)
5    for i in range(1, 1 << n):
6        subset1 = [nums[j] for j in range(n) if (i & (1 << j))]
7        if len(subset1) == 0 or len(subset1) == n:
8            continue
9        product1 = 1
10        for num in subset1:
11            product1 *= num
12        if product1 == target:
13            for j in range(1, 1 << n):
14                if j & i == 0:
15                    subset2 = [nums[k] for k in range(n) if (j & (1 << k))]
16                    product2 = 1
17                    for num in subset2:
18                        product2 *= num
19                    if product2 == target:
20                        return True
21    return False

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.