Find closest value for every element in array
Last Updated :
11 Jul, 2025
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 every picked element, we traverse the remaining array and find the closest element. The time complexity of this solution is O(N2).
Steps:
1. Create a base case in which if the size of the
‘vec’ array is one print -1;
2.create a nested iterations using the ‘for’ loop with the help of
‘i’ and ‘j’ variables.
3. Take two variables to store the abs() difference and closest
element for an element.
4. In the second ‘for’ loop, assign the value at the ‘jth’
position of the ‘vec’ vector, if that element is close to
the respective element.
5.Print the closest element.
Implementation of above approach :
C++
// C++ code of "Find closest value for every element in
// array"
#include <bits/stdc++.h>
using namespace std;
void getResult(vector<int> vec, int n)
{
if (n <= 1) {
cout << "-1" << endl;
return;
}
for (int i = 0; i < n; i++) {
int mini = INT_MAX;
int mini_diff = INT_MAX;
for (int j = 0; j < n; j++) {
if ((i ^ j)) {
int temp
= abs(vec[i] - vec[j]); // finding diff
if (temp < mini_diff) {
// checking its minimum or not!
mini = vec[j];
mini_diff = temp;
}
}
}
cout << mini << " "; // printing the closest
// elemtent
}
return;
}
int main()
{
vector<int> vec = { 10, 5, 11, 6, 20, 12, 10};
int n = vec.size(); // size of array
cout << "vec Array:- ";
for (int i = 0; i < n; i++) {
cout << vec[i] << " "; // intital array
}
cout << endl;
cout << "Resultant Array:- ";
getResult(vec, n); // final array or result array
}
// code is contributed by kg_codex
Python3
import sys
def get_result(arr, n):
if n <= 1:
print("-1")
return
for i in range(n):
mini = sys.maxsize
mini_diff = sys.maxsize
for j in range(n):
if i != j:
temp = abs(arr[i] - arr[j]) # finding diff
if temp < mini_diff: # checking its minimum or not!
mini = arr[j]
mini_diff = temp
print(mini, end=" ") # printing the closest element
return
if __name__ == "__main__":
arr = [10, 5, 11, 6, 20, 12, 10]
n = len(arr)
print("vec Array:-", end=" ")
for i in range(n):
print(arr[i], end=" ") # initial array
print()
print("Resultant Array:-", end=" ")
get_result(arr, n) # final array or result array
Java
import java.util.*;
public class Main {
public static void getResult(List<Integer> vec, int n)
{
if (n <= 1) {
System.out.println("-1");
return;
}
for (int i = 0; i < n; i++) {
int mini = Integer.MAX_VALUE;
int mini_diff = Integer.MAX_VALUE;
for (int j = 0; j < n; j++) {
if ((i ^ j) != 0) {
int temp
= Math.abs(vec.get(i) - vec.get(j));
if (temp < mini_diff) {
mini = vec.get(j);
mini_diff = temp;
}
}
}
System.out.print(mini + " ");
}
}
public static void main(String[] args)
{
List<Integer> vec
= Arrays.asList(10, 5, 11, 6, 20, 12, 10);
int n = vec.size();
System.out.print("vec Array:- ");
for (int i = 0; i < n; i++) {
System.out.print(vec.get(i) + " ");
}
System.out.println("\nResultant Array:- ");
getResult(vec, n);
}
}
C#
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<int> vec = new List<int>{ 10, 5, 11, 6, 20, 12, 10 };
int n = vec.Count; // size of array
Console.Write("vec Array:- ");
for (int i = 0; i < n; i++) {
Console.Write(vec[i] + " "); // intital array
}
Console.WriteLine();
Console.Write("Resultant Array:- ");
GetResult(vec, n); // final array or result array
}
static void GetResult(List<int> vec, int n)
{
if (n <= 1) {
Console.WriteLine("-1");
return;
}
for (int i = 0; i < n; i++) {
int mini = int.MaxValue;
int mini_diff = int.MaxValue;
for (int j = 0; j < n; j++) {
if ((i ^ j) != 0) {
int temp = Math.Abs(vec[i] - vec[j]); // finding diff
if (temp < mini_diff) {
// checking its minimum or not!
mini = vec[j];
mini_diff = temp;
}
}
}
Console.Write(mini + " "); // printing the closest elemtent
}
}
}
JavaScript
function getResult(vec) {
const n = vec.length;
if (n <= 1) {
console.log("-1");
return;
}
for (let i = 0; i < n; i++) {
let mini = Number.MAX_SAFE_INTEGER;
let mini_diff = Number.MAX_SAFE_INTEGER;
for (let j = 0; j < n; j++) {
if (i !== j) {
const temp = Math.abs(vec[i] - vec[j]);
if (temp < mini_diff) {
mini = vec[j];
mini_diff = temp;
}
}
}
process.stdout.write(mini + " ");
}
console.log("");
}
const vec = [10, 5, 11, 6, 20, 12, 10];
console.log("vec Array:- " + vec.join(" "));
console.log("Resultant Array:- ");
getResult(vec);
Outputvec Array:- 10 5 11 6 20 12 10
Resultant Array:- 10 6 10 5 12 11 10
Time Complexity: O(N2)
Auxiliary Space: O(1)
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.
Implementation:
C++
// C++ program to demonstrate insertions in set
#include <iostream>
#include <set>
#include <map>
using namespace std;
void closestGreater(int arr[], int n)
{
if (n == -1) {
cout << -1 << " ";
return;
}
// Insert all array elements into a map.
// A map value indicates whether an element
// appears once or more.
map<int, bool> mp;
for (int i = 0; i < n; i++) {
// A value "True" means that the key
// appears more than once.
if (mp.find(arr[i]) != mp.end())
mp[arr[i]] = true;
else
mp[arr[i]] = false;
}
// Find smallest greater element for every
// array element
for (int i = 0; i < n; i++) {
// If there are multiple occurrences
if (mp[arr[i]] == true)
{
cout << arr[i] << " ";
continue;
}
// If element appears only once
int greater = 0, lower = 0;
auto it = mp.upper_bound(arr[i]);
if (it != mp.end())
greater = it->first;
it = mp.lower_bound(arr[i]);
if (it != mp.begin()) {
--it;
lower = it->first;
}
if (greater == 0)
cout << lower << " ";
else if (lower == 0)
cout << greater << " ";
else {
int d1 = greater - arr[i];
int d2 = arr[i] - lower;
if (d1 > d2)
cout << lower << " ";
else
cout << greater << " ";
}
}
}
int main()
{
int arr[] = { 10, 5, 11, 6, 20, 12, 10 };
int n = sizeof(arr) / sizeof(arr[0]);
closestGreater(arr, n);
return 0;
}
//This code is contributed by shivamsharma215
Java
// 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);
}
}
Python3
from collections import defaultdict
def closest_greater(arr):
if len(arr) == 0:
print("-1", end=" ")
return
# Insert all array elements into a dictionary.
# A dictionary value indicates whether an element
# appears once or more.
d = defaultdict(int)
for i in range(len(arr)):
d[arr[i]] += 1
# Find smallest greater element for every array element
for i in range(len(arr)):
# If there are multiple occurrences
if d[arr[i]] > 1:
print(arr[i], end=" ")
continue
# If element appears only once
greater = None
lower = None
for key in sorted(d.keys()):
if key > arr[i]:
greater = key
break
elif key < arr[i]:
lower = key
if greater is None:
print(lower, end=" ")
elif lower is None:
print(greater, end=" ")
else:
d1 = greater - arr[i]
d2 = arr[i] - lower
if d1 > d2:
print(lower, end=" ")
else:
print(greater, end=" ")
if __name__ == "__main__":
arr = [10, 5, 11, 6, 20, 12, 10]
closest_greater(arr)
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int[] arr = { 10, 5, 11, 6, 20, 12, 10 };
ClosestGreater(arr);
}
static void ClosestGreater(int[] arr)
{
if (arr.Length == 0)
{
Console.Write("-1 ");
return;
}
// Insert all array elements into a dictionary.
// A dictionary value indicates whether an element
// appears once or more.
var dict = new Dictionary<int, int>();
foreach (int num in arr)
{
if (dict.ContainsKey(num))
{
dict[num]++;
}
else
{
dict[num] = 1;
}
}
// Find smallest greater element for every array element
foreach (int num in arr)
{
// If there are multiple occurrences
if (dict[num] > 1)
{
Console.Write(num + " ");
continue;
}
// If element appears only once
int? greater = null;
int? lower = null;
foreach (int key in dict.Keys.OrderBy(x => x))
{
if (key > num)
{
greater = key;
break;
}
else if (key < num)
{
lower = key;
}
}
if (greater == null)
{
Console.Write(lower + " ");
}
else if (lower == null)
{
Console.Write(greater + " ");
}
else
{
int d1 = greater.Value - num;
int d2 = num - lower.Value;
if (d1 > d2)
{
Console.Write(lower + " ");
}
else
{
Console.Write(greater + " ");
}
}
}
}
}
JavaScript
function closestGreater(arr) {
if (arr.length === 0) {
console.log(-1 + " ");
return;
}
// Insert all array elements into a Map.
// A Map value indicates whether an element
// appears once or more.
let map = new Map();
for (let i = 0; i < arr.length; i++) {
// A value "true" means that the key
// appears more than once.
if (map.has(arr[i]))
map.set(arr[i], true);
else
map.set(arr[i], false);
}
// Find smallest greater element for every
// array element
for (let i = 0; i < arr.length; i++) {
// If there are multiple occurrences
if (map.get(arr[i]) === true) {
console.log(arr[i] + " ");
continue;
}
// If element appears only once
let greater = null, lower = null;
for (let [key, value] of map) {
if (key > arr[i]) {
if (!greater || key < greater)
greater = key;
} else if (key < arr[i]) {
if (!lower || key > lower)
lower = key;
}
}
if (greater === null)
console.log(lower + " ");
else if (lower === null)
console.log(greater + " ");
else {
let d1 = greater - arr[i];
let d2 = arr[i] - lower;
if (d1 > d2)
console.log(lower + " ");
else
console.log(greater + " ");
}
}
}
let arr = [10, 5, 11, 6, 20, 12, 10];
closestGreater(arr);
Output:10 6 12 5 12 11 10
Time Complexity:
- The first loop for inserting all the elements into the TreeMap takes O(nlog(n)) time because TreeMap uses a Red-Black tree internally to store the elements, and insertion takes O(log(n)) time in the average case, and since there are 'n' elements in the array, the total time complexity for inserting all elements into the TreeMap is O(nlog(n)).
- The second loop for finding the smallest greater element for each array element takes O(nlog(n)) time because the TreeMap provides the higherKey() and lowerKey() methods that take O(log(n)) time in the average case to find the keys greater than and less than the given key, respectively. Since we are calling these methods 'n' times, the total time complexity for finding the smallest greater element for each array element is O(nlog(n)).
Therefore, the overall time complexity of the algorithm is O(n*log(n)).
Auxiliary Space:
- The algorithm uses a TreeMap to store the array elements, which takes O(n) space because each element takes O(1) space, and there are 'n' elements in the array.
- Therefore, the overall auxiliary space complexity of the algorithm is O(n).
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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem