Skip to main content
Beginnercoding Verified

Write a program to return the third largest number in an array (ask whether the values are unique).

ReportedSource: GeeksforGeeks interview experience: TCS Ninja + Digital

Quick answer

Track first/second/third distinct maxima in one pass, shifting values down when a bigger one appears; skip duplicates; return None if fewer than 3 distinct. O(n), O(1).

Constraints

  • Input: first line n, second line n integers (they may repeat and may be negative).
  • Output: the third largest distinct value, or NONE if there are fewer than 3 distinct values.
  • 1 <= n <= 100000; values fit in a 32-bit signed integer.

Sample I/O

in: 5 4 1 9 7 3

out: 4

in: 4 10 10 9 8

out: 8

in: 4 5 5 2 2

out: NONE

Loading editor…
Output

Sign up to run your code in the sandbox.

Sign up to run code and get an AI review

You can read and edit the challenge freely — running it in the sandbox and getting AI feedback need a free account.

Sign up free

Hints

Reference solution

Clarify first (the candidate in this report did): may values repeat, and should duplicates count? Below, "third largest" means third largest distinct value.

Single pass, O(n) time, O(1) space.

main.py
def third_largest(a):
    first = second = third = None
    for x in a:
        if x in (first, second, third):
            continue
        if first is None or x > first:
            first, second, third = x, first, second
        elif second is None or x > second:
            second, third = x, second
        elif third is None or x > third:
            third = x
    return third   # None if fewer than 3 distinct values

Simpler alternatives to mention. sorted(set(a), reverse=True)[2] is O(n log n) but readable; heapq.nlargest(3, set(a)) is O(n). Explain why the single pass is optimal when n is large.

Edge cases. Fewer than three distinct values, negative numbers, all elements equal.

Discussion