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:
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.
My interests
As a techie + proud Hindhu i love to know/write about technology, spiritual knowledge.
Hey!, I am not living library. But if there is topic if you want me to cover, I will do my research and write about it, if it is unfamiliar to me. Its fun to learn and grow together.
Contact ID
Contact
author@luminari.info
© 2024. All rights reserved.
Well usually everyone goes with explaining containers and pod, like workloads but we feel it's better to know architectures first with those questions in the head. we will explain about work loads but now lets jump in with architecture and components.
Well usually everyone goes with explaining containers and pod, like workloads but we feel it's better to know architectures first with those questions in the head. we will explain about work loads but now lets jump in with architecture and components.