Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2438. Range Product Queries of Powers

Explanation

To solve this problem, we first need to generate the array powers that represents the minimum number of powers of 2 to sum up to n. We then iterate through each query and calculate the product of elements in the range specified by the query in the powers array. Finally, we return the answers modulo 10^9 + 7.

  1. Generate the powers array representing the minimum powers of 2 to sum up to n.
  2. Iterate through each query and calculate the product of elements in the specified range.
  3. Return the answers modulo 10^9 + 7.

Time Complexity:
Generating the powers array takes O(log n) time. Handling each query takes O(1) time. Thus, the overall time complexity is O(log n + q), where q is the number of queries.

Space Complexity:
The space complexity is O(log n) to store the powers array.

class Solution {
    public int[] rangeProductQueriesOfPowers(int n, int[][] queries) {
        int[] powers = new int[(int)(Math.log(n) / Math.log(2)) + 1];
        powers[0] = 1;
        for (int i = 1; i < powers.length; i++) {
            powers[i] = 2 * powers[i - 1];
        }

        int[] answers = new int[queries.length];
        int mod = 1000000007;

        for (int i = 0; i < queries.length; i++) {
            int left = queries[i][0];
            int right = queries[i][1];
            long product = 1;
            for (int j = left; j <= right; j++) {
                product = (product * powers[j]) % mod;
            }
            answers[i] = (int)product;
        }

        return answers;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.