File: third-maximum-number/solution.py

Date: 2026-06-06

Time: 19:28

Purpose

This file solves LeetCode 414 — Third Maximum Number. It owns a single responsibility: given a list of integers, return the third distinct maximum, or fall back to the overall maximum if fewer than three distinct values exist.

Key Components

third_max(nums: list[int]) -> int

The sole public function. Contract:

Patterns

Three-variable tracking with None sentinels. Instead of using a set or sorted structure, the solution maintains exactly three variables (first, second, third) initialized to None. This is a common competitive-programming idiom for "top-K distinct" problems — it avoids allocating extra data structures and runs in O(n) time with O(1) space.

Duplicate skipping via tuple membership. Line if n in (first, second, third) filters duplicates by checking against all three tracked values. This works because None in (first, second, third) is always true when a slot is None — but the check happens *before* the comparison branches, and a None slot means "not yet filled," so a duplicate None value in nums is impossible (integers only). The None sentinel is safe here because nums contains only int values, never None.

Cascading demotion. When a new maximum is found (n > first), the current first is demoted to second, and second to third, via tuple unpacking: first, second, third = n, first, second. This single-line swap avoids temporary variables and guarantees no value is lost.

Dependencies

Flow

1. Initialize first, second, third to None.

2. For each n in nums:

3. Return third if it was filled, otherwise first (the global max).

The entire pass is a single linear scan — O(n) time, O(1) space.

Invariants

Error Handling

None. The function assumes the caller upholds the precondition (non-empty list of integers). An empty list would cause the function to return None (since first stays None), which violates the -> int return type — but this matches LeetCode's guarantee that nums is non-empty.

Topics to Explore

Beliefs