Find Second Largest
Find second largest element in array.
AdvancedPhase 4 - Level 5: Logical & AppliedExample 3 of 14
find-second-largest.py
1# Take array2n = int(input("Enter array size: "))3arr = []4for i in range(n):5 arr.append(int(input(f"Element {i+1}: ")))67# Find second largest8if n < 2:9 print("Array too small")10else:11 # Find max12 max_val = max(arr)1314 # Find second max15 second_max = None16 for element in arr:17 if element != max_val:18 if second_max is None or element > second_max:19 second_max = element2021 if second_max is None:22 print("All elements are same")23 else:24 print(f"Second largest: {second_max}")
Output
Enter array size: 5 Element 1: 10 Element 2: 5 Element 3: 20 Element 4: 15 Element 5: 20 Second largest: 15
What's going on
Find max first, then find largest that's not max.
Key Concepts:
First find maximum
Then find largest excluding max
Handle case where all same
🔗Related Content
- 📖
Phase 4 - Learn Concepts
Review Phase 4 concepts and explanations
- 📝
Phase 4 - Quiz
Test your Phase 4 understanding with quiz questions
- 💻
Phase 4 - All Practice Problems
Explore all practice problems for Phase 4
- 🎓
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- 🧠
Logic Building Overview
Learn about the complete logic building curriculum