Python Program to Find Second Largest Number in List

Day 9 of my #100DaysOfCode challenge 🚀 Today I worked on a Python program to find the second largest number in a list using an optimized approach. The goal was to solve the problem without sorting the list and by traversing it only once. What the program does: • Takes a list of numbers as input • Handles edge cases where a second largest element does not exist • Tracks the largest and second largest values efficiently • Returns the second largest number How the logic works: If the list contains fewer than two elements, the function returns None Two variables (first and second) are initialized with negative infinity The list is traversed one element at a time If the current number is greater than first: – second is updated with the previous first – first is updated with the current number If the number lies between first and second, second is updated After traversal, the function returns the second largest value Example: Input list: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] Output: Second largest number = 6 Key learnings from Day 9: – Solving problems without built-in sorting – Using conditional logic effectively – Understanding single-pass algorithms – Writing optimized Python code #100DaysOfCode #Day9 #Python #PythonProgramming #ProblemSolving #DataStructures #CodingChallenge #LearningInPublic #BTech #CSE #AIandML #VITBhopal #TechJourney

  • text

To view or add a comment, sign in

Explore content categories