Drill

ProblemsTypeScript › data

The second highest number

easydataTypeScript

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

secondLargest(values: list<int>) → int

Solve it in the editor →

Where you start

function secondLargest(values: number[]): number {
  
}

Worked examples

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

Hint

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

Reference solution in TypeScript
function secondLargest(values: number[]): number {
  let found = false;
  let second = 0;
  let best = 0;
  let started = false;
  for (const v of 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;
      }
    }
  }
  return found ? second : -1;
}

The same problem in another language

More data problems in TypeScript