Arrays & Hashing · Pattern 26 of 26

Sort first, then compare neighbours

After sorting, the closest pair is always next to each other. One sort and one pass, plus the wrap-around pair for circular values like times of day.

2 variations · 2 problems · 1 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Minimum difference between any two values
  • Circular values (clock times, angles)

The template

Sorting
int findMinDifference(String[] times) {
    int[] m = new int[times.length];
    for (int i = 0; i < times.length; i++)
        m[i] = Integer.parseInt(times[i].substring(0, 2)) * 60 + Integer.parseInt(times[i].substring(3));
    Arrays.sort(m);
    int best = 1440 + m[0] - m[m.length - 1];             // wrap around midnight
    for (int i = 1; i < m.length; i++) best = Math.min(best, m[i] - m[i - 1]);
    return best;
}

The variations

  1. 1Sort, then compare neighbours

    Convert to numbers, sort, check adjacent pairs and the first-last wrap.

  2. 2More practice

    More problems that use this pattern. Try them once the variations above feel easy.

Mistakes to avoid

  • Forgetting the wrap-around pair (23:59 and 00:00 are 1 minute apart).
  • Comparing every pair: O(n²) when a sort gives O(n log n).
Back to Arrays & Hashing →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.