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.
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
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;
} def find_min_difference(times):
m = sorted(int(t[:2]) * 60 + int(t[3:]) for t in times)
best = 1440 + m[0] - m[-1] # wrap around midnight
for a, b in zip(m, m[1:]):
best = min(best, b - a)
return best int findMinDifference(vector<string>& times) {
vector<int> m;
for (auto& t : times) m.push_back(stoi(t.substr(0, 2)) * 60 + stoi(t.substr(3)));
sort(m.begin(), m.end());
int best = 1440 + m[0] - m.back(); // wrap around midnight
for (size_t i = 1; i < m.size(); i++) best = min(best, m[i] - m[i - 1]);
return best;
} function findMinDifference(times) {
const m = times.map((t) => +t.slice(0, 2) * 60 + +t.slice(3)).sort((a, b) => a - b);
let best = 1440 + m[0] - m[m.length - 1]; // wrap around midnight
for (let i = 1; i < m.length; i++) best = Math.min(best, m[i] - m[i - 1]);
return best;
} The variations
-
1Sort, then compare neighbours
Convert to numbers, sort, check adjacent pairs and the first-last wrap.
-
2More practice
More problems that use this pattern. Try them once the variations above feel easy.
Problems
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).
Lesson done
Back to Arrays & Hashing →Mark it done once you can write the template from memory and you have solved the worked examples yourself.