Find minimum difference with adjacent elements in Array
Last Updated :
18 Sep, 2023
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
Find the only different element in an array
Given an array of integers where all elements are same except one element, find the only different element in the array. It may be assumed that the size of the array is at least two.Examples: Input : arr[] = {10, 10, 10, 20, 10, 10} Output : 3 arr[3] is the only different element.Input : arr[] = {30
10 min read
Minimum elements to be inserted in Array to make adjacent differences equal
Given an array of integers Arr[]. The elements of the array are sorted in increasing order. The task is to find the minimum number of elements to be inserted in the array so that the differences between any two consecutive elements are the same. Examples: Input: Arr[] = {1, 4, 13, 19, 25} Output: 4
8 min read
Find minimum difference between any two elements (pair) in given array
Given an unsorted array, find the minimum difference between any pair in the given array. Examples : Input: {1, 5, 3, 19, 18, 25}Output: 1Explanation: Minimum difference is between 18 and 19 Input: {30, 5, 20, 9}Output: 4Explanation: Minimum difference is between 5 and 9 Input: {1, 19, -4, 31, 38, 2
15+ min read
Minimize sum of adjacent difference with removal of one element from array
Given an array of positive integers of size greater than 2. The task is to find the minimum value of the sum of consecutive difference modulus of an array, i.e. the value of |A1-A0|+|A2-A1|+|A3-A2|+......+|An-1-An-2|+|An-A(n-1)| after removal of one element from the array, where An represents the nt
8 min read
Reduce given Array by replacing adjacent elements with their difference
Given an array arr[] consisting of N elements(such that N = 2k for some k ? 0), the task is to reduce the array and find the last remaining element after merging all elements into one. The array is reduced by performing the following operation: Merge the adjacent elements i.e merge elements at indic
5 min read
Minimum absolute difference of adjacent elements in a Circular Array
Given a circular array arr[] of length N, the task is to find the minimum absolute difference between any adjacent pair. If there are many optimum solutions, output any of them. Examples: Input: arr[] = {10, 12, 13, 15, 10} Output: 0Explanation: |10 - 10| = 0 is the minimum possible difference. Inpu
5 min read
Maximum difference between two elements in an Array
Given an array arr[] of N integers, the task is to find the maximum difference between any two elements of the array.Examples: Input: arr[] = {2, 1, 5, 3} Output: 4 |5 - 1| = 4 Input: arr[] = {-10, 4, -9, -5} Output: 14 Naive Approach:- As the maximum difference will be in between smallest and the l
9 min read
Maximize sum of absolute difference between adjacent elements in Array with sum K
Given two integers N and K, the task is to maximize the sum of absolute differences between adjacent elements of an array of length N and sum K. Examples: Input: N = 5, K = 10 Output: 20 Explanation: The array arr[] with sum 10 can be {0, 5, 0, 5, 0}, maximizing the sum of absolute difference of adj
4 min read
Maximum adjacent difference in an array in its sorted form
Given an array arr[] of size N, find the maximum difference between its two consecutive elements in its sorted form. Examples: Input: N = 3, arr[] = {1, 10, 5}Output: 5Explanation: Sorted array would be {1, 5, 10} and maximum adjacent difference would be 10 - 5 = 5 Input: N = 4, arr[] = {2, 4, 8, 11
8 min read
Queries to find minimum absolute difference between adjacent array elements in given ranges
Given an array arr[] consisting of N integers and an array query[] consisting of queries of the form {L, R}, the task for each query is to find the minimum of the absolute difference between adjacent elements over the range [L, R]. Examples: Input: arr[] = {2, 6, 1, 8, 3, 4}, query[] = {{0, 3}, {1,
15+ min read