Find Second Smallest
Find second smallest element in array.
AdvancedPhase 4 - Level 5: Logical & AppliedExample 4 of 14
find-second-smallest.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 smallest8if n < 2:9 print("Array too small")10else:11 # Find min12 min_val = min(arr)1314 # Find second min15 second_min = None16 for element in arr:17 if element != min_val:18 if second_min is None or element < second_min:19 second_min = element2021 if second_min is None:22 print("All elements are same")23 else:24 print(f"Second smallest: {second_min}")
Output
Enter array size: 5 Element 1: 10 Element 2: 5 Element 3: 20 Element 4: 3 Element 5: 15 Second smallest: 5
What's going on
Find min first, then find smallest that's not min.
Key Concepts:
First find minimum
Then find smallest excluding min
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