Given Q queries where each query consists of two numbers L and R which denotes a range [L, R]. The task is to find the sum of all Even Parity Numbers lying in the given range [L, R].
Parity of a number refers to whether it contains an odd or even number of 1-bits. The number has Even Parity if it contains even number of 1-bits.
Input: Q = [ [1, 10], [121, 211] ]
binary(1) = 01, parity = 1
binary(2) = 10, parity = 1
binary(3) = 11, parity = 2
binary(4) = 100, parity = 1
binary(5) = 101, parity = 2
binary(6) = 110, parity = 2
binary(7) = 111, parity = 3
binary(8) = 1000, parity = 1
binary(9) = 1001, parity = 2
binary(10) = 1010, parity = 2
From 1 to 10, 3, 5, 6, 9 and 10 are the Even Parity numbers. Therefore the sum is 33.
From 121 to 211 the sum of all the even parity numbers is 7493.
Input: Q = [ [ 10, 10 ], [ 258, 785 ], [45, 245], [ 1, 1000]]
The idea is to use a Prefix Sum Array. The sum of all Even Parity Numbers till that particular index is precomputed and stored in an array pref so that every query can be answered in O(1) time.
- Initialise the prefix array pref.
- Iterate from 1 to N and check if the number has even parity or not:
- If the number is Even Parity Number then, the current index of pref will store the sum of Even Parity Numbers found so far.
- Else the current index of pref is same as the value at previous index of pref.
- For Q queries the sum of all Even Parity Numbers for range [L, R] can be calculated as follows:
sum = pref[R] - pref[L - 1]
Below is the implementation of the above approach
Time Complexity: O(N), where N is the maximum element in the query.