Program to find second largest number optimized

Program to find second largest number optimized This is question recently asked me in the interview, So I wanted to share it. happy coding and all the best for your interview.

PYTHON PROGRAM

Luminari

7/14/20241 min read

Question:

Second largest number complete solution

example : [22,3,4,5,6,11,3,33] output should be : 22

I know this is the common question asked in interview, there are number of solutions to this. But what about optimization?. This solution will give you optimized implementation

Logic:

  1. Initialize two variables, large and sec_large, to None.

  2. Check if the input list l1 has at least 2 elements (using len(l1) > 1).

  3. If the condition is met, iterate through each element i in the list:

    • If large is None or i is greater than large, update large and sec_large.

    • Otherwise, if sec_large is None or i is between sec_large and large, update sec_large.

  4. If the list has fewer than 2 elements, return the message “At least 2 numbers required.”

  5. Otherwise, return a tuple containing sec_large (the second largest element) and large (the largest element).

Solution in python:

At the time of interview i went with 2 for loop as i was prepared for this question. But interviewer asked me to improve this over and over finally he was satisfied with the below implementation

data = [10, 5, 20, 15, 30]

print(second_large(data)) # Output: (20, 30)

Preparing for interview?