Problem solution · C++

Partition Array into Two Equal Product Subsets

Partition Array into Two Equal Product Subsets: a C++ solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Direct simulation
Source
Kamyu LeetCode Solutions
Length
36 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Direct simulation

For Partition Array into Two Equal Product Subsets, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 36 lines of C++ from the credited upstream file partition-array-into-two-equal-product-subsets.cpp.
  • The implementation visibly relies on sequence storage.
  • 3 loop blocks detected.

Complexity

Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codePartition Array into Two Equal Product Subsets · C++C++
Use this to learn the idea, then write your own version.
// Time:  O(n * 2^n)// Space: O(1) // bitmasksclass Solution {public:    bool checkEqualPartitions(vector<int>& nums, long long target) {        __int128 total = 1;        for (const auto& x : nums) {            total *= x;            if (total > static_cast<__int128>(target) * target) {                return false;            }        }        if (total != static_cast<__int128>(target) * target) {            return false;        }        for (int mask = 1; mask < (1 << size(nums)) - 1; ++mask) {            __int128 curr = 1;            for (int i = 0; i < size(nums); ++i) {                if (!(mask & (1 << i))) {                    continue;                }                curr *= nums[i];                if (curr > target) {                    break;                }            }            if (curr == target) {                return true;            }        }        return false;    }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗