04 / 19

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

Second Largest Element

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.

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

Scenario Questions

0-2 years experience
  1. 1

    Given an unsorted integer array of size N, how would you write a function to return the second largest value?

  2. 2

    If you can only use O(1) extra space, what approach would you take to find the second largest element?

  3. 3

    What would your function return for an array that contains only one element?

2-5 years experience
  1. 1

    We 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. 2

    A teammate implemented second‑largest by sorting the whole array. Explain why that could be problematic in production and suggest a better alternative.

  3. 3

    If 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. 1

    Our 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. 2

    Suppose 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. 3

    When scaling the second‑largest calculation across shards, what consistency model would you choose and why?

8+ years experience
  1. 1

    We 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. 2

    If 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. 3

    Discuss 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?