PPractick

DSA interview question

Second Largest Element in an Array

Easy · Algorithms · Topics: array, linear search

The problem

A leaderboard shows the top score and, right below it, the runner-up score, which must be strictly less than the top score (if two players tie for first, the runner-up is the next distinct score). If every player has the same score, there's no runner-up, and the screen shows "-1". Sorting all the scores just to read two values is wasteful; the classic interview answer finds both in a single pass by tracking the largest and second-largest so far.

Example: [12, 35, 1, 10, 34, 1] → 34.

Function signature

int secondLargest(const vector<int>& a);  // largest value strictly below the maximum, or -1 if none

Test cases

Input aOutputExplanation
[12, 35, 1, 10, 34, 1]34
[10, 5, 10]5The duplicate maximum doesn't count as second
[10, 10, 10]-1No value below the maximum
[7]-1Only one element
[1, 2]1
[2, 1]1Order doesn't matter

(Confirm: values are positive (as in the GeeksforGeeks version), so -1 unambiguously means "no second largest".)

How interviewers phrase it

Clarifying questions to ask

  1. Must the second largest be strictly smaller than the largest, or can duplicates of the max count?
  2. What should be returned if it doesn't exist?
  3. Can values be negative? (Then -1 is a poor sentinel.)
  4. Is one pass required?

Follow-ups to expect

  1. "What are the update rules?"
  2. "Why not sort?"
  3. "What if values can be negative?"
  4. "How would you get the k-th largest?"
  5. "Second smallest?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in