Logo
    Logo

    ©️ 2020-2026, Akhil Abraham.

    LinkedInGitHubMediumX
    Akhil Abraham
    Akhil Abraham
    /Posts
    Posts
    /LeetCode
    LeetCode
    /
    LeetCode
    /0414 - Third Maximum Number
    0414 - Third Maximum Number
    0414 - Third Maximum Number
    0414 - Third Maximum Number

    0414 - Third Maximum Number

    Difficulty
    Easy
    Language
    Python
    URL
    https://leetcode.com/problems/third-maximum-number/

    Solution 1 - Sorting with Set

    Convert the array to a set to remove duplicates, sort in descending order, and return the third element if it exists — otherwise return the maximum.

    TimeComplexity:O(nlog⁡n)TimeComplexity: O(n \log n)TimeComplexity:O(nlogn)
    SpaceComplexity:O(n)SpaceComplexity: O(n)SpaceComplexity:O(n)

    Solution 2 - Three Variables Tracking

    Track the top three distinct maximums using three variables initialized to negative infinity. Iterate through the array once, updating the variables as larger distinct values are found.

    TimeComplexity:O(n)TimeComplexity: O(n)TimeComplexity:O(n)
    SpaceComplexity:O(1)SpaceComplexity: O(1)SpaceComplexity:O(1)
    """ 0414.1 - Solution 1 - Sorting with Set """
    
    #####################################################################################
    # Imports
    #####################################################################################
    from typing import List
    
    #####################################################################################
    # Classes
    #####################################################################################
    class Solution:
        """Solution Class"""
    
        def thirdMax(self, nums: List[int]) -> int:
            """Third Maximum Number Function"""
            unique = sorted(set(nums), reverse=True)
            return unique[2] if len(unique) >= 3 else unique[0]
    
    
    #####################################################################################
    # Functions
    #####################################################################################
    def testcase():
        """Test Function"""
        print(Solution().thirdMax([3, 2, 1]))       # Expected: 1
        print(Solution().thirdMax([1, 2]))           # Expected: 2
        print(Solution().thirdMax([2, 2, 3, 1]))     # Expected: 1
    
    
    #####################################################################################
    # Main
    #####################################################################################
    if __name__ == "__main__":
        testcase()
    
    """ 0414.2 - Solution 2 - Three Variables Tracking """
    
    #####################################################################################
    # Imports
    #####################################################################################
    from typing import List
    import math
    
    #####################################################################################
    # Classes
    #####################################################################################
    class Solution:
        """Solution Class"""
    
        def thirdMax(self, nums: List[int]) -> int:
            """Third Maximum Number Function"""
            first = second = third = -math.inf
    
            for num in nums:
                if num in (first, second, third):
                    continue
                if num > first:
                    first, second, third = num, first, second
                elif num > second:
                    second, third = num, second
                elif num > third:
                    third = num
    
            return third if third != -math.inf else first
    
    
    #####################################################################################
    # Functions
    #####################################################################################
    def testcase():
        """Test Function"""
        print(Solution().thirdMax([3, 2, 1]))       # Expected: 1
        print(Solution().thirdMax([1, 2]))           # Expected: 2
        print(Solution().thirdMax([2, 2, 3, 1]))     # Expected: 1
    
    
    #####################################################################################
    # Main
    #####################################################################################
    if __name__ == "__main__":
        testcase()