Drill

ProblemsGo › data

The second highest number

easydataArraysGo

A leaderboard shows only the top name, but the report also wants the runner-up.

secondLargest(values: 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 secondLargest(values []int) int {
	
}

Worked examples

CallResult
secondLargest([]int{3, 1, 2})2
secondLargest([]int{10, 10, 9})9
secondLargest([]int{4, 1, 4, 2, 3})3
secondLargest([]int{5})-1

Hint

Walk once keeping the two best so far, and ignore a value equal to the current best.

Reference solution in Go
func secondLargest(values []int) int {
	best, second := 0, 0
	found, started := false, false
	for _, v := range values {
		if !started {
			best = v
			started = true
			continue
		}
		if v > best {
			second = best
			found = true
			best = v
		} else if v < best {
			if !found || v > second {
				second = v
				found = true
			}
		}
	}
	if found {
		return second
	}
	return -1
}

The same problem in another language

More data problems in Go