Python Program to Find Second Largest Number
Finding the second largest number in a list is a common coding problem that helps build logic and understanding of lists.
It is frequently asked in interviews and competitive programming.
1. Understanding the Problem
Given a list of numbers, find the second largest unique number.
Input: [10, 20, 4, 45, 99] Output: 45
2. Method 1: Using Sorting
arr = list(map(int, input().split()))
arr = list(set(arr))
arr.sort()
print(arr[-2])
Removes duplicates and sorts the list.
3. Method 2: Using Loop
arr = list(map(int, input().split()))
first = second = float('-inf')
for num in arr:
if num > first:
second = first
first = num
elif num > second and num != first:
second = num
print(second)
Efficient single-pass solution.
4. Method 3: Using heapq
import heapq
arr = list(map(int, input().split()))
unique = list(set(arr))
print(heapq.nlargest(2, unique)[-1])
Uses heap for efficient extraction.
5. Method 4: Using Function
def second_largest(arr):
unique = list(set(arr))
unique.sort()
return unique[-2]
print(second_largest([1, 5, 3, 9, 7]))
Encapsulates logic for reuse.
6. Method 5: Handling Edge Cases
arr = list(map(int, input().split()))
unique = list(set(arr))
if len(unique) < 2:
print("No second largest element")
else:
unique.sort()
print(unique[-2])
Handles cases with insufficient elements.
7. Algorithm
1. Take input list.
2. Remove duplicates.
3. Find largest and second largest.
4. Return second largest.
8. Common Mistakes
1. Not removing duplicates.
2. Index errors when list is small.
3. Confusing second largest with second element.
4. Not handling negative values.
9. Applications
1. Ranking systems.
2. Data analysis.
3. Competitive programming.
4. Interview questions.
Conclusion
Finding the second largest number is a key problem for mastering list operations.
Using optimized approaches improves performance for large datasets.
Codecrown