Drill

ProblemsJavaScript › monitoring

The longest silence between heartbeats

mediummonitoringJavaScript

A service sends a heartbeat every so often. The longest gap between two of them is how long it might have been down without anyone noticing.

longestGap(timestamps: list<int>) → int

Solve it in the editor →

Where you start

function longestGap(timestamps) {
  
}

Worked examples

CallResult
longestGap([100,130,200,205])70
longestGap([205,100,200,130])70
longestGap([10,20])10
longestGap([42])0

Hint

Sort first. Without that, "next to each other" means nothing.

Reference solution in JavaScript
function longestGap(timestamps) {
  if (timestamps.length < 2) return 0;
  const s = timestamps.slice().sort((a, b) => a - b);
  let worst = 0;
  for (let i = 1; i < s.length; i++) worst = Math.max(worst, s[i] - s[i - 1]);
  return worst;
}

The same problem in another language

More monitoring problems in JavaScript