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.
Minimum Absolute Difference in an Array
Minimum Absolute Difference in an Array
Sort by
recency
|
705 Discussions
|
Please Login in order to post a comment
I haven't seen anyone talk about the intuition behind their solution so here is mine.
Brute Force: You are trying to find the distance between pairs of numbers in the array. So the brute force solution is to compare every number to every other number and get the min distance out of all of them, which would take O(n^2) time if there are n numbers in the array (n numbers to check for each of the n numbers).
A Better Solution: At this point I already know this problem is under the greedy category because it's HackerRank but if it was an interview I usually go through my algorithmic tool bag and think about what makes sense for the problem. It's not a graph, would a hashmap help? I couldn't come up with anything. Dynamic programming? Maybe. So I would need overlapping sub problems, and optimal substructure, one thing I know is greedy problems are related to dynamic programming problems because they also have optimal substructure but not overlapping sub problems, so I usually think about a greedy solution before a dynamic programming one (not sure if that is right but it's what I do). Ok so if I break the problem down and only look at the relationship between two numbers in the array, is there anyway to know that one number is definitely larger (or smaller) than the other? Well if the numbers are in order yes! Then you for sure know the relationship between the two numbers, so sorting the array would do that.
If you sort the array, then you only need to compare each number at index i with it's neighbor at index i + 1 that is greater than or equal to it (Assuming the array is sorted in ascending order) by scanning the array from beginning to end. For example, assume you have 3 numbers, a, b, and c in the array, and for simplicity assume that each number is unique. Now assume in the sorted array the order is a < b < c. Then the distance between a and b must be less than the distance between a and c, because the numbers are sorted and we know that b is less than c. So in other words b is closer to a in value than any number that comes after b and that is why you only have to compare each number with it's neighbor that is greater than or equal to it with a scan from left to right if the array is in ascending order. Sorting the array can be done fastest in O(n log n) time if there are n elements in the array and scanning the array takes O(n) time but is bounded above by the time it takes to sort the array and so you get O(n log n) time for this solution.
Here is my c++ solution, you can find the explanation here : https://youtu.be/6SnD7A1TbJQ
My Java solution with o(n log n + n) time complexity and o(1) space:
Here is my Python solution!