| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | using System.Numerics; |
| | 13 | |
|
| | 14 | | namespace LeetCode.Algorithms.RangeProductQueriesOfPowers; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class RangeProductQueriesOfPowersPrefixSum : IRangeProductQueriesOfPowers |
| | 18 | | { |
| | 19 | | private const int Mod = 1_000_000_007; |
| | 20 | |
|
| | 21 | | /// <summary> |
| | 22 | | /// Time complexity - O(q), where q is queries.Length |
| | 23 | | /// Space complexity - O(1) |
| | 24 | | /// </summary> |
| | 25 | | /// <param name="n"></param> |
| | 26 | | /// <param name="queries"></param> |
| | 27 | | /// <returns></returns> |
| | 28 | | public int[] ProductQueries(int n, int[][] queries) |
| 2 | 29 | | { |
| 2 | 30 | | var exponents = new List<int>(BitOperations.PopCount((uint)n)); |
| | 31 | |
|
| 128 | 32 | | for (var bit = 0; bit < 31; bit++) |
| 62 | 33 | | { |
| 62 | 34 | | if (((n >> bit) & 1) == 0) |
| 57 | 35 | | { |
| 57 | 36 | | continue; |
| | 37 | | } |
| | 38 | |
|
| 5 | 39 | | exponents.Add(bit); |
| 5 | 40 | | } |
| | 41 | |
|
| 2 | 42 | | var exponentsPrefixSum = new int[exponents.Count + 1]; |
| | 43 | |
|
| 14 | 44 | | for (var i = 0; i < exponents.Count; i++) |
| 5 | 45 | | { |
| 5 | 46 | | exponentsPrefixSum[i + 1] = exponentsPrefixSum[i] + exponents[i]; |
| 5 | 47 | | } |
| | 48 | |
|
| 2 | 49 | | var maxExponent = exponentsPrefixSum[^1]; |
| | 50 | |
|
| 2 | 51 | | var powersOfTwo = new int[maxExponent + 1]; |
| | 52 | |
|
| 2 | 53 | | powersOfTwo[0] = 1; |
| | 54 | |
|
| 18 | 55 | | for (var i = 1; i <= maxExponent; i++) |
| 7 | 56 | | { |
| 7 | 57 | | powersOfTwo[i] = powersOfTwo[i - 1] * 2 % Mod; |
| 7 | 58 | | } |
| | 59 | |
|
| 2 | 60 | | var result = new int[queries.Length]; |
| | 61 | |
|
| 12 | 62 | | for (var i = 0; i < queries.Length; i++) |
| 4 | 63 | | { |
| 4 | 64 | | var left = queries[i][0]; |
| 4 | 65 | | var right = queries[i][1]; |
| 4 | 66 | | var exponent = exponentsPrefixSum[right + 1] - exponentsPrefixSum[left]; |
| | 67 | |
|
| 4 | 68 | | result[i] = powersOfTwo[exponent]; |
| 4 | 69 | | } |
| | 70 | |
|
| 2 | 71 | | return result; |
| 2 | 72 | | } |
| | 73 | | } |