Open In App

Find minimum difference with adjacent elements in Array

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:

Below is the implementation for the above approach:




// 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 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) + " ");
    }
}




# 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




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




// 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

Output
-2 6 -2 2 






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++ 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;
}




/*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] + " ");
        }
    }
}




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# 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.




// 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] + " ");
    }
  }
}

Output
-2 6 -2 2 






Time Complexity: O(N)
Auxiliary Space: O(N)


Article Tags :