Skip to content
Related Articles

Related Articles

Find the farthest smaller number in the right side

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 30 Aug, 2022
View Discussion
Improve Article
Save Article

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 

Recommended Practice

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++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the farthest
// smaller number in the right side
void 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 code
int 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




// Java implementation of the approach
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;
                }
            }
 
            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

Python3




# Python 3 implementation of the approach
# Function to find the farthest
# smaller number in the right side
def farthest_min(a, n):
  for i in range(n):
     
    # keeping the idx = -1 from beginning
    idx = -1
    j = n - 1
     
    # traverse the given array backward
    while j > i:
       
      # if found any element smaller   
      if a[i] > a[j]:
         
        # update that index and break
        idx = j
         
        break
      j -= 1
       
    # Print the required index
    print(idx,end=" ")
     
# Driver code
a = [3,1,5,2,4]
n = len(a)
farthest_min(a, n)
 
"This Code is contributed by rajatkumargla19"

C#




// C# implementation of the approach
using 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.

Output

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++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the farthest
// smaller number in the right side
void 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 code
int main()
{
    int a[] = { 3, 1, 5, 2, 4 };
    int n = sizeof(a) / sizeof(a[0]);
 
    farthest_min(a, n);
 
    return 0;
}

Java




// Java implementation of the approach
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
            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




# 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 code
a = [3, 1, 5, 2, 4]
n = len(a)
 
farthest_min(a, n)
 
# This code is contributed by Mohit Kumar

C#




// C# implementation of the approach
using 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




Javascript<script>
 
// Javascript implementation of the approach
 
// Function to find the farthest
// smaller number in the right side
function 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>

Output

3 -1 4 -1 -1 

Time Complexity: O(N* log(N) )
Auxiliary Space: O(N)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!