![]() |
VOOZH | about |
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].
Table of Content
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.
2 4 -1 4 -1
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:
2 4 -1 4 -1