educative.io

Second maximum task may need clarification

Hi, the task about finding a second maximum value might need some clarification.

Do we need to find the second largest number?
Ex. in a list [5,2,8,8], do you expect the result to be 5, because 8 is the largest number,
or
8, because this list has two maximum numbers, so… kind of… both of them take slots of two largest numbers?
If former, then there’s a bug in Solution 3.

Dear Dennis,

Thanks for reaching out. We’re glad to hear from you.
Your query has been logged, we’ll get back to you shortly.

Thanks & Regards!
Team Educative

Hi Dennis,

Thank you for reaching out!

So, the question does assume that we need to find the second largest number even if duplicates of the first largest number exist. We have updated solution #3 accordingly, you should be able to see the changes now. Also note that this assumption does break solution #1 which is why it wasn’t a good solution to begin with. Let me know if this helps :slight_smile:

If you have any further queries/comments/suggestions, feel free to let us know!

Ayesha Basit Alvi | Technical Content Developer

A simpler and more readable solution #3:

def find_second_maximum(lst):
    # Initialize maximum and second_maximum variables
    maximum = second_maximum = float('-inf')
    for ele in lst:
        # First check if the current element is the new maximum
        if ele > maximum:
            # Promote the old maximum as the second maximum
            second_maximum = maximum
            # Set the new maximum
            maximum = ele
        # Check if the current element is the new second maximum
        # Only set if the element is also not equal to current maximum
        elif ele > second_maximum and ele != maximum:
            second_maximum = ele
    # Return second maximum
    if second_maximum > float('-inf')
        return second_maximum