VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sudo-placement1-5-second-smallest-in-range/

⇱ Sudo Placement[1.5] | Second Smallest in Range - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sudo Placement[1.5] | Second Smallest in Range

Last Updated : 11 Jul, 2025

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.  

  • Initialize both first and second smallest as INT_MAX
  • Loop through all the elements. 
    1. If the current element is smaller than the first, then update first and second.
    2. Else if the current element is smaller than the second then update second

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:  


Output
-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.

Comment