
You are given an array A of 'N' integers and 'Q' queries.
For each query, you are given a start index L and an end index R (1-based), which define a subarray A[L...R].
Your task is to find the median of this subarray. The median of a subarray is defined as the element that would be at the middle position if the subarray were sorted in non-decreasing order.
The first line of input contains an integer 'N'.
The second line contains 'N' space-separated integers, representing the elements of array A.
The third line contains an integer 'Q', the number of queries.
The next 'Q' lines each contain two space-separated integers, L and R.
For each query, print the median of the subarray A[L...R] on a new line.
The problem uses 1-based indexing for L and R, which should be converted to 0-based for array access in most languages.
A naive solution would be to extract the subarray, sort it, and find the middle element for each query. This is too slow (O(Q * N log N)).
An optimized approach for the given constraints would typically involve a persistent segment tree or a similar advanced data structure that can answer order statistic queries on a range in O(log N) time. A simpler approach using a Fenwick tree (BIT) or segment tree on a sorted, coordinate-compressed version of the values is also possible.
5
3 1 2 5 4
2
1 5
2 4
3
2
Query 1 (L=1, R=5): The subarray is `{3, 1, 2, 5, 4}`.
- Sorted, it becomes `{1, 2, 3, 4, 5}`.
- Length is 5. Median position is `(5+1)/2 = 3`.
- The 3rd element is 3.
Query 2 (L=2, R=4): The subarray is `{1, 2, 5}`.
- Sorted, it becomes `{1, 2, 5}`.
- Length is 3. Median position is `(3+1)/2 = 2`.
- The 2nd element is 2.
The expected time complexity for an optimized solution is O((N+Q)*log(N)).
1 <= N, Q <= 10^5
-10^9 <= A[i] <= 10^9
Time limit: 1 sec