![]() |
VOOZH | about |
You have an array arr[] of size N and Q queries where in each query, we need to find two distinct indices within the specified range in the array such that the values at those indices are different. If such indices exist, you should return them. Otherwise, return (-1, -1).
Examples:
Input: N = 5, Q = 3, arr[] = {1, 1, 2, 1, 1} queries[][] = {{0, 4}, {0, 1}, {0, 2}}
Output:
1 2
-1 -1
1 2
Explanation: We can select index 1 and 2 in the range 0 to 4 such that the values at these indexes are different, for range (0, 1) we cannot find any such pair of indices which have different values, and for range (0, 2) we can find index 1 and 2 which have different values.Input: N = 4, Q = 2, arr[] = {1, 1, 1, 2}, queries[][] = {{0, 3}, {0, 2}}
Output:
2 3
-1 -1
Explanation: We can select index 2 and 3 in the range 0 to 3 such that the values at these indexes are different and for range (0, 2) we cannot find any such pair of indices which have different values.
Approach: To solve the problem, follow the below idea:
The key idea behind the approach is to precompute the array to find the nearest index to the left with a different value for each element. Then, for each query, it efficiently checks whether such a pair exists within the specified range using the precomputed information. The use of prefix preprocessing helps achieve an efficient solution to the problem.
Step-by-step algorithm:
Below is the implementation of above approach:
2 4 -1 -1 1 2
Time Complexity: O(N), where N is the size of input array arr[].
Auxiliary Space: O(Q)