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:
-
Initialize two variables, large and sec_large, to None.
-
Check if the input list l1 has at least 2 elements (using len(l1) > 1).
-
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.
-
-
If the list has fewer than 2 elements, return the message “At least 2 numbers required.”
-
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?
-
Checkout our Interview prep page, It might help you.