We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • Hackerrank Home
  • Prepare
    NEW
  • Certify
  • Compete
  • Career Fair
  • Hiring developers?
  1. Prepare
  2. Algorithms
  3. Greedy
  4. Minimum Absolute Difference in an Array
  5. Discussions

Minimum Absolute Difference in an Array

Problem
Submissions
Leaderboard
Discussions
Editorial

Sort 615 Discussions, By:

votes

Please Login in order to post a comment

  • anjalipv
    5 years ago+ 43 comments

    1)sort 2)consider diff between the first pair as min 3)compare all "consecutive pair min" with the one in step2 to get the least min.

    216|
    Permalink
    View more Comments..
  • BTANguyen
    5 years ago+ 4 comments

    Why this is under greedy algo ? What is the greedy property in this problem?

    55|
    Permalink
    View more Comments..
  • rosberglinhares
    3 years ago+ 4 comments
    Arrays.sort(arr);
    
    int minimumDifference = Integer.MAX_VALUE;
    
    for (int i = 0; i < arr.length - 1; i++) {
        int difference = arr[i + 1] - arr[i];
        
        if (difference < minimumDifference) {
            minimumDifference = difference;
            
            if (minimumDifference == 0) {
                return 0;
            }
        }
    }
    
    return minimumDifference;
    
    20|
    Permalink
    View more Comments..
  • _sss1
    5 years ago+ 4 comments

    Is it possible to solve it better than O (n log n)?

    17|
    Permalink
    View more Comments..
  • dejno
    3 years ago+ 1 comment

    JavaScript version that I like and feel is readable and clean.

    function minimumAbsoluteDifference(arr) {
        // Sort
        arr.sort();
    
        let minDiff;
    
        // Loop through the consecutive pairs, if 0 return, else set min diff
        for (let i = 0; i < arr.length; i++) {
            let absDiff = Math.abs(arr[i+1] - arr[i]);
            if (!minDiff || absDiff < minDiff) minDiff = absDiff;
            if (minDiff === 0) return 0;
        }
    
        return minDiff;
    }
    
    8|
    Permalink
Load more conversations

Need Help?


View editorial
View top submissions
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature