Minimum Non-Zero Product of the Array Elements - Problem

You are given a positive integer p. Consider an array nums (1-indexed) that consists of the integers in the inclusive range [1, 2^p - 1] in their binary representations. You are allowed to do the following operation any number of times:

  • Choose two elements x and y from nums.
  • Choose a bit in x and swap it with its corresponding bit in y. Corresponding bit refers to the bit that is in the same position in the other integer.

For example, if x = 1101 and y = 0011, after swapping the 2nd bit from the right, we have x = 1111 and y = 0001.

Find the minimum non-zero product of nums after performing the above operation any number of times. Return this product modulo 10^9 + 7.

Note: The answer should be the minimum product before the modulo operation is done.

Input & Output

Example 1 — Basic Case
$ Input: p = 1
Output: 1
💡 Note: Array is [1], so the product is 1
Example 2 — Small Array
$ Input: p = 2
Output: 6
💡 Note: Array is [1,2,3]. Optimal: swap to get [1,2,3] or [3,2,1]. Product = 1×2×3 = 6
Example 3 — Larger Case
$ Input: p = 3
Output: 1512
💡 Note: Array is [1,2,3,4,5,6,7]. After optimal swaps: many 1s, many 6s, one 7. Product = 6³ × 7 = 1512

Constraints

  • 1 ≤ p ≤ 60

Visualization

Tap to expand
Minimum Non-Zero Product of Array Elements INPUT p = 1 Array range: [1, 2^p - 1] = [1, 2^1 - 1] = [1, 1] nums array: 1 index: 1 Binary form: 1 Input: p = 1 ALGORITHM STEPS 1 Calculate max value max = 2^p - 1 = 1 2 Count pairs pairs = (2^p - 2) / 2 = 0 3 Apply formula result = max * (max-1)^pairs 4 Compute result = 1 * (0)^0 = 1 Optimal Formula: (2^p - 1) * (2^p - 2)^((2^p-2)/2) mod (10^9 + 7) For p=1: only element is 1 Product = 1 FINAL RESULT Minimum Non-Zero Product 1 With p = 1: nums = [1] Only one element exists No swaps possible OK Output: 1 Key Insight: To minimize product, maximize the count of smallest non-zero values (1s) and have one maximum value. Swap bits to create pairs of (2^p - 1, 1). The formula: (2^p - 1) * (2^p - 2)^((2^(p-1)) - 1) handles all cases. For p=1, the array contains only [1], so the product is trivially 1. TutorialsPoint - Minimum Non-Zero Product of the Array Elements | Optimal Solution
Asked in
Google 25 Facebook 18
23.0K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen