VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-farthest-smaller-number-in-the-right-side/

⇱ Rightmost Smaller for Each Element - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Rightmost Smaller for Each Element

Last Updated : 19 Jul, 2025

Given an array arr[] of size n. For each element arr[i] (0-based indexing), find the index of the farthest element to its right (i.e., having a greater index) such that arr[j] < arr[i] and j > i. If no such element exists, return -1 for that position.

Examples:

Input: arr[] = [2, 5, 1, 3, 2] 
Output: [2, 4, -1, 4, -1] 
Explanation: arr[0] = 2: Farthest smaller element to the right is arr[2] = 1 → index 2.
arr[1] = 5: Farthest smaller element to the right is arr[4] = 2 → index 4.
arr[2] = 1: No smaller element to the right → -1.
arr[3] = 3: Farthest smaller element to the right is arr[4] = 2 → index 4.
arr[4] = 2: No elements to the right → -1.

Input: arr[] = [2, 3, 5, 4, 1] 
Output: [4, 4, 4, 4, -1]
Explanation: arr[4] is the farthest smallest element to the right for arr[0], arr[1], arr[2] and arr[3].

[Naive Approach] Checking Each Element in Right – O(n^2) Time and O(1) Space

A brute force approach to this problem can be, keep a variable idx = -1 from beginning and for each element start traversing the same array from the backward upto (i+1)th index. And, if any element at index j is smaller than the current element,  i.e. (a[i] > a[j]) break from the loop, and return the jth index.


Output
2 4 -1 4 -1 

[Expected Approach] Binary Search – O(n*log(n)) Time and O(n) Space

The idea is to find the farthest smaller element to the right for each arr[i], we want a way to quickly know if a smaller element exists further ahead and how far it is.
Instead of scanning all elements to the right of every index, we can precompute:
The minimum values in all suffixes of the array. This allows us to efficiently search for the farthest valid position using binary search.

Step By Step Implementations:

  • Suffix Minimum Array
    -> For each position in the array, store the minimum value among all elements from that index to the end.
    -> This allows us to know quickly if there's any smaller element on the right.
  • Binary Search for Each Element
    -> For every element arr[i], use binary search on the suffix minimum array to find the farthest index j > i such that the value at j is smaller than arr[i].
    -> We try to go as far as possible to the right while the condition holds.
  • Store and Return Results
    -> If such an index is found, store it.
    -> If not, store -1 for that position.

Output
2 4 -1 4 -1 
Comment