Drill

ProblemsGo › monitoring

The longest silence between heartbeats

mediummonitoringArraysMathGo

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

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func longestGap(timestamps []int) int {
	
}

Worked examples

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

Hint

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

Reference solution in Go
func longestGap(timestamps []int) int {
	if len(timestamps) < 2 {
		return 0
	}
	s := append([]int{}, timestamps...)
	sort.Ints(s)
	worst := 0
	for i := 1; i < len(s); i++ {
		if d := s[i] - s[i-1]; d > worst {
			worst = d
		}
	}
	return worst
}

The same problem in another language

More monitoring problems in Go