Skip to content
Related Articles

Related Articles

Improve Article

Find closest value for every element in array

  • Difficulty Level : Medium
  • Last Updated : 02 Dec, 2018

Given an array of integers, find the closest element for every element.

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 nested loops. We pick an outer element one by one. For every picked element, we traverse remaining array and find closest element. Time complexity of this solution is O(n*n)



An efficient solution is to use Self Balancing BST (Implemented as set in C++ and TreeSet in Java). In a Self Balancing BST, we can do both insert and closest greater operations in O(Log n) time.




// Java program to demonstrate insertions in TreeSet
import java.util.*;
  
class TreeSetDemo {
    public static void closestGreater(int[] arr)
    {
        if (arr.length == -1) {
            System.out.print(-1 + " ");
            return;
        }
  
        // Insert all array elements into a TreeMap.
        // A TreeMap value indicates whether an element
        // appears once or more.
        TreeMap<Integer, Boolean> tm = 
                    new TreeMap<Integer, Boolean>();
        for (int i = 0; i < arr.length; i++) {
  
            // A value "True" means that the key
            // appears more than once.
            if (tm.containsKey(arr[i]))
                tm.put(arr[i], true);
            else
                tm.put(arr[i], false);
        }
  
        // Find smallest greater element for every
        // array element
        for (int i = 0; i < arr.length; i++) {
  
            // If there are multiple occurrences
            if (tm.get(arr[i]) == true)
            {
                System.out.print(arr[i] + " ");
                continue;
            }
  
            // If element appears only once
            Integer greater = tm.higherKey(arr[i]);
            Integer lower = tm.lowerKey(arr[i]);
            if (greater == null)
                System.out.print(lower + " ");
            else if (lower == null)
                System.out.print(greater + " ");
            else {
                int d1 = greater - arr[i];
                int d2 = arr[i] - lower;
                if (d1 > d2)
                    System.out.print(lower + " ");
                else
                    System.out.print(greater + " ");
            }
        }
    }
  
    public static void main(String[] args)
    {
        int[] arr = { 10, 5, 11, 6, 20, 12, 10 };
        closestGreater(arr);
    }
}
Output:
10 6 12 5 12 11 10

Exercise : Another efficient solution is to use sorting that also works in O(n Log n) time. Write complete algorithm and code for sorting based solution.

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :