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++
#include <bits/stdc++.h>
using namespace std;
vector< int > findDifferenceArray(vector< int >& arr)
{
int n = arr.size();
vector< int > res(n);
for ( int i = 0; i < n; i++) {
int leftMin = INT_MAX, rightMin = INT_MAX;
for ( int j = 0; j < i; j++)
leftMin = min(leftMin, arr[j]);
for ( int j = i + 1; j < n; j++)
rightMin = min(rightMin, arr[j]);
if (leftMin == INT_MAX)
leftMin = 0;
if (rightMin == INT_MAX)
rightMin = 0;
res[i] = leftMin - rightMin;
}
return res;
}
int main()
{
int N = 4;
vector< int > arr = { 8, 4, 2, 6 };
vector< int > ans = findDifferenceArray(arr);
for ( int i = 0; i < N; i++)
cout << ans[i] << " " ;
return 0;
}
|
Java
import java.util.*;
public class GFG {
public static List<Integer>
findDifferenceArray(List<Integer> arr)
{
int n = arr.size();
List<Integer> res = new ArrayList<Integer>(n);
for ( int i = 0 ; i < n; i++) {
int leftMin = Integer.MAX_VALUE,
rightMin = Integer.MAX_VALUE;
for ( int j = 0 ; j < i; j++)
leftMin = Math.min(leftMin, arr.get(j));
for ( int j = i + 1 ; j < n; j++)
rightMin = Math.min(rightMin, arr.get(j));
if (leftMin == Integer.MAX_VALUE)
leftMin = 0 ;
if (rightMin == Integer.MAX_VALUE)
rightMin = 0 ;
res.add(leftMin - rightMin);
}
return res;
}
public static void main(String[] args)
{
int N = 4 ;
List<Integer> arr = new ArrayList<Integer>(
Arrays.asList( 8 , 4 , 2 , 6 ));
List<Integer> ans = findDifferenceArray(arr);
for ( int i = 0 ; i < N; i++)
System.out.print(ans.get(i) + " " );
}
}
|
Python3
def find_difference_array(arr):
n = len (arr)
res = []
for i in range (n):
left_min = float ( 'inf' )
right_min = float ( 'inf' )
for j in range (i):
left_min = min (left_min, arr[j])
for j in range (i + 1 , n):
right_min = min (right_min, arr[j])
if left_min = = float ( 'inf' ):
left_min = 0
if right_min = = float ( 'inf' ):
right_min = 0
res.append(left_min - right_min)
return res
N = 4
arr = [ 8 , 4 , 2 , 6 ]
ans = find_difference_array(arr)
for i in range (N):
print (ans[i], end = " " )
|
C#
using System;
using System.Collections.Generic;
class GFG {
static List< int > FindDifferenceArray(List< int > arr)
{
int n = arr.Count;
List< int > res = new List< int >(n);
for ( int i = 0; i < n; i++) {
int leftMin = int .MaxValue, rightMin
= int .MaxValue;
for ( int j = 0; j < i; j++)
leftMin = Math.Min(leftMin, arr[j]);
for ( int j = i + 1; j < n; j++)
rightMin = Math.Min(rightMin, arr[j]);
if (leftMin == int .MaxValue)
leftMin = 0;
if (rightMin == int .MaxValue)
rightMin = 0;
res.Add(leftMin - rightMin);
}
return res;
}
static void Main()
{
List< int > arr = new List< int >{ 8, 4, 2, 6 };
List< int > ans = FindDifferenceArray(arr);
foreach ( int diff in ans) Console.Write(diff + " " );
Console.WriteLine();
}
}
|
Javascript
function findDifferenceArray(arr) {
const n = arr.length;
const res = new Array(n);
for (let i = 0; i < n; i++) {
let leftMin = Infinity;
let rightMin = Infinity;
for (let j = 0; j < i; j++)
leftMin = Math.min(leftMin, arr[j]);
for (let j = i + 1; j < n; j++)
rightMin = Math.min(rightMin, arr[j]);
if (leftMin === Infinity)
leftMin = 0;
if (rightMin === Infinity)
rightMin = 0;
res[i] = leftMin - rightMin;
}
return res;
}
const arr = [8, 4, 2, 6];
const ans = findDifferenceArray(arr);
for (let i = 0; i < arr.length; i++)
console.log(ans[i]);
|
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++
#include <bits/stdc++.h>
using namespace std;
void findDifferenceArray( int N, vector< int >& A)
{
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;
for ( auto a : m) {
up = a.first;
break ;
}
if (i == 0) {
v.push_back(0 - up);
}
else {
v.push_back(minn - up);
}
minn = min(minn, A[i]);
i++;
}
for ( auto a : v) {
cout << a << " " ;
}
}
int main()
{
int N = 4;
vector< int > A = { 8, 4, 2, 6 };
findDifferenceArray(N, A);
return 0;
}
|
Java
import java.io.*;
class GFG {
public static int [] findDifferenceArray( int N, int A[])
{
int res[] = new int [N];
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];
for ( int i = N - 2 ; i >= 0 ; i--) {
mini = Math.min(mini, A[i + 1 ]);
right[i] = mini;
}
for ( int i = 1 ; i < N; i++) {
mini1 = Math.min(mini1, A[i - 1 ]);
left[i] = mini1;
}
for ( int i = 0 ; i < N; i++) {
res[i] = left[i] - right[i];
}
return res;
}
public static void main(String[] args)
{
int N = 4 ;
int A[] = { 8 , 4 , 2 , 6 };
int [] result = findDifferenceArray(N, A);
for ( int i = 0 ; i < N; i++) {
System.out.print(result[i] + " " );
}
}
}
|
Python3
class GFG:
@staticmethod
def findDifferenceArray(N, A):
res = [ 0 ] * N
if N = = 1 :
return res
mini = float ( 'inf' )
mini1 = float ( 'inf' )
left = [ 0 ] * N
right = [ 0 ] * N
for i in range (N - 2 , - 1 , - 1 ):
mini = min (mini, A[i + 1 ])
right[i] = mini
for i in range ( 1 , N):
mini1 = min (mini1, A[i - 1 ])
left[i] = mini1
for i in range (N):
res[i] = left[i] - right[i]
return res
@staticmethod
def main():
N = 4
A = [ 8 , 4 , 2 , 6 ]
result = GFG.findDifferenceArray(N, A)
for i in range (N):
print (result[i], end = " " )
GFG.main()
|
C#
using System;
public class GFG {
static int [] findDifferenceArray( int N, int [] A)
{
int [] res = new int [N];
if (N == 1) {
return res;
}
int mini = Int32.MaxValue;
int mini1 = Int32.MaxValue;
int [] left = new int [N];
int [] right = new int [N];
for ( int i = N - 2; i >= 0; i--) {
mini = Math.Min(mini, A[i + 1]);
right[i] = mini;
}
for ( int i = 1; i < N; i++) {
mini1 = Math.Min(mini1, A[i - 1]);
left[i] = mini1;
}
for ( int i = 0; i < N; i++) {
res[i] = left[i] - right[i];
}
return res;
}
static public void Main()
{
int N = 4;
int [] A = { 8, 4, 2, 6 };
int [] result = findDifferenceArray(N, A);
for ( int i = 0; i < N; i++) {
Console.Write(result[i] + " " );
}
}
}
|
Javascript
class GFG {
static findDifferenceArray(N, A) {
let res = new Array(N);
if (N === 1) {
return res;
}
let mini = Number.MAX_SAFE_INTEGER;
let mini1 = Number.MAX_SAFE_INTEGER;
let left = new Array(N);
let right = new Array(N);
for (let i = N - 2; i >= 0; i--)
{
mini = Math.min(mini, A[i + 1]);
right[i] = mini;
}
for (let i = 1; i < N; i++)
{
mini1 = Math.min(mini1, A[i - 1]);
left[i] = mini1;
}
for (let i = 0; i < N; i++)
{
res[i] = left[i] - right[i];
}
return res;
}
static main()
{
let N = 4;
let A = [8, 4, 2, 6];
let result = GFG.findDifferenceArray(N, A);
for (let i = 0; i < N; i++) {
console.log(result[i] + " " );
}
}
}
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...