KatInterview

Count Subsets With Product Equal to a Power of Two

Math & Bit ManipulationAuto-graded · 17 test cases
EasyAuto-gradedMath & Bit Manipulationcombinatoricsbit manipulationmath

Last updated

Tests whether candidates can combine combinatorics (counting subsets) with the insight that a product is a power of two iff every element is itself a power of two.

Count Subsets With Product Equal to a Power of Two

You are given a list of positive integers nums and a non-negative integer k.

A valid subset is any non-empty subset of nums whose product is exactly 2^k (two to the power of k).

Return the number of valid subsets.

Background

Recall that a positive integer is a power of two if and only if it has exactly one set bit in its binary representation (i.e. x & (x - 1) == 0). A product of integers is a power of two if and only if every factor is itself a power of two.

Therefore the problem reduces to:

  1. Identify which elements of nums are powers of two.
  2. Among those elements, count non-empty subsets whose exponents (where element 2^e contributes exponent e) sum to exactly k.

Task

Implement:

def count_power_subsets(nums: list[int], k: int) -> int:
  • nums may contain elements that are not powers of two; such elements can never appear in a valid subset.
  • Multiple elements with the same value are treated as distinct (they occupy different positions).
  • Return 0 if no valid subset exists.

Constraints

  • 1 ≤ len(nums) ≤ 2 000
  • 1 ≤ nums[i] ≤ 2^20
  • 0 ≤ k ≤ 40
  • The answer fits in a 64-bit signed integer.

Examples

Example 1

Input: count_power_subsets([1, 2, 4, 3], 2)

Output: 2

Example 2

Input: count_power_subsets([4, 2, 2], 2)

Output: 2

Example 3

Input: count_power_subsets([3, 5, 7], 3)

Output: 0

Hints

Hint 1

Filter out elements that are not powers of two first — they can never contribute to a valid subset.

Hint 2

For each remaining element 2^e, extract its exponent e using bit_length() - 1 or int.bit_length(). The problem then becomes: count subsets of a multiset of small non-negative integers that sum to k.

Hint 3

Use a 1-D DP array dp[s] = number of subsets of processed elements whose exponents sum to s, updating it like a 0-1 knapsack (iterate s from k down to 0).