Find Second Smallest
Find the second distinct smallest list value with Python. Students exclude all copies of the minimum and use None until a valid replacement candidate appears.
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
In this one
- Exclude every minimum
- Track a nullable candidate
- Separate size from distinctness
How it works
- 1
Handle input with fewer than two entries.
- 2
Find min_val and skip every equal value.
- 3
Keep the smallest remaining candidate or report all-equal input.
Edge cases
What if there are two identical values?
What if there are two identical values?
There is no second distinct minimum.
What does [0, 2, 1] return?
What does [0, 2, 1] return?
One.
What's going on
min_val is found before the scan. Values equal to it are skipped, and smaller qualifying candidates replace second_min.
For [1, 1, 4, 3], the result is three, not another one. None distinguishes no candidate from a genuine numeric value such as zero. Too-short input and all-equal input are handled before a result is printed.
What if there are two identical values? There is no second distinct minimum.
What does [0, 2, 1] return? One.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which values are skipped?
Pick an answer to check it.
Question 2
What if there are two identical values?
Pick an answer to check it.
Questions people ask
What if there are two identical values?
There is no second distinct minimum.
What does [0, 2, 1] return?
One.
Which values are skipped?
Every value equal to the minimum.
๐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