Related Articles

# Minimum absolute value of (K – arr[i]) for all possible values of K over the range [0, N – 1]

• Last Updated : 14 Jul, 2021

Given a positive integer N and a sorted array arr[] consisting of M integers, the task is to find the minimum absolute value of (K – arr[i]) for all possible values of K over the range [0, N – 1].

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: N = 5, arr[] = {0, 4}
Output: 0 1 2 1 0
Explanation:
Below are the possible minimum value for all possible values of K over the range [0, N – 1]:

• K = 0: The minimum value of abs(K – arr[i]) is obtained by considering arr[i] as 0. Therefore, the value is abs(0 – 0) = 0.
• K = 1: The minimum value of abs(K – arr[i]) is obtained by considering arr[i] as 0. Therefore, the value is abs(1 – 0) = 1.
• K = 2: The minimum value of abs(K – arr[i]) is obtained by considering arr[i] as 0. Therefore, the value is abs(2 – 0) = 2.
• K = 3: The minimum value of abs(K – arr[i]) is obtained by considering arr[i] as 4. Therefore, the value is abs(3 – 4) = 1.
• K = 4: The minimum value of abs(K – arr[i]) is obtained by considering arr[i] as 4. Therefore, the value is abs(4 – 4) = 0.

Input: N = 6, arr[] = {0, 1, 4, 5}
Output: 0 0 1 1 0 0

Approach: The given problem can be solved by choosing the value from the array which is just greater or smaller than the current value of K. Follow the steps below to solve the problem:

• Initialize a variable, say ind as 0, and a variable, say prev to arr that stores the previously assigned value.
• Iterate over the range [0, N – 1] using the variable K and perform the following steps:
• Initialize a variable, say distance to store the minimum absolute value of (K – arr[i]).
• If the value of i is less than arr, then update the value of the distance to (arr – i).
• Otherwise, if the value of i is at least prev, the value of (ind + 1) is less than the M and the value of i is at most arr[ind + 1], then perform the following steps:
• Update the value of distance to the minimum of (i – prev) and (arr[ind + 1] – i).
• If the value of i is equal to arr[ind + 1], then update the value of distance to 0, prev to arr[ind + 1], and increment the value of ind by 1.
• If the value of i is greater than prev, then update the value of distance to the (i – prev).
• After completing the above steps, print the value of distance as the minimum absolute value of (K – arr[i]) for the current value of K.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ``using` `namespace` `std;` `// Function to find the minimum absolute``// value of (K - arr[i]) for each possible``// value of K over the range [0, N - 1]|``void` `minimumDistance(vector<``int``> arr,``                     ``int` `N)``{``    ``int` `ind = 0;``    ``int` `prev = arr[ind];``    ``int` `s = arr.size();` `    ``// Traverse the given array arr[]``    ``for` `(``int` `i = 0; i < N; i++) {` `        ``// Stores the mininimum distance``        ``// to any array element arr[i]``        ``int` `distance = INT_MAX;` `        ``// Check if there is no safe``        ``// position smaller than i``        ``if` `(i < arr) {``            ``distance = arr - i;``        ``}` `        ``// Check if the current position``        ``// is between two safe positions``        ``else` `if` `(i >= prev && ind + 1 < s``                 ``&& i <= arr[ind + 1]) {` `            ``// Take the minimum of two``            ``// distances``            ``distance = min(i - prev,``                           ``arr[ind + 1] - i);` `            ``// Check if the current index``            ``// is a safe position``            ``if` `(i == arr[ind + 1]) {``                ``distance = 0;``                ``prev = arr[ind + 1];``                ``ind++;``            ``}``        ``}` `        ``// Check if there is no safe``        ``// position greater than i``        ``else` `{``            ``distance = i - prev;``        ``}` `        ``// Print the minimum distance``        ``cout << distance << ``" "``;``    ``}``}` `// Driver Code``int` `main()``{``    ``int` `N = 5;``    ``vector<``int``> arr = { 0, 4 };``    ``minimumDistance(arr, N);` `    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.io.*;``class` `GFG``{``  ` `    ``// Functinion to find the minimum absolute``    ``// value of (K - arr[i]) for each possible``    ``// value of K over the range [0, N - 1]|``    ``public` `static` `void` `minimumDistance(``int` `arr[],``                         ``int` `N)``    ``{``        ``int` `ind = ``0``;``        ``int` `prev = arr[ind];``        ``int` `s = arr.length;``    ` `        ``// Traverse the given array arr[]``        ``for` `(``int` `i = ``0``; i < N; i++) {``    ` `            ``// Stores the mininimum distance``            ``// to any array element arr[i]``            ``int` `distance = Integer.MAX_VALUE;``    ` `            ``// Check if there is no safe``            ``// position smaller than i``            ``if` `(i < arr[``0``]) {``                ``distance = arr[``0``] - i;``            ``}``    ` `            ``// Check if the current position``            ``// is between two safe positions``            ``else` `if` `(i >= prev && ind + ``1` `< s``                     ``&& i <= arr[ind + ``1``]) {``    ` `                ``// Take the minimum of two``                ``// distances``                ``distance = Math.min(i - prev,``                               ``arr[ind + ``1``] - i);``    ` `                ``// Check if the current index``                ``// is a safe position``                ``if` `(i == arr[ind + ``1``]) {``                    ``distance = ``0``;``                    ``prev = arr[ind + ``1``];``                    ``ind++;``                ``}``            ``}``    ` `            ``// Check if there is no safe``            ``// position greater than i``            ``else` `{``                ``distance = i - prev;``            ``}``            ` `            ``// Print the minimum distance``            ``System.out.print(distance+``" "``);``        ``}``    ``}` `    ``// driver code``    ``public` `static` `void` `main (String[] args) {``        ``int` `N = ``5``;``        ``int` `arr[] = { ``0``, ``4` `};``        ``minimumDistance(arr, N);``    ``}``}` `// This code is contributed by Manu Pathria`

## Python3

 `# Python program for the above approach`  `# Function to find the minimum absolute``# value of (K - arr[i]) for each possible``# value of K over the range [0, N - 1]|``def` `minimumDistance(arr, N):``    ``ind ``=` `0``;``    ``prev ``=` `arr[ind];``    ``s ``=` `len``(arr);` `    ``# Traverse the given array arr[]``    ``for` `i ``in` `range``(N):` `        ``# Stores the mininimum distance``        ``# to any array element arr[i]``        ``distance ``=` `10``*``*``9``;` `        ``# Check if there is no safe``        ``# position smaller than i``        ``if` `(i < arr[``0``]):``            ``distance ``=` `arr[``0``] ``-` `i;` `        ``# Check if the current position``        ``# is between two safe positions``        ``elif` `(i >``=` `prev ``and` `ind ``+` `1` `< s``            ``and` `i <``=` `arr[ind ``+` `1``]):` `            ``# Take the minimum of two``            ``# distances``            ``distance ``=` `min``(i ``-` `prev, arr[ind ``+` `1``] ``-` `i);` `            ``# Check if the current index``            ``# is a safe position``            ``if` `(i ``=``=` `arr[ind ``+` `1``]):``                ``distance ``=` `0``;``                ``prev ``=` `arr[ind ``+` `1``];``                ``ind ``+``=` `1``;` `        ``# Check if there is no safe``        ``# position greater than i``        ``else``:``            ``distance ``=` `i ``-` `prev;` `        ``# Print the minimum distance``        ``print``(distance, end``=``" "``);` `# Driver Code` `N ``=` `5``;``arr ``=` `[``0``, ``4``];``minimumDistance(arr, N);` `# This code is contributed by _saurabh_jaiswal.`

## C#

 `// C# program for the above approach``using` `System;``class` `GFG``{``  ` `    ``// Functinion to find the minimum absolute``    ``// value of (K - arr[i]) for each possible``    ``// value of K over the range [0, N - 1]|``    ``public` `static` `void` `minimumDistance(``int` `[]arr,``                         ``int` `N)``    ``{``        ``int` `ind = 0;``        ``int` `prev = arr[ind];``        ``int` `s = arr.Length;``    ` `        ``// Traverse the given array arr[]``        ``for` `(``int` `i = 0; i < N; i++) {``    ` `            ``// Stores the mininimum distance``            ``// to any array element arr[i]``            ``int` `distance = Int32.MaxValue;``    ` `            ``// Check if there is no safe``            ``// position smaller than i``            ``if` `(i < arr) {``                ``distance = arr - i;``            ``}``    ` `            ``// Check if the current position``            ``// is between two safe positions``            ``else` `if` `(i >= prev && ind + 1 < s``                     ``&& i <= arr[ind + 1]) {``    ` `                ``// Take the minimum of two``                ``// distances``                ``distance = Math.Min(i - prev,``                               ``arr[ind + 1] - i);``    ` `                ``// Check if the current index``                ``// is a safe position``                ``if` `(i == arr[ind + 1]) {``                    ``distance = 0;``                    ``prev = arr[ind + 1];``                    ``ind++;``                ``}``            ``}``    ` `            ``// Check if there is no safe``            ``// position greater than i``            ``else` `{``                ``distance = i - prev;``            ``}``            ` `            ``// Print the minimum distance``            ``Console.Write(distance+``" "``);``        ``}``    ``}` `    ``// driver code``    ``public` `static` `void` `Main (``string``[] args) {``        ``int` `N = 5;``        ``int` `[]arr = { 0, 4 };``        ``minimumDistance(arr, N);``    ``}``}` `// This code is contributed by ukasp.`

## Javascript

 ``
Output:
`0 1 2 1 0`

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

My Personal Notes arrow_drop_up