![]() |
VOOZH | about |
Given an array of N integers and Q queries. Every query consists of L and R. The task is to print the second smallest element in range L-R. Print -1 if no second smallest element exists.
Examples:
Input:
a[] = {1, 2, 2, 4}
Queries= 2
L = 1, R = 2
L = 0, R = 1
Output:
-1
2
Approach: Process every query and print the second smallest using the following algorithm.
If the second element is still INT_MAX after looping through all the elements, print -1 else print the second smallest element.
Below is the implementation of the above approach:
-1 2
Time Complexity: O(M), where M = R-L is the number of elements in the range [L, R]
Auxiliary Space: O(1)
Note: Since the constraints of the question were very less, a brute force solution will pass. The solution can be further optimized using a Segment Tree.