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):

  • n: an integer that represents the length of arr
  • arr: an array of integers

Input Format

The first line contains a single integer , the size of .
The second line contains  space-separated integers .

Constraints

Output Format

Print the minimum absolute difference between any two elements in the array.


hackerrank minimum absolute difference in an array solution


Problem solution in C++ programming language.

#include <bits/stdc++.h>

using namespace std;

int main(){
    int n;
    cin >> n;
    vector<int> a(n);
    for(int i=0;i<n;i++){
        cin >> a[i];
    } 
    sort(a.begin(),a.end());
    int ans=10000000;
    for(int i=0;i<n-1;i++){
        ans = min(ans,abs(a[i]-a[i+1]));
    }
    cout << ans << endl;
    // your code goes here
    return 0;
}


Problem solution in C programming language.

#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int comp(const void *a, const void *b)
{
	int A=*((int *)a);
	int B=*((int *)b);
	return A-B;
}
int main()
{
	int n,arr[100010],i,min=1000009999;
	scanf("%d",&n);
	for(i=0;i<n;i++)
		scanf("%d",&arr[i]);
	qsort(arr,n,sizeof(int),comp);
	for(i=0;i<n-1;i++)
		if(abs(arr[i]-arr[i+1])<min)
			min=abs(arr[i]-arr[i+1]);
	printf("%d\n",min);
	return 0;
}


Problem solution in Java programming language.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] a = new int[n];
        for(int a_i=0; a_i < n; a_i++){
            a[a_i] = in.nextInt();
        }
        Arrays.sort(a);
        int min = 2000000000;
        for (int i = 1; i < n; i++) {
            min = Math.min(Math.abs(a[i]-a[i-1]), min);
        }
        System.out.println(min);
    }
}


Problem solution in Python programming language.

#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the minimumAbsoluteDifference function below.
def minimumAbsoluteDifference(arr):
    diffs = []
    arr.sort()
    for i in range(len(arr)-1):
        diffs.append(abs(arr[i]-arr[i+1]))
    return min(diffs)

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input())

    arr = list(map(int, input().rstrip().split()))

    result = minimumAbsoluteDifference(arr)

    fptr.write(str(result) + '\n')

    fptr.close()