Find the farthest smaller number in the right side

13 Jun, 2022
Given an array arr[] of size N. For every element in the array, the task is to find the index of the farthest element in the array to the right which is smaller than the current element. If no such number exists then print -1. 
Examples: 
Input: arr[] = {3, 1, 5, 2, 4} Output: 3 -1 4 -1 -1 arr[3] is the farthest smallest element to the right of arr[0]. arr[4] is the farthest smallest element to the right of arr[2]. And for the rest of the elements, there is no smaller element to their right.
Input: arr[] = {1, 2, 3, 4, 0} Output: 4 4 4 4 -1 
Approach 1 : (Brute Force Method)
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 at any index j find smaller element from the current element,  i.e. (a[i] > a[j]) break from the loop.
Below is the implementation of the above approach :
C++
Java
C#
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find the farthest// smaller number in the right sidevoid farthest_min(int a[], int n){     for (int i = 0; i < n; i++) {               // keeping the idx = -1 from beginning        int idx = -1;         // traverse the given array backward        for (int j = n - 1; j > i; j--) {                       // if found any element smaller            if (a[i] > a[j]) {                // update that index and break                idx = j;                break;            }        }         // Print the required index        cout << idx << " ";    }} // Driver codeint main(){    int a[] = { 3, 1, 5, 2, 4 };    int n = sizeof(a) / sizeof(a[0]);     farthest_min(a, n);     return 0;} // this code is contributed by Rajdeep
// Java implementation of the approachclass GFG {     // Function to find the farthest    // smaller number in the right side    static void farthest_min(int[] a, int n)    {        // To store minimum element        // in the range i to n         for (int i = 0; i < n; i++) {                         // keeping the idx = -1 from beginning            int idx = -1;                       for (int j = n - 1; j > i; j--) {                               // if found any element smaller                if (a[i] > a[j]) {                    // update that index and break                    idx = j;                    break;                }            }             System.out.print(idx + " ");        }    }     // Driver code    public static void main(String[] args)    {        int[] a = { 3, 1, 5, 2, 4 };        int n = a.length;         farthest_min(a, n);    }} // This code is contributed by Rajdeep
// C# implementation of the approachusing System;class GFG {     // Function to find the farthest    // smaller number in the right side    static void farthest_min(int[] a, int n)    {        // To store minimum element        // in the range i to n         for (int i = 0; i < n; i++) {             // keeping the idx = -1 from beginning            int idx = -1;             for (int j = n - 1; j > i; j--) {                 // if found any element smaller                if (a[i] > a[j]) {                    // update that index and break                    idx = j;                    break;                }            }             Console.Write(idx + " ");        }    }     // Driver code    public static void Main()    {        int[] a = { 3, 1, 5, 2, 4 };        int n = a.Length;         farthest_min(a, n);    }} // This code is contributed by Samim Hossain Mondal.
3 -1 4 -1 -1 
Time Complexity : O(N^2)Auxiliary Space :  O(1)
Approach 2 : (Optimized Method)
An efficient approach is to create a suffix_min[] array where suffix_min[i] stores the minimum element from the subarray arr[i ... N – 1]. Now for any element arr[i], binary search can be used on the subarray suffix_min[i + 1 ... N – 1] to find the farthest smallest element to the right of arr[i].
Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find the farthest// smaller number in the right sidevoid farthest_min(int a[], int n){    // To store minimum element    // in the range i to n    int suffix_min[n];    suffix_min[n - 1] = a[n - 1];    for (int i = n - 2; i >= 0; i--) {        suffix_min[i] = min(suffix_min[i + 1], a[i]);    }     for (int i = 0; i < n; i++) {        int low = i + 1, high = n - 1, ans = -1;         while (low <= high) {            int mid = (low + high) / 2;             // If current element in the suffix_min            // is less than a[i] then move right            if (suffix_min[mid] < a[i]) {                ans = mid;                low = mid + 1;            }            else                high = mid - 1;        }         // Print the required answer        cout << ans << " ";    }} // Driver codeint main(){    int a[] = { 3, 1, 5, 2, 4 };    int n = sizeof(a) / sizeof(a[0]);     farthest_min(a, n);     return 0;}
// Java implementation of the approachclass GFG {     // Function to find the farthest    // smaller number in the right side    static void farthest_min(int[] a, int n)    {        // To store minimum element        // in the range i to n        int[] suffix_min = new int[n];         suffix_min[n - 1] = a[n - 1];        for (int i = n - 2; i >= 0; i--) {            suffix_min[i]                = Math.min(suffix_min[i + 1], a[i]);        }         for (int i = 0; i < n; i++) {            int low = i + 1, high = n - 1, ans = -1;             while (low <= high) {                int mid = (low + high) / 2;                 // If current element in the suffix_min                // is less than a[i] then move right                if (suffix_min[mid] < a[i]) {                    ans = mid;                    low = mid + 1;                }                else                    high = mid - 1;            }             // Print the required answer            System.out.print(ans + " ");        }    }     // Driver code    public static void main(String[] args)    {        int[] a = { 3, 1, 5, 2, 4 };        int n = a.length;         farthest_min(a, n);    }} // This code is contributed by ihritik
# Python3 implementation of the approach # Function to find the farthest# smaller number in the right side  def farthest_min(a, n):     # To store minimum element    # in the range i to n    suffix_min = [0 for i in range(n)]    suffix_min[n - 1] = a[n - 1]    for i in range(n - 2, -1, -1):        suffix_min[i] = min(suffix_min[i + 1], a[i])     for i in range(n):        low = i + 1        high = n - 1        ans = -1         while (low <= high):            mid = (low + high) // 2             # If current element in the suffix_min            # is less than a[i] then move right            if (suffix_min[mid] < a[i]):                ans = mid                low = mid + 1            else:                high = mid - 1         # Print the required answer        print(ans, end=" ")  # Driver codea = [3, 1, 5, 2, 4]n = len(a) farthest_min(a, n) # This code is contributed by Mohit Kumar
// C# implementation of the approachusing System;class GFG {     // Function to find the farthest    // smaller number in the right side    static void farthest_min(int[] a, int n)    {        // To store minimum element        // in the range i to n        int[] suffix_min = new int[n];         suffix_min[n - 1] = a[n - 1];        for (int i = n - 2; i >= 0; i--) {            suffix_min[i]                = Math.Min(suffix_min[i + 1], a[i]);        }         for (int i = 0; i < n; i++) {            int low = i + 1, high = n - 1, ans = -1;             while (low <= high) {                int mid = (low + high) / 2;                 // If current element in the suffix_min                // is less than a[i] then move right                if (suffix_min[mid] < a[i]) {                    ans = mid;                    low = mid + 1;                }                else                    high = mid - 1;            }             // Print the required answer            Console.Write(ans + " ");        }    }     // Driver code    public static void Main()    {        int[] a = { 3, 1, 5, 2, 4 };        int n = a.Length;         farthest_min(a, n);    }} // This code is contributed by ihritik
Javascript<script> // Javascript implementation of the approach // Function to find the farthest// smaller number in the right sidefunction farthest_min(a, n){    // To store minimum element    // in the range i to n    let suffix_min = new Array(n);    suffix_min[n - 1] = a[n - 1];    for (let i = n - 2; i >= 0; i--) {        suffix_min[i] = Math.min(suffix_min[i + 1], a[i]);    }     for (let i = 0; i < n; i++) {        let low = i + 1, high = n - 1, ans = -1;         while (low <= high) {            let mid = Math.floor((low + high) / 2);             // If current element in the suffix_min            // is less than a[i] then move right            if (suffix_min[mid] < a[i]) {                ans = mid;                low = mid + 1;            }            else                high = mid - 1;        }         // Print the required answer        document.write(ans + " ");    }} // Driver code     let a = [ 3, 1, 5, 2, 4 ];    let n = a.length;     farthest_min(a, n);     //This code is contributed by Mayank Tyagi </script>
3 -1 4 -1 -1 
Time Complexity: O(N* log(N) )Auxiliary Space: O(N)
mohit kumar 29
ihritik
nidhi_biet
ujjwalgoel1103
mayanktyagi1709
gulshankumarar231
rajdeepmallick999
samim2000
Binary Search
Suffix-Array
Arrays
Searching
Arrays
Searching
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.