Find minimum difference with adjacent elements in Array
Last Updated :
23 Jul, 2025
Given an array A[] of N integers, the task is to find min(A[0], A[1], ..., A[i-1]) - min(A[i+1], A[i+2], ..., A[n-1]) for each i (1 ≤ i ≤ N).
Note: If there are no elements at the left or right of i then consider the minimum element towards that part zero.
Examples:
Input: N = 4, A = {8, 4, 2, 6}
Output: -2 6 -2 2
Input: N = 1, A = {55}
Output: 0
Approach 1: Bruteforce (Naive Approach)
The brute force approach calculates the difference between the left and right subarrays minimum of each element in the input array by iterating through the array arr[] and getting the minimum of the elements to the left and right of each element separately. This approach has a time complexity of O(N^2), where N is the size of the input array.
Below are the steps involved in the implementation of the code:
- Create an empty array res to store the absolute difference for each element of the input array.
- Iterate through the input array arr, and for each element arr[i], do the following:
- Create two variables leftMin and rightMin, both initialized to the maximum value of an integer. These variables will store the minimum of the elements to the left and to the right of the current element, respectively.
- Calculate the left Min by iterating from the first element of the array up to arr[i]-1 and comparing each element to leftMin. if leftMin is greater than the current element update leftMin.
- Calculate the right Min by iterating from arr[i]+1 up to the last element of the array and comparing each element to rightMin. if rightMin is greater than the current element update rightMin.
- If leftMin == INT_MAX (maximum value of integer) means there is no element on the left side so set leftMin=0
- If rightMin == INT_MAX (maximum value of integer) means there is no element on the right side so set rightMin=0
- Calculate the difference between leftMin and rightMin using (leftMin – rightMin).
- Add the difference to the result array res[].
- Return the result array.
Below is the implementation for the above approach:
C++
// C++ Implementation
#include <bits/stdc++.h>
using namespace std;
// Function to find difference array
vector<int> findDifferenceArray(vector<int>& arr)
{
int n = arr.size();
vector<int> res(n);
// Iterate in array arr[]
for (int i = 0; i < n; i++) {
int leftMin = INT_MAX, rightMin = INT_MAX;
// calculate left minimum
for (int j = 0; j < i; j++)
leftMin = min(leftMin, arr[j]);
// calculate right minimum
for (int j = i + 1; j < n; j++)
rightMin = min(rightMin, arr[j]);
// means there is no element in left side
if (leftMin == INT_MAX)
leftMin = 0;
// means there is no element in right side
if (rightMin == INT_MAX)
rightMin = 0;
// add difference to result array
res[i] = leftMin - rightMin;
}
return res;
}
// Driver code
int main()
{
int N = 4;
vector<int> arr = { 8, 4, 2, 6 };
// Function call
vector<int> ans = findDifferenceArray(arr);
for (int i = 0; i < N; i++)
cout << ans[i] << " ";
return 0;
}
Java
// Java Implementation
import java.util.*;
public class GFG {
// Function to find difference array
public static List<Integer>
findDifferenceArray(List<Integer> arr)
{
int n = arr.size();
List<Integer> res = new ArrayList<Integer>(n);
// Iterate in array arr[]
for (int i = 0; i < n; i++) {
int leftMin = Integer.MAX_VALUE,
rightMin = Integer.MAX_VALUE;
// calculate left minimum
for (int j = 0; j < i; j++)
leftMin = Math.min(leftMin, arr.get(j));
// calculate right minimum
for (int j = i + 1; j < n; j++)
rightMin = Math.min(rightMin, arr.get(j));
// means there is no element in left side
if (leftMin == Integer.MAX_VALUE)
leftMin = 0;
// means there is no element in right side
if (rightMin == Integer.MAX_VALUE)
rightMin = 0;
// add difference to result array
res.add(leftMin - rightMin);
}
return res;
}
// Driver code
public static void main(String[] args)
{
int N = 4;
List<Integer> arr = new ArrayList<Integer>(
Arrays.asList(8, 4, 2, 6));
// Function call
List<Integer> ans = findDifferenceArray(arr);
for (int i = 0; i < N; i++)
System.out.print(ans.get(i) + " ");
}
}
Python3
# Python Implementation
# Function to find difference array
def find_difference_array(arr):
n = len(arr)
res = []
# Iterate in array arr[]
for i in range(n):
left_min = float('inf')
right_min = float('inf')
# calculate left minimum
for j in range(i):
left_min = min(left_min, arr[j])
# calculate right minimum
for j in range(i + 1, n):
right_min = min(right_min, arr[j])
# means there is no element in left side
if left_min == float('inf'):
left_min = 0
# means there is no element in right side
if right_min == float('inf'):
right_min = 0
# add difference to result array
res.append(left_min - right_min)
return res
# Driver code
N = 4
arr = [8, 4, 2, 6]
# Function call
ans = find_difference_array(arr)
for i in range(N):
print(ans[i], end=" ")
# This code is contributed by Pushpesh Raj
C#
using System;
using System.Collections.Generic;
class GFG {
// Function to find difference array
static List<int> FindDifferenceArray(List<int> arr)
{
int n = arr.Count;
List<int> res = new List<int>(n);
// Iterate in array arr[]
for (int i = 0; i < n; i++) {
int leftMin = int.MaxValue, rightMin
= int.MaxValue;
// calculate left minimum
for (int j = 0; j < i; j++)
leftMin = Math.Min(leftMin, arr[j]);
// calculate right minimum
for (int j = i + 1; j < n; j++)
rightMin = Math.Min(rightMin, arr[j]);
// means there is no element on the left side
if (leftMin == int.MaxValue)
leftMin = 0;
// means there is no element on the right side
if (rightMin == int.MaxValue)
rightMin = 0;
// add the difference to the result array
res.Add(leftMin - rightMin);
}
return res;
}
// Driver code
static void Main()
{
List<int> arr = new List<int>{ 8, 4, 2, 6 };
// Function call
List<int> ans = FindDifferenceArray(arr);
foreach(int diff in ans) Console.Write(diff + " ");
Console.WriteLine();
}
}
// This code is contributed by shivamgupta310570
JavaScript
// Function to find difference array
function findDifferenceArray(arr) {
const n = arr.length;
const res = new Array(n);
// Iterate through array arr[]
for (let i = 0; i < n; i++) {
let leftMin = Infinity;
let rightMin = Infinity;
// Calculate left minimum
for (let j = 0; j < i; j++)
leftMin = Math.min(leftMin, arr[j]);
// Calculate right minimum
for (let j = i + 1; j < n; j++)
rightMin = Math.min(rightMin, arr[j]);
// Means there is no element on the left side
if (leftMin === Infinity)
leftMin = 0;
// Means there is no element on the right side
if (rightMin === Infinity)
rightMin = 0;
// Add difference to the result array
res[i] = leftMin - rightMin;
}
return res;
}
// Driver code
const arr = [8, 4, 2, 6];
// Function call
const ans = findDifferenceArray(arr);
for (let i = 0; i < arr.length; i++)
console.log(ans[i]);
// This code is contributed by Aditi Tyagi
Time complexity: O(N^2)
Auxiliary Space: O(1)
Approach 2: This can be solved with the following idea:
Store all the elements in map and start iterating in array. Get the first element of map as smallest element from right subarray and maintain a minima for left subarray.
Below is the implementation of the above approach:
C++
// C++ Implementation
#include <bits/stdc++.h>
using namespace std;
// Function to find difference array
void findDifferenceArray(int N, vector<int>& A)
{
// Map Intialisation
map<int, int> m;
int i = 0;
while (i < A.size()) {
m[A[i]]++;
i++;
}
int minn = INT_MAX;
i = 0;
vector<int> v;
while (i < A.size()) {
m[A[i]]--;
if (m[A[i]] == 0) {
m.erase(A[i]);
}
int up = 0;
// Minimum element from
// right subarray
for (auto a : m) {
up = a.first;
break;
}
if (i == 0) {
v.push_back(0 - up);
}
else {
v.push_back(minn - up);
}
// Minimum from left subarray
minn = min(minn, A[i]);
i++;
}
for (auto a : v) {
cout << a << " ";
}
}
// Driver code
int main()
{
int N = 4;
vector<int> A = { 8, 4, 2, 6 };
// Function call
findDifferenceArray(N, A);
return 0;
}
Java
/*package whatever // do not write package name here */
import java.io.*;
class GFG {
public static int[] findDifferenceArray(int N, int A[])
{
// store the result in res[]
int res[] = new int[N];
// If there is only one element than return 0
if (N == 1)
return res;
int mini = Integer.MAX_VALUE;
int mini1 = Integer.MAX_VALUE;
int[] left = new int[N];
int[] right = new int[N];
// right vector store the suffix minimum value till
// ith element
for (int i = N - 2; i >= 0; i--) {
mini = Math.min(mini, A[i + 1]);
right[i] = mini;
}
// left vector store the prefix minimum value till
// ith element
for (int i = 1; i < N; i++) {
mini1 = Math.min(mini1, A[i - 1]);
left[i] = mini1;
}
// left_min[]-right_min[]
for (int i = 0; i < N; i++) {
res[i] = left[i] - right[i];
}
// return result in res array
return res;
}
public static void main(String[] args)
{
int N = 4;
int A[] = { 8, 4, 2, 6 };
// result has min(0, ..i-1)-min(i+1, ..N-1)
int[] result = findDifferenceArray(N, A);
// print the result array value
for (int i = 0; i < N; i++) {
System.out.print(result[i] + " ");
}
}
}
Python3
class GFG:
@staticmethod
def findDifferenceArray(N, A):
# store the result in res[]
res = [0] * N
# If there is only one element than return 0
if N == 1:
return res
mini = float('inf')
mini1 = float('inf')
left = [0] * N
right = [0] * N
# right vector store the suffix minimum value till
# ith element
for i in range(N - 2, -1, -1):
mini = min(mini, A[i + 1])
right[i] = mini
# left vector store the prefix minimum value till
# ith element
for i in range(1, N):
mini1 = min(mini1, A[i - 1])
left[i] = mini1
# left_min[]-right_min[]
for i in range(N):
res[i] = left[i] - right[i]
# return result in res array
return res
@staticmethod
def main():
N = 4
A = [8, 4, 2, 6]
# result has min(0, ..i-1)-min(i+1, ..N-1)
result = GFG.findDifferenceArray(N, A)
# print the result array value
for i in range(N):
print(result[i], end=" ")
GFG.main()
C#
// C# code implementation:
using System;
public class GFG {
static int[] findDifferenceArray(int N, int[] A)
{
// store the result in res[]
int[] res = new int[N];
// If there is only one element than return 0
if (N == 1) {
return res;
}
int mini = Int32.MaxValue;
int mini1 = Int32.MaxValue;
int[] left = new int[N];
int[] right = new int[N];
// right vector store the suffix minimum value till
// ith element
for (int i = N - 2; i >= 0; i--) {
mini = Math.Min(mini, A[i + 1]);
right[i] = mini;
}
// left vector store the prefix minimum value till
// ith element
for (int i = 1; i < N; i++) {
mini1 = Math.Min(mini1, A[i - 1]);
left[i] = mini1;
}
// left_min[]-right_min[]
for (int i = 0; i < N; i++) {
res[i] = left[i] - right[i];
}
// return result in res array
return res;
}
static public void Main()
{
// Code
int N = 4;
int[] A = { 8, 4, 2, 6 };
// result has min(0, ..i-1)-min(i+1, ..N-1)
int[] result = findDifferenceArray(N, A);
// print the result array value
for (int i = 0; i < N; i++) {
Console.Write(result[i] + " ");
}
}
}
// This code is contributed by sankar.
JavaScript
// Define a class GFG
class GFG {
// Define a static method called
// findDifferenceArray that takes
// an integer N and an integer array
// A as input and returns an integer array
static findDifferenceArray(N, A) {
// Create an empty integer array called res with length N
let res = new Array(N);
// If the length of the array is 1, return an empty array res
if (N === 1) {
return res;
}
// Initialize mini and mini1 as the maximum integer value
let mini = Number.MAX_SAFE_INTEGER;
let mini1 = Number.MAX_SAFE_INTEGER;
// Create two empty integer arrays
// called left and right with length N
let left = new Array(N);
let right = new Array(N);
// right vector store the suffix minimum value till ith element
for (let i = N - 2; i >= 0; i--)
{
// Calculate the minimum value from
// the i+1th element to the end of the array A
mini = Math.min(mini, A[i + 1]);
// Store the minimum value in the right array at the ith index
right[i] = mini;
}
// left vector store the prefix minimum value till ith element
for (let i = 1; i < N; i++)
{
// Calculate the minimum value from
// the beginning of the array A to the ith element
mini1 = Math.min(mini1, A[i - 1]);
// Store the minimum value in the left array at the ith index
left[i] = mini1;
}
// left_min[]-right_min[]
for (let i = 0; i < N; i++)
{
// Calculate the difference between
// the ith index of the left array and
// the ith index of the right array and
// store it in the ith index of the res array
res[i] = left[i] - right[i];
}
// Return the res array
return res;
}
// Define a static method called main that
// does not return a value and takes no arguments
static main()
{
// Initialize N to 4 and A to
// an integer array containing 8, 4, 2, and 6
let N = 4;
let A = [8, 4, 2, 6];
// Set the result equal to the result of
// calling findDifferenceArray with N and A as arguments
let result = GFG.findDifferenceArray(N, A);
// Print each element of the result array separated by a space
for (let i = 0; i < N; i++) {
console.log(result[i] + " ");
}
}
}
Time Complexity: O(N)
Auxiliary Space: O(N)
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