Third Maximum Number Problem in Java

Finding the third maximum number in an array is a common problem in coding interviews and competitive programming. The problem can be approached in multiple ways, each with its own trade-offs in terms of time and space complexities. In this section, we will explore three different methods to solve third maximum number problem in Java.

Using Sorting: This method involves sorting the array and then finding the third distinct maximum number.

Using a Single Pass with Three Variables: This approach maintains three variables to keep track of the top three distinct maximum numbers while iterating through the array.

Using a Priority Queue: This method leverages a min-heap to dynamically keep track of the top three distinct maximum numbers as we process the array.

By understanding these methods, you can choose the most appropriate solution depending on the problem constraints and performance requirements.

Method 1: Using Sorting

Sort the array and then traverse from the end to find the third distinct maximum number.

File Name: ThirdMaxUsingSorting.java

Output:

 
Third Maximum Number: 4   

Time Complexity: O(nlogn) due to sorting.

Space Complexity: O(1) if sorting is done in-place, otherwise O(n).

Method 2: Using a Single Pass with Three Variables

Approach: Use three variables to keep track of the top three distinct maximum numbers.

File Name: ThirdMaxUsingSinglePass.java

Output:

 
Third Maximum Number: 4   

Time Complexity: O(n) since we only pass through the array once.

Space Complexity: O(1) since we use a constant amount of extra space.

Method 3: Using a Priority Queue

Use a min-heap (priority queue) to keep track of the top three distinct maximum numbers.

File Name: ThirdMaxUsingPriorityQueue.java

Output:

 
Third Maximum Number: 4   

Time Complexity: O(nlog3)=O(n) since the heap size is at most 3.

Space Complexity: O(1) if we consider the heap size as a constant.

Conclusion

Finding the third maximum number in an array is a problem with multiple viable solutions, each suited to different scenarios. The sorting method, while easy to implement, may not be the best choice for large datasets due to its O(nlogn) time complexity.

The single-pass approach with three variables offers an efficient O(n) solution with constant space usage, though it requires careful handling of distinct values. The priority queue method strikes a balance between simplicity and efficiency, maintaining O(n) time complexity with minimal space overhead.

Understanding these methods allows you to select the most appropriate solution based on the constraints and performance requirements of your specific problem, ensuring an effective and optimized approach to finding the third maximum number in an array.