Skip to the content

The smallest difference

Problem

Write a function that takes a list of numbers and returns the smallest difference there is between two of them.

With 1, 5, 3, 19, 18 and 25 the answer is 1, because 18 and 19 are the two that sit closest together.

The rules: the difference is never negative, so measure the distance between the two, not which one comes first. If a number is repeated, the difference is 0. With fewer than two numbers there is no pair to compare: in that case you return 0.

You can compare all of them against all the others, but there is a shorter road: sort the list and compare only neighbors, because the two closest numbers always end up side by side.

Examples

  • Two that sit close

    [1, 5, 3, 19, 18, 25] → 1

  • In a row

    [4, 3, 2, 6] → 1

  • Far apart

    [30, 5, 20, 9] → 4

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def min_difference(numbers):
    pass

JavaScript

function minDifference(numbers) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n log n) challenges

See all challenges →