# Queries to find minimum absolute difference between adjacent array elements in given ranges

• Last Updated : 16 Sep, 2021

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:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr[] = {2, 6, 1, 8, 3, 4}, query[] = {{0, 3}, {1, 5}, {4, 5}}
Output:
4
1
1
Explanation:
Following are the values of queries performed:

1. The minimum absolute difference between  adjacent element over the range [0, 3] is min(|2 – 6|, |6 – 1|, |1 – 8|) = 4.
2. The minimum absolute difference between  adjacent element over the range [1, 5] is min(|6 – 1|, |1 – 8|, |8 – 3|, |3 – 4| ) = 1.
3. The minimum absolute difference between  adjacent element over the range [4, 5] is min(|3 – 4|) = 1.

Therefore, print 4, 1, 1 as the results of the given queries.

Input: arr[] = [10, 20, 1, 1, 5 ], query[] = [0, 1], [1, 4], [2, 3]
Output:
10
0
0

Naive Approach: The simplest approach to solve the given problem is to create an array diff[] that stores the absolute difference between adjacent elements for each array element. Now for each query, traverse the array diff[] over the range [L, R – 1] and print the value of minimum all the values in the range [L, R – 1].

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach``#include ``using` `namespace` `std;` `// Structure for query range``struct` `Query {``    ``int` `L, R;``};` `int` `MAX = 5000;` `// Function to find the minimum difference``// between adjacent array element over the``// given range [L, R] for Q Queries``void` `minDifference(``int` `arr[], ``int` `n,``                   ``Query q[], ``int` `m)``{` `    ``// Find the sum of all queries``    ``for` `(``int` `i = 0; i < m; i++) {` `        ``// Left and right boundaries``        ``// of current range``        ``int` `L = q[i].L, R = q[i].R;` `        ``int` `ans = MAX;``        ``for` `(``int` `i = L; i < R; i++) {``            ``ans = min(ans, arr[i]);``        ``}` `        ``// Print  the sum of the``        ``// current query range``        ``cout << ans << ``'\n'``;``    ``}``}` `// Function to find the minimum absolute``// difference of adjacent array elements``// for the given range``void` `minimumDifference(``int` `arr[], Query q[],``                       ``int` `N, ``int` `m)``{` `    ``// Stores the absolute difference of``    ``// adjacent elements``    ``int` `diff[N];` `    ``for` `(``int` `i = 0; i < N - 1; i++)``        ``diff[i] = ``abs``(arr[i] - arr[i + 1]);` `    ``// Find the minimum difference of``    ``// adjacent elements``    ``minDifference(diff, N - 1, q, m);``}` `// Driver Code``int` `main()``{``    ``int` `arr[] = { 2, 6, 1, 8, 3, 4 };``    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr);``    ``Query Q[] = { { 0, 3 }, { 1, 5 }, { 4, 5 } };``    ``int` `M = ``sizeof``(Q) / ``sizeof``(Q);` `    ``minimumDifference(arr, Q, N, M);` `    ``return` `0;``}`

## Java

 `// Java program for the above approach``class` `GFG{` `// Structure for query range``static` `class` `Query {``    ``int` `L, R;` `    ``public` `Query(``int` `l, ``int` `r) {``        ``super``();``        ``L = l;``        ``R = r;``    ``}``    ` `};` `static` `int` `MAX = ``5000``;` `// Function to find the minimum difference``// between adjacent array element over the``// given range [L, R] for Q Queries``static` `void` `minDifference(``int` `arr[], ``int` `n,``                   ``Query q[], ``int` `m)``{` `    ``// Find the sum of all queries``    ``for` `(``int` `i = ``0``; i < m; i++) {` `        ``// Left and right boundaries``        ``// of current range``        ``int` `L = q[i].L, R = q[i].R;` `        ``int` `ans = MAX;``        ``for` `(``int` `j = L; j < R; j++) {``            ``ans = Math.min(ans, arr[j]);``        ``}` `        ``// Print  the sum of the``        ``// current query range``        ``System.out.println(ans);``    ``}``}` `// Function to find the minimum absolute``// difference of adjacent array elements``// for the given range``static` `void` `minimumDifference(``int` `arr[], Query q[],``                       ``int` `N, ``int` `m)``{` `    ``// Stores the absolute difference of``    ``// adjacent elements``    ``int` `[]diff = ``new` `int``[N];` `    ``for` `(``int` `i = ``0``; i < N - ``1``; i++)``        ``diff[i] = Math.abs(arr[i] - arr[i + ``1``]);` `    ``// Find the minimum difference of``    ``// adjacent elements``    ``minDifference(diff, N - ``1``, q, m);``}` `// Driver Code``public` `static` `void` `main(String[] args)``{``    ``int` `arr[] = { ``2``, ``6``, ``1``, ``8``, ``3``, ``4` `};``    ``int` `N = arr.length;``    ``Query Q[] = {``new` `Query( ``0``, ``3` `),``new` `Query( ``1``, ``5` `),``new` `Query( ``4``, ``5` `) };``    ``int` `M = Q.length;` `    ``minimumDifference(arr, Q, N, M);` `}``}` `// This code is contributed by Princi Singh`

## Python3

 `# Python3 program for the above approach``MAX` `=` `5000``;` `# Function to find the minimum difference``# between adjacent array element over the``# given range [L, R] for Q Queries``def` `minDifference(arr, n, q, m) :` `    ``# Find the sum of all queries``    ``for` `i ``in` `range``(m) :``        ` `        ``# Left and right boundaries``        ``# of current range``        ``L ``=` `q[i][``0``]; R ``=` `q[i][``1``];` `        ``ans ``=` `MAX``;``        ``for` `i ``in` `range``(L, R) :``            ``ans ``=` `min``(ans, arr[i]);` `        ``# Print  the sum of the``        ``# current query range``        ``print``(ans);``    `  `# Function to find the minimum absolute``# difference of adjacent array elements``# for the given range``def` `minimumDifference(arr, q, N, m) :` `    ``# Stores the absolute difference of``    ``# adjacent elements``    ``diff ``=` `[``0``]``*``N;` `    ``for` `i ``in` `range``(N ``-` `1``) :``        ``diff[i] ``=` `abs``(arr[i] ``-` `arr[i ``+` `1``]);` `    ``# Find the minimum difference of``    ``# adjacent elements``    ``minDifference(diff, N ``-` `1``, q, m);` `# Driver Code``if` `__name__ ``=``=` `"__main__"` `:` `    ``arr ``=` `[ ``2``, ``6``, ``1``, ``8``, ``3``, ``4` `];``    ``N ``=` `len``(arr);``    ``Q ``=` `[ [ ``0``, ``3` `], [ ``1``, ``5` `], [ ``4``, ``5` `] ];``    ``M ``=` `len``(Q);` `    ``minimumDifference(arr, Q, N, M);``    ` `    ``# This code is contributed by AnkThon`

## C#

 `// C# program for the above approach``using` `System;``using` `System.Collections.Generic;` `class` `GFG{` `// Structure for query range``class` `Query {``    ``public` `int` `L, R;` `    ``public` `Query(``int` `l, ``int` `r) {``        ``this``.L = l;``        ``this``.R = r;``    ``}``    ` `};` `static` `int` `MAX = 5000;` `// Function to find the minimum difference``// between adjacent array element over the``// given range [L, R] for Q Queries``static` `void` `minDifference(``int` `[]arr, ``int` `n,``                   ``Query []q, ``int` `m)``{` `    ``// Find the sum of all queries``    ``for` `(``int` `i = 0; i < m; i++) {` `        ``// Left and right boundaries``        ``// of current range``        ``int` `L = q[i].L, R = q[i].R;` `        ``int` `ans = MAX;``        ``for` `(``int` `j = L; j < R; j++) {``            ``ans = Math.Min(ans, arr[j]);``        ``}` `        ``// Print  the sum of the``        ``// current query range``        ``Console.WriteLine(ans);``    ``}``}` `// Function to find the minimum absolute``// difference of adjacent array elements``// for the given range``static` `void` `minimumDifference(``int` `[]arr, Query []q,``                       ``int` `N, ``int` `m)``{` `    ``// Stores the absolute difference of``    ``// adjacent elements``    ``int` `[]diff = ``new` `int``[N];` `    ``for` `(``int` `i = 0; i < N - 1; i++)``        ``diff[i] = Math.Abs(arr[i] - arr[i + 1]);` `    ``// Find the minimum difference of``    ``// adjacent elements``    ``minDifference(diff, N - 1, q, m);``}` `// Driver Code``public` `static` `void` `Main()``{``    ``int` `[]arr = { 2, 6, 1, 8, 3, 4 };``    ``int` `N = arr.Length;``    ``Query []Q = {``new` `Query( 0, 3 ),``new` `Query( 1, 5 ),``new` `Query( 4, 5 ) };``    ``int` `M = Q.Length;` `    ``minimumDifference(arr, Q, N, M);` `}``}` `// This code is contributed by SURENDRA_GANGWAR.`

## Javascript

 ``

Output:
```4
1
1```

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

Efficient Approach: The above approach can also be optimized by using the Sparse Table that supports query in constant time O(1) with extra space O(N log N). Instead of passing original arr[] pass diff[] to get the required answer. Follow the steps below to solve the problem:

1. Initialize a global array lookup[][] for the sparse array.
2. Define a function preprocess(arr, N) and perform the following operations:
• Iterate over the range [0, N) using the variable i and set the value of lookup[i] as i.
• Iterate over the range [1, N) using the variable j and i nestedly and if arr[lookup[i][j-1]] is less than arr[lookup[i + (1 << (j-1))][j-1], then set lookup[i][j] as lookup[i][j-1], otherwise set lookup[i][j] as lookup[i + (1 << (j – 1))][j – 1].
3. Define a function query(int arr[], int L, int M) and perform the following operations:
• Initialize the variable j as (int)log2(R – L + 1).
• If arr[lookup[L][j]] is less than equal to arr[lookup[R – (1 << j) + 1][j]], then return arr[lookup[L][j]], else return arr[lookup[R – (1 << j) + 1][j]].
4. Define a function Min_difference(arr, n, q, m) and perform the following operations:
• Call the function preprocess(arr, n) to preprocess the sparse array.
• Traverse the given array of queries Q[] and the value returned by the function query(arr, L, R – 1) gives the result for the current query.
5. Initialize an array diff[] of size N and store the absolute differences of arr[i]-arr[i+1] for every value of i.
6. Call the function Min_difference(diff, N-1, q, m) to find the minimum absolute difference for each query.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach``#include ``using` `namespace` `std;``#define MAX 500` `// Stores the index for the minimum``// value in the subarray arr[i, j]``int` `lookup[MAX][MAX];` `// Structure for query range``struct` `Query {``    ``int` `L, R;``};` `// Function to fill the lookup array``// lookup[][] in the bottom up manner``void` `preprocess(``int` `arr[], ``int` `n)``{``    ``// Initialize M for the intervals``    ``// with length 1``    ``for` `(``int` `i = 0; i < n; i++)``        ``lookup[i] = i;` `    ``// Find the values from smaller``    ``// to bigger intervals``    ``for` `(``int` `j = 1; (1 << j) <= n; j++) {` `        ``// Compute minimum value for``        ``// all intervals with size 2^j``        ``for` `(``int` `i = 0; (i + (1 << j) - 1) < n; i++) {` `            ``// For arr, compare``            ``// arr[lookup] and``            ``// arr[lookup]``            ``if` `(arr[lookup[i][j - 1]]``                ``< arr[lookup[i + (1 << (j - 1))][j - 1]])``                ``lookup[i][j] = lookup[i][j - 1];` `            ``// Otherwise``            ``else``                ``lookup[i][j]``                    ``= lookup[i + (1 << (j - 1))][j - 1];``        ``}``    ``}``}` `// Function find minimum of absolute``// difference of all adjacent element``// in subarray arr[L..R]``int` `query(``int` `arr[], ``int` `L, ``int` `R)``{``    ``// For [2, 10], j = 3``    ``int` `j = (``int``)log2(R - L + 1);` `    ``// For [2, 10], compare arr[lookup]``    ``// and arr[lookup],``    ``if` `(arr[lookup[L][j]]``        ``<= arr[lookup[R - (1 << j) + 1][j]])``        ``return` `arr[lookup[L][j]];` `    ``else``        ``return` `arr[lookup[R - (1 << j) + 1][j]];``}` `// Function to find the minimum of the``// ranges for M queries``void` `Min_difference(``int` `arr[], ``int` `n,``                    ``Query q[], ``int` `m)``{``    ``// Fills table lookup[n][Log n]``    ``preprocess(arr, n);` `    ``// Compute sum of all queries``    ``for` `(``int` `i = 0; i < m; i++) {` `        ``// Left and right boundaries``        ``// of current range``        ``int` `L = q[i].L, R = q[i].R;` `        ``// Print sum of current query range``        ``cout << query(arr, L, R - 1) << ``'\n'``;``    ``}``}` `// Function to find the minimum absolute``// difference in a range``void` `minimumDifference(``int` `arr[], Query q[],``                       ``int` `N, ``int` `m)``{` `    ``// diff[] is to stores the absolute``    ``// difference of adjacent elements``    ``int` `diff[N];``    ``for` `(``int` `i = 0; i < N - 1; i++)``        ``diff[i] = ``abs``(arr[i] - arr[i + 1]);` `    ``// Call Min_difference to get minimum``    ``// difference of adjacent elements``    ``Min_difference(diff, N - 1, q, m);``}` `// Driver Code``int` `main()``{``    ``int` `arr[] = { 2, 6, 1, 8, 3, 4 };``    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr);``    ``Query Q[] = { { 0, 3 }, { 1, 5 }, { 4, 5 } };``    ``int` `M = ``sizeof``(Q) / ``sizeof``(Q);` `    ``minimumDifference(arr, Q, N, M);` `    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.util.*;``import` `javax.management.Query;` `class` `GFG{``static` `final` `int` `MAX = ``500``;` `// Stores the index for the minimum``// value in the subarray arr[i, j]``static` `int` `[][]lookup = ``new` `int``[MAX][MAX];` `// Structure for query range``static` `class` `Query {``    ``int` `L, R;` `    ``public` `Query(``int` `l, ``int` `r) {``        ``super``();``        ``L = l;``        ``R = r;``    ``}``};` `// Function to fill the lookup array``// lookup[][] in the bottom up manner``static` `void` `preprocess(``int` `arr[], ``int` `n)``{``    ``// Initialize M for the intervals``    ``// with length 1``    ``for` `(``int` `i = ``0``; i < n; i++)``        ``lookup[i][``0``] = i;` `    ``// Find the values from smaller``    ``// to bigger intervals``    ``for` `(``int` `j = ``1``; (``1` `<< j) <= n; j++) {` `        ``// Compute minimum value for``        ``// all intervals with size 2^j``        ``for` `(``int` `i = ``0``; (i + (``1` `<< j) - ``1``) < n; i++) {` `            ``// For arr, compare``            ``// arr[lookup] and``            ``// arr[lookup]``            ``if` `(arr[lookup[i][j - ``1``]]``                ``< arr[lookup[i + (``1` `<< (j - ``1``))][j - ``1``]])``                ``lookup[i][j] = lookup[i][j - ``1``];` `            ``// Otherwise``            ``else``                ``lookup[i][j]``                    ``= lookup[i + (``1` `<< (j - ``1``))][j - ``1``];``        ``}``    ``}``}` `// Function find minimum of absolute``// difference of all adjacent element``// in subarray arr[L..R]``static` `int` `query(``int` `arr[], ``int` `L, ``int` `R)``{``    ``// For [2, 10], j = 3``    ``int` `j = (``int``)Math.log(R - L + ``1``);` `    ``// For [2, 10], compare arr[lookup]``    ``// and arr[lookup],``    ``if` `(arr[lookup[L][j]]``        ``<= arr[lookup[R - (``1` `<< j) + ``1``][j]])``        ``return` `arr[lookup[L][j]];` `    ``else``        ``return` `arr[lookup[R - (``1` `<< j) + ``1``][j]];``}` `// Function to find the minimum of the``// ranges for M queries``static` `void` `Min_difference(``int` `arr[], ``int` `n,``                    ``Query q[], ``int` `m)``{``    ``// Fills table lookup[n][Log n]``    ``preprocess(arr, n);` `    ``// Compute sum of all queries``    ``for` `(``int` `i = ``0``; i < m; i++) {` `        ``// Left and right boundaries``        ``// of current range``        ``int` `L = q[i].L, R = q[i].R;` `        ``// Print sum of current query range``        ``System.out.println(query(arr, L, R - ``1``));``    ``}``}` `// Function to find the minimum absolute``// difference in a range``static` `void` `minimumDifference(``int` `arr[], Query q[],``                       ``int` `N, ``int` `m)``{` `    ``// diff[] is to stores the absolute``    ``// difference of adjacent elements``    ``int` `[]diff = ``new` `int``[N];``    ``for` `(``int` `i = ``0``; i < N - ``1``; i++)``        ``diff[i] = Math.abs(arr[i] - arr[i + ``1``]);` `    ``// Call Min_difference to get minimum``    ``// difference of adjacent elements``    ``Min_difference(diff, N - ``1``, q, m);``}` `// Driver Code``public` `static` `void` `main(String[] args)``{``    ``int` `arr[] = { ``2``, ``6``, ``1``, ``8``, ``3``, ``4` `};``    ``int` `N = arr.length;``    ``Query Q[] = { ``new` `Query( ``0``, ``3` `), ``new` `Query( ``1``, ``5` `), ``new` `Query( ``4``, ``5` `) };``    ``int` `M = Q.length;` `    ``minimumDifference(arr, Q, N, M);` `}``}` `// This code is contributed by 29AjayKumar`

## C#

 `// C# program for the above approach``using` `System;` `public` `class` `GFG{``static` `readonly` `int` `MAX = 500;` `// Stores the index for the minimum``// value in the subarray arr[i, j]``static` `int` `[,]lookup = ``new` `int``[MAX, MAX];` `// Structure for query range``class` `Query {``    ``public` `int` `L, R;` `    ``public` `Query(``int` `l, ``int` `r) {``       ` `        ``L = l;``        ``R = r;``    ``}``};` `// Function to fill the lookup array``// lookup[,] in the bottom up manner``static` `void` `preprocess(``int` `[]arr, ``int` `n)``{``  ` `    ``// Initialize M for the intervals``    ``// with length 1``    ``for` `(``int` `i = 0; i < n; i++)``        ``lookup[i,0] = i;` `    ``// Find the values from smaller``    ``// to bigger intervals``    ``for` `(``int` `j = 1; (1 << j) <= n; j++) {` `        ``// Compute minimum value for``        ``// all intervals with size 2^j``        ``for` `(``int` `i = 0; (i + (1 << j) - 1) < n; i++) {` `            ``// For arr[2,10], compare``            ``// arr[lookup[0,3]] and``            ``// arr[lookup[3,3]]``            ``if` `(arr[lookup[i,j - 1]]``                ``< arr[lookup[i + (1 << (j - 1)),j - 1]])``                ``lookup[i,j] = lookup[i,j - 1];` `            ``// Otherwise``            ``else``                ``lookup[i,j]``                    ``= lookup[i + (1 << (j - 1)),j - 1];``        ``}``    ``}``}` `// Function find minimum of absolute``// difference of all adjacent element``// in subarray arr[L..R]``static` `int` `query(``int` `[]arr, ``int` `L, ``int` `R)``{``  ` `    ``// For [2, 10], j = 3``    ``int` `j = (``int``)Math.Log(R - L + 1);` `    ``// For [2, 10], compare arr[lookup[0,3]]``    ``// and arr[lookup[3,3]],``    ``if` `(arr[lookup[L,j]]``        ``<= arr[lookup[R - (1 << j) + 1,j]])``        ``return` `arr[lookup[L,j]];` `    ``else``        ``return` `arr[lookup[R - (1 << j) + 1,j]];``}` `// Function to find the minimum of the``// ranges for M queries``static` `void` `Min_difference(``int` `[]arr, ``int` `n,``                    ``Query []q, ``int` `m)``{``  ` `    ``// Fills table lookup[n,Log n]``    ``preprocess(arr, n);` `    ``// Compute sum of all queries``    ``for` `(``int` `i = 0; i < m; i++) {` `        ``// Left and right boundaries``        ``// of current range``        ``int` `L = q[i].L, R = q[i].R;` `        ``// Print sum of current query range``        ``Console.WriteLine(query(arr, L, R - 1));``    ``}``}` `// Function to find the minimum absolute``// difference in a range``static` `void` `minimumDifference(``int` `[]arr, Query []q,``                       ``int` `N, ``int` `m)``{` `    ``// diff[] is to stores the absolute``    ``// difference of adjacent elements``    ``int` `[]diff = ``new` `int``[N];``    ``for` `(``int` `i = 0; i < N - 1; i++)``        ``diff[i] = Math.Abs(arr[i] - arr[i + 1]);` `    ``// Call Min_difference to get minimum``    ``// difference of adjacent elements``    ``Min_difference(diff, N - 1, q, m);``} ` `// Driver Code``public` `static` `void` `Main(String[] args)``{``    ``int` `[]arr = { 2, 6, 1, 8, 3, 4 };``    ``int` `N = arr.Length;``    ``Query []Q = { ``new` `Query( 0, 3 ), ``new` `Query( 1, 5 ), ``new` `Query( 4, 5 ) };``    ``int` `M = Q.Length;` `    ``minimumDifference(arr, Q, N, M);` `}``}` `// This code is contributed by shikhasingrajput`

## Javascript

 ``

Output:
```4
1
1```

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

My Personal Notes arrow_drop_up