![]() |
VOOZH | about |
Given an array A of size N, containing integers. We have to answer Q queries where each query is of the form:
For each query print two integers p and q which represent the probability p/q. Both p and q are reduced to the minimal form.
If p is 0 print 0 or if p is equal to q print 1, otherwise print p and q alone.
Examples:
Input : N = 5, arr[] = { 6, 5, 2, 1, 7 }
query 1: 0 2 2
query 2: 1 2 5
query 3: 0 1 4
Output : 0
3 4
1 2
Explanation :
First query is to find probability of even
element in range [2, 2]. Since range contains
a single element 5 which is odd, the answer
is 0. Second query is to find probability of
odd element in range [2, 5]. There are 3
odd elements in range probability is 3/4.
Third query is for even elements in range
from 1 to 4. Since there are equal even
and odd elements, probability is 2/4
which is 1/2.
The idea is to maintain two arrays, say even[] and odd[], which maintain the number of even or odd element upto index i. Now, to answer each query, we can compute result denominator q by finding number of element in the given query range. To find result numerator, we remove number of elements upto l - 1 from elements upto r.
To output the answer in minimal form, we find the GCD of p and q and output p/gcd and q/gcd. For answer 0 and 1, we will explicitly specify the conditions.
Below is the implementation of this approach:
0 3 4
Time Complexity: O(n)
Auxiliary Space: O(n)