Minimum difference between adjacent elements of array which contain elements from each row of a matrix
Last Updated :
27 Mar, 2023
Given a matrix of N rows and M columns, the task is to find the minimum absolute difference between any of the two adjacent elements of an array of size N, which is created by picking one element from each row of the matrix. Note the element picked from row 1 will become arr[0], element picked from row 2 will become arr[1] and so on.
Examples:
Input : N = 2, M = 2
m[2][2] = { 8, 2,
6, 8 }
Output : 0.
Picking 8 from row 1 and picking 8 from row 2, we create an array { 8, 8 } and minimum
difference between any of adjacent element is 0.
Input : N = 3, M = 3
m[3][3] = { 1, 2, 3
4, 5, 6
7, 8, 9 }
Output : 1.
The idea is to sort all rows individually and then do binary search to find the closest element in next row for each element.
To do this in an efficient manner, sort each row of the matrix. Starting from row 1 to row N - 1 of matrix, for each element m[i][j] of current row in the matrix, find the smallest element in the next row which is greater than or equal to the current element, say p and the largest element which is smaller than the current element, say q. This can be done using Binary Search. Finally,find the minimum of the difference of current element from p and q and update the variable.
Below is implementation of this approach:
C++
// C++ program to find the minimum absolute difference
// between any of the adjacent elements of an array
// which is created by picking one element from each
// row of the matrix.
#include<bits/stdc++.h>
using namespace std;
#define R 2
#define C 2
// Return smallest element greater than or equal
// to the current element.
int bsearch(int low, int high, int n, int arr[])
{
int mid = (low + high)/2;
if(low <= high)
{
if(arr[mid] < n)
return bsearch(mid +1, high, n, arr);
return bsearch(low, mid - 1, n, arr);
}
return low;
}
// Return the minimum absolute difference adjacent
// elements of array
int mindiff(int arr[R][C], int n, int m)
{
// Sort each row of the matrix.
for (int i = 0; i < n; i++)
sort(arr[i], arr[i] + m);
int ans = INT_MAX;
// For each matrix element
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < m; j++)
{
// Search smallest element in the next row which
// is greater than or equal to the current element
int p = bsearch(0, m-1, arr[i][j], arr[i + 1]);
ans = min(ans, abs(arr[i + 1][p] - arr[i][j]));
// largest element which is smaller than the current
// element in the next row must be just before
// smallest element which is greater than or equal
// to the current element because rows are sorted.
if (p-1 >= 0)
ans = min(ans, abs(arr[i + 1][p - 1] - arr[i][j]));
}
}
return ans;
}
// Driven Program
int main()
{
int m[R][C] =
{
8, 5,
6, 8,
};
cout << mindiff(m, R, C) << endl;
return 0;
}
Java
// Java program to find the minimum
// absolute difference between any
// of the adjacent elements of an
// array which is created by picking
// one element from each row of the matrix
import java.util.Arrays;
class GFG
{
static final int R=2;
static final int C=2;
// Return smallest element greater than
// or equal to the current element.
static int bsearch(int low, int high, int n, int arr[])
{
int mid = (low + high)/2;
if(low <= high)
{
if(arr[mid] < n)
return bsearch(mid +1, high, n, arr);
return bsearch(low, mid - 1, n, arr);
}
return low;
}
// Return the minimum absolute difference adjacent
// elements of array
static int mindiff(int arr[][], int n, int m)
{
// Sort each row of the matrix.
for (int i = 0; i < n; i++)
Arrays.sort(arr[i]);
int ans = +2147483647;
// For each matrix element
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < m; j++)
{
// Search smallest element in the
// next row which is greater than
// or equal to the current element
int p = bsearch(0, m-1, arr[i][j], arr[i + 1]);
ans = Math.min(ans, Math.abs(arr[i + 1][p] - arr[i][j]));
// largest element which is smaller than the current
// element in the next row must be just before
// smallest element which is greater than or equal
// to the current element because rows are sorted.
if (p-1 >= 0)
ans = Math.min(ans,
Math.abs(arr[i + 1][p - 1] - arr[i][j]));
}
}
return ans;
}
//Driver code
public static void main (String[] args)
{
int m[][] ={{8, 5},
{6, 8}};
System.out.println(mindiff(m, R, C));
}
}
//This code is contributed by Anant Agarwal.
Python3
# Python program to find the minimum absolute difference
# between any of the adjacent elements of an array
# which is created by picking one element from each
# row of the matrix.
# R 2
# C 2
# Return smallest element greater than or equal
# to the current element.
def bsearch(low, high, n, arr):
mid = (low + high)//2
if(low <= high):
if(arr[mid] < n):
return bsearch(mid +1, high, n, arr);
return bsearch(low, mid - 1, n, arr);
return low;
# Return the minimum absolute difference adjacent
# elements of array
def mindiff(arr, n, m):
# arr = [0 for i in range(R)][for j in range(C)]
# Sort each row of the matrix.
for i in range(n):
sorted(arr)
ans = 2147483647
# For each matrix element
for i in range(n-1):
for j in range(m):
# Search smallest element in the next row which
# is greater than or equal to the current element
p = bsearch(0, m-1, arr[i][j], arr[i + 1])
ans = min(ans, abs(arr[i + 1][p] - arr[i][j]))
# largest element which is smaller than the current
# element in the next row must be just before
# smallest element which is greater than or equal
# to the current element because rows are sorted.
if (p-1 >= 0):
ans = min(ans, abs(arr[i + 1][p - 1] - arr[i][j]))
return ans;
# Driver Program
m =[8, 5], [6, 8]
print (mindiff(m, 2, 2))
# This code is contributed by Afzal
C#
// C# program to find the minimum
// absolute difference between any
// of the adjacent elements of an
// array which is created by picking
// one element from each row of the matrix
using System;
class GFG
{
static public int R=2;
static public int C=2;
// Return smallest element greater than
// or equal to the current element.
static int bsearch(int low, int high, int n, int []arr)
{
int mid = (low + high)/2;
if(low <= high)
{
if(arr[mid] < n)
return bsearch(mid +1, high, n, arr);
return bsearch(low, mid - 1, n, arr);
}
return low;
}
public static int[] GetRow(int[,] matrix, int row)
{
var rowLength = matrix.GetLength(1);
var rowVector = new int[rowLength];
for (var i = 0; i < rowLength; i++)
rowVector[i] = matrix[row, i];
return rowVector;
}
// Return the minimum absolute difference adjacent
// elements of array
static int mindiff(int [,]arr, int n, int m)
{
// Sort each row of the matrix.
for (int i = 0; i < n; i++)
Array.Sort(GetRow(arr,i));
int ans = +2147483647;
// For each matrix element
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < m; j++)
{
// Search smallest element in the
// next row which is greater than
// or equal to the current element
int p = bsearch(0, m-1, arr[i,j], GetRow(arr,i+1));
ans = Math.Min(ans, Math.Abs(arr[i + 1,p] - arr[i,j]));
// largest element which is smaller than the current
// element in the next row must be just before
// smallest element which is greater than or equal
// to the current element because rows are sorted.
if (p-1 >= 0)
ans = Math.Min(ans,
Math.Abs(arr[i + 1,p - 1] - arr[i,j]));
}
}
return ans;
}
// Driver code
public static void Main (String[] args)
{
int [,]m ={{8, 5},
{6, 8}};
Console.WriteLine(mindiff(m, R, C));
}
}
// This code is contributed by 29AjayKumar
PHP
<?php
// PHP program to find the minimum
// absolute difference between any
// of the adjacent elements of an
// array which is created by picking
// one element from each row of the matrix.
$R = 2;
$C = 2;
// Return smallest element greater
// than or equal to the current element.
function bsearch($low, $high, $n, $arr)
{
$mid = ($low + $high) / 2;
if($low <= $high)
{
if($arr[$mid] < $n)
return bsearch($mid + 1, $high,
$n, $arr);
return bsearch($low, $mid - 1,
$n, $arr);
}
return $low;
}
// Return the minimum absolute difference
// adjacent elements of array
function mindiff($arr, $n, $m)
{
// Sort each row of the matrix.
for ($i = 0; $i < $n; $i++)
sort($arr);
$ans = PHP_INT_MAX;
// For each matrix element
for ($i = 0; $i < $n - 1; $i++)
{
for ( $j = 0; $j < $m; $j++)
{
// Search smallest element in the
// next row which is greater than
// or equal to the current element
$p = bsearch(0, $m - 1, $arr[$i][$j],
$arr[$i + 1]);
$ans = min($ans, abs($arr[$i + 1][$p] -
$arr[$i][$j]));
// largest element which is smaller than
// the current element in the next row
// must be just before smallest element
// which is greater than or equal to the
// current element because rows are sorted.
if ($p - 1 >= 0)
$ans = min($ans, abs($arr[$i + 1][$p - 1] -
$arr[$i][$j]));
}
}
return $ans;
}
// Driver Code
$m = array(8, 5, 6, 8);
echo mindiff($m, $R, $C), "\n";
// This code is contributed by Sach_Code
?>
JavaScript
<script>
// JavaScript program to find the minimum
// absolute difference between any
// of the adjacent elements of an
// array which is created by picking
// one element from each row of the matrix.
let R = 2;
let C = 2;
// Return smallest element greater than
// or equal to the current element.
function bsearch(low, high, n, arr)
{
let mid = (low + high) / 2;
if (low <= high)
{
if (arr[mid] < n)
return bsearch(mid + 1,
high, n, arr);
return bsearch(low, mid - 1,
n, arr);
}
return low;
}
// Return the minimum absolute difference
// adjacent elements of array
function mindiff(arr, n, m)
{
// Sort each row of the matrix.
for(let i = 0; i < n; i++)
arr.sort();
let ans = +2147483647;
// For each matrix element
for(let i = 0; i < n - 1; i++)
{
for(let j = 0; j < m; j++)
{
// Search smallest element in the
// next row which is greater than
// or equal to the current element
let p = bsearch(0, m - 1, arr[i][j],
arr[i + 1]);
ans = Math.min(ans,
Math.abs(arr[i + 1][p] -
arr[i][j]));
// largest element which is smaller
// than the current element in the
// next row must be just before smallest
// element which is greater than or equal
// to the current element because
// rows are sorted.
if (p - 1 >= 0)
ans = Math.min(ans,
Math.abs(arr[i + 1][p - 1] -
arr[i][j]));
}
}
return ans;
}
// Driver Code
let m = [ [ 8, 5 ],
[ 6, 8 ] ];
document.write(mindiff(m, R, C));
// This code is contributed by code_hunt
</script>
Time Complexity : O(N*M*logM).
Auxiliary Space: O(1), since no extra space required.
Similar Reads
Minimize maximum difference between adjacent elements possible by removing a single array element
Given an sorted array arr[] consisting of N elements, the task is to find the minimum of all maximum differences between adjacent elements of all arrays obtained by removal of any single array element. Examples: Input: arr[ ] = { 1, 3, 7, 8}Output: 5Explanation:All possible arrays after removing a s
6 min read
Sum of minimum difference between consecutive elements of an array
Given an array of pairs where each pair represents a range, the task is to find the sum of the minimum difference between the consecutive elements of an array where the array is filled in the below manner: Each element of an array lies in the range given at its corresponding index in the range array
10 min read
Minimum deletions in Array to make difference of adjacent elements non-decreasing
Given an array A of N non-negative integers, the task is to compute the minimum number of elements to be deleted so, that the following conditions hold: The elements are in non-decreasing order. (Formally, for each i (1 ⤠i ⤠N-1), the condition Ai+1 >= Ai should hold.)The difference between adja
15+ min read
Maximum difference between a pair of adjacent elements by excluding every element once
Given an array arr[] consisting of positive integers, the task is to find the maximum difference between any two adjacent elements after excluding each element from the array (except the first and last elements).Examples:Input: arr[] = [1, 3, 4, 7, 8]Output: [3, 4, 4]Explanation:Excluding i = 1: Rem
11 min read
Sum of matrix in which each element is absolute difference of its row and column numbers
Given a positive integer n. Consider a matrix of n rows and n columns, in which each element contain absolute difference of its row number and numbers. The task is to calculate sum of each element of the matrix. Examples : Input : n = 2 Output : 2 Matrix formed with n = 2 with given constraint: 0 1
13 min read
Minimum sum of all absolute differences of same column elements in adjacent rows in a given Matrix
Given a matrix mat[][] having N rows and M columns, the task is to find the minimum distance between two adjacent rows where the distance between two rows is defined as the sum of all absolute differences between two elements present at the same column in the two rows. Examples: Input: mat[][] = {{1
5 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
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}Out
12 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
Minimize increment-decrement operation on adjacent elements to convert Array A to B
Given two arrays A[] and B[] consisting of N positive integers, the task is to find the minimum number of increment and decrements of adjacent array elements of the array A[] required to convert it to the array B[]. If it is not possible, then print "-1". Examples: Input: A[] = {1, 2}, B[] = {2, 1}O
11 min read