Magicsheet logo

Find Products of Elements of Big Array

Hard
71.7%
Updated 6/1/2025

Find Products of Elements of Big Array

What is this problem about?

The Find Products of Elements of Big Array interview question is a high-level bitwise math problem. A "Big Array" is constructed by taking every positive integer ii and appending the powers of 2 that sum to ii (in ascending order). For example, 3=20+213 = 2^0 + 2^1, so the parts for 3 are {0,1}\{0, 1\}. You are given queries [from,to][from, to] and need to find the product of all elements in that range of the Big Array, modulo mm.

Why is this asked in interviews?

IBM and other technical firms ask this to test a candidate's mastery of Bit Manipulation and Binary Search. It is a "Hard" problem because the Big Array is virtually infinite. You must use combinatorial counting to find which integers contribute to a specific range of the array without actually building the array. It evaluates your ability to handle large-scale numeric patterns.

Algorithmic pattern used

This follows the Digit/Bit Counting and Binary Search pattern.

  1. Find Integer Range: Use binary search to find the integer NN such that the total number of set bits in all integers from 1N1 \dots N is approximately equal to the query index.
  2. Count Bits: For each bit position jj, calculate how many times the jthj^{th} bit is set in the range [1,N][1, N].
  3. Power Calculation: The product of 2aimes2b2^a imes 2^b \dots is 2a+b+2^{a+b+\dots}. Calculate the total sum of all exponents in the query range.
  4. Modulo Math: Use binary exponentiation (pow(2, exponent_sum, m)) to find the final product.

Example explanation

Integers: 1 (bits: {0}), 2 (bits: {1}), 3 (bits: {0, 1}). Big Array: [0, 1, 0, 1, ...]

  • index 0: 202^0
  • index 1: 212^1
  • index 2: 202^0
  • index 3: 212^1 Query [0,1][0, 1]: 20imes21=20+1=22^0 imes 2^1 = 2^{0+1} = 2.

Common mistakes candidates make

  • Building the array: Trying to actually append elements to a list. The indices can be up to 101510^{15}, which is impossible to store.
  • Counting bits: Inefficiently counting bits for each number instead of using the mathematical pattern for bit frequency in a range.
  • Modulo: Forgetting that you cannot take the modulo of the exponent directly unless you use Euler's Totient Theorem (the exponent sum must be used in a power function).

Interview preparation tip

Learn the formula for counting set bits in the range [1,N][1, N]. For the jthj^{th} bit, the pattern 00,110 \dots 0, 1 \dots 1 repeats every 2j+12^{j+1} numbers. This is a foundational Bit Manipulation interview pattern for large-scale problems.

Similar Questions