Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Find the nearest perfect square for each element of the array
Next article icon

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

Last Updated : 11 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

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 <bits/stdc++.h>
using namespace std;
  
// Function to find the closest number on
// the left side of x
void printClosest(set<int>& 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 Code
int main()
{
  
    // Given array
    vector<int> arr = { 3, 3, 2, 4, 6, 5, 5, 1 };
  
    // Initialize set
    set<int> streamNumbers;
  
    // Print Answer
    for (int i = 0; i < arr.size(); i++) {
  
        // Function Call
        printClosest(streamNumbers, arr[i]);
    }
  
    return 0;
}
 
 

Java




import java.util.*;
  
class Main {
  // Function to find the closest number on
  // the left side of x
  static void printClosest(SortedSet<Integer> streamNumbers, int x) {
  
    streamNumbers.add(x);
    int rightVal, leftVal;
    // Insert the value in set and store
    // its position
    List<Integer> it = new ArrayList<>(streamNumbers);
    it.sort(null);
  
    int i = it.indexOf(x);
  
    // If x is the smallest element in set
    if (it.get(i) == it.get(0)) {
      // If count of elements in the set
      // equal to 1
      if (it.size() == 1) {
  
        System.out.print("-1 ");
        return;
      }
  
      // Otherwise, print its
      // immediate greater element
      rightVal = it.get(i + 1);
      System.out.print(rightVal + " ");
      return;
    }
  
    // Store its immediate smaller element
    leftVal = it.get(i - 1);
  
    // If immediate greater element does not
    // exists print it's immediate
    // smaller element
    if (i + 1 == it.size()) {
      System.out.print(leftVal + " ");
      return;
    }
  
    // Store the immediate
    // greater element
    rightVal = it.get(i + 1);
  
    // Print the closest number
    if (x - leftVal <= rightVal - x)
      System.out.print(leftVal + " ");
    else
      System.out.print(rightVal + " ");
  }
  
  // Driver Code
  public static void main(String[] args) {
    // Given array
    int[] arr = {3, 3, 2, 4, 6, 5, 5, 1};
  
    // Initialize set
    SortedSet<Integer> streamNumbers = new TreeSet<>();
  
    // Print Answer
    for (int i = 0; i < arr.length; i++) {
      // Function Call
      printClosest(streamNumbers, arr[i]);
    }
  }
}
 
 

Python3




# Python3 program for the above approach
  
# Function to find the closest number on
# the left side of x
def printClosest(streamNumbers, x):
    streamNumbers.add(x);
      
    # Insert the value in set and store
    # its position
    it =sorted(streamNumbers)
     
    i = it.index(x);
      
    # If x is the smallest element in set
    if (it[i] == it[0]):
      
        # If count of elements in the set
        # equal to 1
        if ( len(it) == 1):
  
            print("-1", end = " ");
            return;
          
        # Otherwise, print its
        # immediate greater element
        rightVal = it[i + 1]
        print(rightVal, end = " ");
        return;
      
    # Store its immediate smaller element
    leftVal = it[i - 1]
  
    # If immediate greater element does not
    # exists print it's immediate
    # smaller element
    if (i + 1 == len(it) ): 
        print(leftVal, end = " ");
        return;
      
    # Store the immediate
    # greater element
    rightVal = it[i + 1];
  
    # Print the closest number
    if (x - leftVal <= rightVal - x):
        print(leftVal, end = " ");
    else:
        print(rightVal, end = " ");
  
# Driver Code
  
# Given array
arr = [ 3, 3, 2, 4, 6, 5, 5, 1 ];
  
# Initialize set
streamNumbers = set()
  
# Print Answer
for i in range(len(arr)):
    # Function Call
    printClosest(streamNumbers, arr[i]);
  
# This code is contributed by phasing17.
 
 

C#




// C# program for the above approach
using System;
using System.Linq;
using System.Collections.Generic;
  
class GFG
{
  // Function to find the closest number on
  // the left side of x
  static void printClosest(SortedSet<int> streamNumbers, int x)
  {
  
    streamNumbers.Add(x);
    int rightVal, leftVal;
    // Insert the value in set and store
    // its position
    var it = streamNumbers.ToList();
    it.Sort();
  
    var i = it.IndexOf(x);
  
    // If x is the smallest element in set
    if (it[i] == it[0])
    {
      // If count of elements in the set
      // equal to 1
      if ( it.Count == 1)
      {
  
        Console.Write("-1 ");
        return;
      }
  
      // Otherwise, print its
      // immediate greater element
      rightVal = it[i + 1];
      Console.Write(rightVal + " ");
      return;
    }
  
    // Store its immediate smaller element
    leftVal = it[i - 1];
  
    // If immediate greater element does not
    // exists print it's immediate
    // smaller element
    if (i + 1 == it.Count ) {
      Console.Write(leftVal + " ");
      return;
    }
  
    // Store the immediate
    // greater element
    rightVal = it[i + 1];
  
    // Print the closest number
    if (x - leftVal <= rightVal - x)
      Console.Write(leftVal + " ");
    else
      Console.Write(rightVal + " ");
  }
  
  // Driver Code
  public static void Main(string[] args)
  {
    // Given array
    int[] arr = { 3, 3, 2, 4, 6, 5, 5, 1 };
  
    // Initialize set
    var streamNumbers = new SortedSet<int>();
  
    // Print Answer
    for (var i = 0; i < arr.Length; i++) 
    {
        
      // Function Call
      printClosest(streamNumbers, arr[i]);
    }
  }
}
  
// This code is contributed by phasing17.
 
 

Javascript




// JS program for the above approach
  
// Function to find the closest number on
// the left side of x
function printClosest(streamNumbers, x)
{
      
    streamNumbers.add(x);
      
    // Insert the value in set and store
    // its position
    let it = Array.from(streamNumbers)
     
    it.sort(function(a, b) {return a - b})
    let i = it.indexOf(x);
      
    // If x is the smallest element in set
    if (it[i] == it[0])
    {
        // If count of elements in the set
        // equal to 1
        if ( it.length == 1)
        {
  
            process.stdout.write("-1 ");
            return;
        }
  
        // Otherwise, print its
        // immediate greater element
        let rightVal = it[i + 1]
        process.stdout.write(rightVal + " ");
        return;
    }
  
    // Store its immediate smaller element
    let leftVal = it[i - 1]
  
    // If immediate greater element does not
    // exists print it's immediate
    // smaller element
    if (i + 1 == it.length ) {
        process.stdout.write(leftVal + " ");
        return;
    }
  
    // Store the immediate
    // greater element
    let rightVal = it[i + 1];
  
    // Print the closest number
    if (x - leftVal <= rightVal - x)
        process.stdout.write(leftVal + " ");
    else
        process.stdout.write(rightVal + " ");
}
  
// Driver Code
  
// Given array
let arr = [ 3, 3, 2, 4, 6, 5, 5, 1 ];
  
// Initialize set
let streamNumbers = new Set();
  
// Print Answer
for (var i = 0; i < arr.length; i++) {
    // Function Call
    printClosest(streamNumbers, arr[i]);
}
  
// This code is contributed by phasing17.
 
 
Output
-1 -1 3 3 4 4 4 2 

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



Next Article
Find the nearest perfect square for each element of the array

P

pratikraut0000
Improve
Article Tags :
  • Arrays
  • DSA
  • Hash
  • Mathematical
  • Searching
  • Technical Scripter
  • cpp-set
  • Technical Scripter 2020
Practice Tags :
  • Arrays
  • Hash
  • Mathematical
  • Searching

Similar Reads

  • Find the nearest power of 2 for every array element
    Given an array arr[] of size N, the task is to print the nearest power of 2 for each array element. Note: If there happens to be two nearest powers of 2, consider the larger one. Examples: Input: arr[] = {5, 2, 7, 12} Output: 4 2 8 16 Explanation: The nearest power of arr[0] ( = 5) is 4. The nearest
    4 min read
  • Find the nearest perfect square for each element of the array
    Given an array arr[] consisting of N positive integers, the task is to print the nearest perfect square for each array element. Examples: Input: arr[] = {5, 2, 7, 13}Output: 4 1 9 16Explanation:The nearest perfect square of arr[0] (= 5) is 4.The nearest perfect square of arr[1] (= 2) is 1.The neares
    5 min read
  • Nearest prime number in the array of every array element
    Given an integer array arr[] consisting of N integers, the task is to find the nearest Prime Number in the array for every element in the array. If the array does not contain any prime number, then print -1. Examples: Input: arr[] = {1, 2, 3, 1, 6} Output: 2 2 3 3 3 Explanation: For the subarray {1,
    11 min read
  • Find closest greater value for every element in array
    Given an array of integers, find the closest greater element for every element. If there is no greater element then print -1 Examples: Input : arr[] = {10, 5, 11, 6, 20, 12} Output : 11 6 12 10 -1 20 Input : arr[] = {10, 5, 11, 10, 20, 12} Output :z 11 10 12 11 -1 20 A simple solution is to run two
    4 min read
  • Replace all array elements with the nearest power of its previous element
    Given a circular array arr[] consisting of N integers, the task is to replace all the array elements with the nearest possible power of its previous adjacent element Examples: Input: arr[] = {2, 4, 6, 3, 11}Output: 1 4 4 6 9 Explanation:Power of 11 which is nearest to 2 ---> 110 = 1Power of 2 whi
    6 min read
  • Find closest value for every element in array
    Given an array of integers, find the closest element for every element. Examples: Input : arr[] = {10, 5, 11, 6, 20, 12} Output : 11 6 12 5 12 11 Input : arr[] = {10, 5, 11, 10, 20, 12} Output : 10 10 12 10 12 11 A simple solution is to run two nested loops. We pick an outer element one by one. For
    11 min read
  • Closest greater or same value on left side for every element in array
    Given an array arr[] of size n. For each element in the array, find the value wise closest element to its left that is greater than or equal to the current element. If no such element exists, return -1 for that position. Examples: Input : arr[] = [10, 5, 11, 6, 20, 12]Output : [-1, 10, -1, 10, -1, 2
    9 min read
  • Find closest smaller value for every element in array
    Given an array of integers, find the closest smaller element for every element. If there is no smaller element then print -1 Examples: Input : arr[] = {10, 5, 11, 6, 20, 12} Output : 6, -1, 10, 5, 12, 11 Input : arr[] = {10, 5, 11, 10, 20, 12} Output : 5 -1 10 5 12 11 A simple solution is to run two
    4 min read
  • Smallest element greater than X not present in the array
    Given an array arr[] of size N and an integer X. The task is to find the smallest element greater than X which is not present in the array. Examples: Input: arr[] = {1, 5, 10, 4, 7}, X = 4 Output: 6 6 is the smallest number greater than 4 which is not present in the array. Input: arr[] = {1, 5, 10,
    7 min read
  • Floor of every element in same array
    Given an array of integers, find the closest smaller or same element for every element. If all elements are greater for an element, then print -1. We may assume that the array has at least two elements. Examples: Input : arr[] = {10, 5, 11, 10, 20, 12} Output : 10 -1 10 10 12 11 Note that there are
    14 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences