Bloomberg LP Interview Question
Software Engineer InternsCountry: United States
Interview Type: Phone Interview
def find_min_diff(arr):
arr = sorted(arr)
min_diff = None
for i in range(1, len(arr)):
diff = arr[i]-arr[i-1]
if min_diff is None or min_diff>diff:
min_diff = diff
return min_diff
if __name__=='__main__':
data = [
[[100, 20, 52, 18, -4], 2]
]
print('Find minimum difference between items in array')
for d in data:
print('array is', d[0], 'result', find_min_diff(d[0]), 'expected', d[1])
If the question says that the difference has to be absolute, then sorting the array and finding the adjacent difference is the most appropriate solution. But if the question says finding the smallest difference out of all the pairs from an array i.e min_diff can be less than 0, then we can find it with the following code.
MIN_DIFF(ARRAY){
MAX_ELEMENT := FIND_MAX(ARRAY) //O(n)
MIN_ELEMENT := FIND_MIN(ARRAY) //O(n)
return MIN_ELEMENT - MAX_ELEMENT
}
This this runs in O(n) time and O(1) space.
- Loghman Barari October 24, 2019