In this Minimum Absolute Difference HackerRank solution,The absolute difference is the positive difference between two values and , is written or and they are equal. If and , . Given an array of integers, find the minimum absolute difference between any two elements in the array.
Example.
There are pairs of numbers: and . The absolute differences for these pairs are , and . The minimum absolute difference is .
Function Description
Complete the minimumAbsoluteDifference function in the editor below. It should return an integer that represents the minimum absolute difference between any pair of elements.
minimumAbsoluteDifference has the following parameter(s):
- int arr[n]: an array of integers
Returns
- int: the minimum absolute difference found
Input Format
The first line contains a single integer , the size of .
The second line contains space-separated integers, .
Constraints
Minimum Absolute Difference HackerRank Solution
I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.
Problem Solution in Python
def minimumAbsoluteDifference(arr):
sorted_arr = sorted(arr)
asb_diff = []
for i in range(1,n):
asb_diff.append(abs(sorted_arr[i]-sorted_arr[i-1]))
return min(asb_diff)
Problem Solution in JavaScript
function minimumAbsoluteDifference(arr) {
const sorted = arr.sort((a, b)=>(a-b));
let tiny = Math.abs(sorted[0]-sorted[1]);
for (let i=0; i<sorted.length;i++){
let iGap= Math.abs(sorted[i] - sorted[i+1]);
if (iGap < tiny) {
tiny = iGap
}
}
return tiny;
}
Problem Solution in PHP
function minimumAbsoluteDifference($arr) {
// Write your code here
sort($arr);
$res = [];
$count = count($arr) -1;
foreach($arr as $k => $int){
if($k != $count){
$diff = abs($int - $arr[$k+1]);
array_push($res, $diff);
}
}
return min($res);
}
Problem Solution in C++
int minimumAbsoluteDifference(vector<int> arr) {
std::sort(arr.begin(), arr.end());
int min = arr[1] - arr[0];
for (size_t i = 1; i < arr.size() - 1; i++)
{
if (arr[i+1] - arr[i] < min)
min = arr[i+1] - arr[i];
}
return min;
}
Problem Solution in Java
public static int minimumAbsoluteDifference(List<Integer> arr) {
int minimum = Integer.MAX_VALUE;
List<Integer> allElUnique = arr.stream()
.distinct()
.collect(Collectors.toList());
if (allElUnique.size() != arr.size()) {
return 0;
} else {
Collections.sort(arr);
for (int i = 0; i < arr.size() - 1; i++) {
int left = arr.get(i);
int right = arr.get(i+1);
int diff = Math.abs(right - left);
if (diff < minimum) {
minimum = diff;
}
}
}
return minimum;
}
Leave a Reply