↓Skip to main content
  1. LeetCode/

LeetCode 414: Third Maximum Number

·1 min· ·
LeetCode Easy Array Sorting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-24

  • Submissions: Accepted (first try)

Approach
#

The problem asks for the third largest distinct value. Keep first > second > third in one pass, skip values already present, and shift everything down when a new maximum arrives (Greedy Template 1). With fewer than three distinct values return the maximum. O(n), no sorting.

My Attempts
#

Passed on the first try with sorted(set(nums))[-3], falling back to max(nums) via try/except when fewer than three exist, in O(n log n).

Solution
#

class Solution:
    def thirdMax(self, nums: List[int]) -> int:
        top = []
        for x in nums:
            if x in top:
                continue
            top.append(x)
            top.sort(reverse=True)
            if len(top) > 3:
                top.pop()
        return top[2] if len(top) == 3 else top[0]

Complexity
#

Time O(n), space O(1) (top holds at most 4).

Mistakes to Avoid
#

  • Count distinct values only; repeats do not count.

Interview Explanation
#

I keep at most three distinct largest values, skipping repeats and trimming to three after each insert, then return the third if it exists or else the maximum. Time O(n).

Related

LeetCode 455: Assign Cookies
·2 mins
LeetCode Easy Array Two-Pointers Greedy Sorting
LeetCode 455 note: sort children and cookies, satisfying the least greedy child with the smallest cookie that suffices; each pointer walks once
LeetCode 217: Contains Duplicate
·1 min
LeetCode Easy Array Hash-Table Sorting
LeetCode 217 note: if converting to a set shortens the array, there is a duplicate
LeetCode 169: Majority Element
·2 mins
LeetCode Easy Array Hash-Table Divide-and-Conquer Sorting
LeetCode 169 note: Boyer-Moore voting, where different values cancel in pairs and the survivor is the one appearing more than half the time
LeetCode 448: Find All Numbers Disappeared in an Array
·1 min
LeetCode Easy Array Hash-Table
LeetCode 448 note: use the array itself as the hash table, marking nums[x - 1] negative for each x; positions still positive are the missing numbers
LeetCode 463: Island Perimeter
·2 mins
LeetCode Easy Array Depth-First-Search Breadth-First-Search Matrix
LeetCode 463 note: each land cell contributes 4 edges, minus 2 for each land neighbor above or to the left
LeetCode 495: Teemo Attacking
·2 mins
LeetCode Easy Array Simulation
LeetCode 495 note: each attack contributes min(gap to the next attack, duration), and the last one contributes the full duration