04 / 19

How do you find the second largest element in an unsorted array?

Difficulty: 2/10
array traversal, single-pass algorithm, space optimization

Second Largest Element

The optimal single-pass solution maintains the largest and second-largest distinct values while scanning the array once. This avoids sorting, which would require O(n log n) time.

javascript
  1. 1

    Time complexity: O(n).

  2. 2

    Auxiliary space: O(1).

  3. 3

    The comparison x != first ensures the second value is distinct.

  4. 4

    Edge cases such as fewer than two distinct values should be handled explicitly.

Scenario Questions

0-2 years experience

  1. 1Given an unsorted integer array of size N, how would you write a function to return the second largest value?
  2. 2If you can only use O(1) extra space, what approach would you take to find the second largest element?
  3. 3What would your function return for an array that contains only one element?

2-5 years experience

  1. 1We have a live leaderboard stored as an unsorted list that updates concurrently; how would you efficiently find the runner‑up score and what pitfalls might you watch for?
  2. 2A teammate implemented second‑largest by sorting the whole array. Explain why that could be problematic in production and suggest a better alternative.
  3. 3If the array may contain duplicate maximum values, how would you ensure you still return the correct second distinct largest element?

5-8 years experience

  1. 1Our analytics pipeline processes millions of records per minute and must emit the second highest metric per batch without storing the entire batch in memory. Design an algorithm/component to achieve this, discussing time/space trade‑offs.
  2. 2Suppose data arrives as a stream and you must maintain the second largest element at any point. How would you structure the service, and how would you handle node failures or restarts?
  3. 3When scaling the second‑largest calculation across shards, what consistency model would you choose and why?

8+ years experience

  1. 1We are migrating a legacy monolith that computes ranking statistics, including second highest, to a microservices architecture. How would you refactor this logic to be reusable, testable, and performant across services?
  2. 2If the second‑largest calculation becomes a critical KPI for many teams, what governance, observability, and versioning strategies would you put in place to avoid regressions?
  3. 3Discuss the trade‑offs between implementing the second‑largest logic in the database using window functions versus in the application layer for a globally distributed system.

Follow-up Questions

  • How does your solution handle duplicate maximum values?
  • What are the time and space complexities of your approach?
  • Can you adapt it to work on a continuous data stream?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.