Find closest value for every element in array - GeeksforGeeks

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 TreeSetimport 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);    }}
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.
java-TreeMap
Self-Balancing-BST
Arrays
Binary Search Tree
Sorting
Arrays
Sorting
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Introduction to Arrays
Maximum and minimum of an array using minimum number of comparisons
Python | Using 2D arrays/lists the right way
Linked List vs Array
Binary Search Tree | Set 1 (Search and Insertion)
AVL Tree | Set 1 (Insertion)
Binary Search Tree | Set 2 (Delete)
A program to check if a binary tree is BST or not
Sorted Array to Balanced BST