Find Products of Elements of Big Array - Problem
Find Products of Elements of Big Array

Imagine a magical array called big_nums that's constructed in a fascinating way! For every positive integer, we create its powerful array - which contains all the powers of 2 that sum up to that number (based on its binary representation).

For example:
โ€ข Number 13 has binary 1101, so its powerful array is [1, 4, 8] (positions of 1-bits)
โ€ข Number 23 has binary 10111, so its powerful array is [1, 2, 4, 16]

The big_nums array is formed by concatenating all these powerful arrays in order:
[1, 2, 1, 2, 4, 1, 4, 2, 4, 1, 2, 4, 8, ...]

Your task: Given multiple queries [from, to, mod], calculate the product of elements from index from to to (inclusive) in big_nums, modulo mod.

Can you solve this efficiently without actually building the massive array?

Input & Output

example_1.py โ€” Basic Query
$ Input: queries = [[0, 2, 3]]
โ€บ Output: [2]
๐Ÿ’ก Note: big_nums = [1, 2, 1, 2, 4, ...]. Range [0,2] contains [1,2,1]. Product = 1ร—2ร—1 = 2. Since 2 < 3, result is 2.
example_2.py โ€” Multiple Queries
$ Input: queries = [[2, 5, 4], [0, 2, 3]]
โ€บ Output: [0, 2]
๐Ÿ’ก Note: Range [2,5] = [1,2,4,1] โ†’ product = 8 โ‰ก 0 (mod 4). Range [0,2] = [1,2,1] โ†’ product = 2.
example_3.py โ€” Large Numbers
$ Input: queries = [[10, 15, 7]]
โ€บ Output: [1]
๐Ÿ’ก Note: For large ranges, we need efficient calculation without building the actual array. The product modulo 7 equals 1.

Constraints

  • 1 โ‰ค queries.length โ‰ค 500
  • queries[i].length == 3
  • 0 โ‰ค fromi โ‰ค toi โ‰ค 1015
  • 2 โ‰ค modi โ‰ค 109
  • The answer is guaranteed to fit in a 32-bit integer.

Visualization

Tap to expand
Big Array Construction VisualizationNumbers โ†’ Powerful Arrays โ†’ Big Sequence11โ‚‚1210โ‚‚2311โ‚‚124100โ‚‚4Big Array Sequence:1[0]2[1]1[2]2[3]4[4]...
Understanding the Visualization
1
Extract Powers
Each number contributes its binary powers to the sequence
2
Mathematical Mapping
Use formulas to find position without building array
3
Efficient Calculation
Count and multiply using modular arithmetic
Key Takeaway
๐ŸŽฏ Key Insight: Instead of building the massive array, use mathematical formulas to count power occurrences and binary search for efficient index mapping!
Asked in
Google 45 Meta 32 Amazon 28 Microsoft 22
42.0K Views
Medium Frequency
~35 min Avg. Time
1.5K 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