# Find the nearest value present on the left of every array element

• Difficulty Level : Medium
• Last Updated : 10 Jun, 2021

Given an array arr[] of size N, the task is for each array element is to find the nearest non-equal value present on its left in the array. If no such element is found, then print -1

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr[] = { 2, 1, 5, 8, 3 }
Output: -1 2 2 5 2
Explanation:
[2], it is the only number in this prefix. Hence, answer is -1.
[2, 1], the closest number to 1 is 2
[2, 1, 5], the closest number to 5 is 2
[2, 1, 5, 8], the closest number to 8 is 5
[2, 1, 5, 8, 3], the closest number to 3 is 2

Input: arr[] = {3, 3, 2, 4, 6, 5, 5, 1}
Output: -1 -1 3 3 4 4 4 2
Explanation:
[3], it is the only number in this prefix. Hence, answer is -1.
[3, 3], it is the only number in this prefix. Hence, answer is -1
[3, 3, 2], the closest number to 2 is 3
[3, 3, 2, 4], the closest number to 4 is 3
[3, 3, 2, 4, 6], the closest number to 6 is 4
[3, 3, 2, 4, 6, 5], the closest number to 5 is 4
[3, 3, 2, 4, 6, 5, 5], the closest number to 5 is 4
[3, 3, 2, 4, 6, 5, 5, 1], the closest number to 1 is 2

Naive Approach: The simplest idea is to traverse the given array and for every ith element, find the closest element on the left side of index i which is not equal to arr[i]
Time Complexity: O(N^2)
Auxiliary Space: O(1)

Efficient Approach:

The idea is to insert the elements of the given array in a Set such that the inserted numbers are sorted and then for an integer, find its position and compare its next value with the previous value, and print the closer value out of the two.
Follow the steps below to solve the problem:

• Initialize a Set of integers S to store the elements in sorted order.
• Traverse the array arr[] using the variable i.
• Now, find the nearest value smaller as well as greater than arr[i], say X and Y respectively.
• If X cannot be found, print Y.
• If Y cannot be found, print Z.
• If both X and Y cannot be found, print “-1”.
• After that, add arr[i] to the Set S and print X if abs(X – arr[i]) is smaller than abs(Y – arr[i]). Otherwise, print Y.
• Repeat the above steps for every element.

Below is the implementation of the above approach:

## C++14

 // C++ program for the above approach#include using namespace std; // Function to find the closest number on// the left side of xvoid printClosest(set& streamNumbers, int x){     // Insert the value in set and store    // its position    auto it = streamNumbers.insert(x).first;     // If x is the smallest element in set    if (it == streamNumbers.begin())    {        // If count of elements in the set        // equal to 1        if (next(it) == streamNumbers.end())        {             cout << "-1 ";            return;        }         // Otherwise, print its        // immediate greater element        int rightVal = *next(it);        cout << rightVal << " ";        return;    }     // Store its immediate smaller element    int leftVal = *prev(it);     // If immediate greater element does not    // exists print it's immediate    // smaller element    if (next(it) == streamNumbers.end()) {        cout << leftVal << " ";        return;    }     // Store the immediate    // greater element    int rightVal = *next(it);     // Print the closest number    if (x - leftVal <= rightVal - x)        cout << leftVal << " ";    else        cout << rightVal << " ";} // Driver Codeint main(){     // Given array    vector arr = { 3, 3, 2, 4, 6, 5, 5, 1 };     // Initialize set    set streamNumbers;     // Print Answer    for (int i = 0; i < arr.size(); i++) {         // Function Call        printClosest(streamNumbers, arr[i]);    }     return 0;}
Output
-1 -1 3 3 4 4 4 2

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

My Personal Notes arrow_drop_up