Find Second Smallest

Find second smallest element in array.

AdvancedPhase 4 - Level 5: Logical & AppliedExample 4 of 14
find-second-smallest.py
1# Take array
2n = int(input("Enter array size: "))
3arr = []
4for i in range(n):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7# Find second smallest
8if n < 2:
9 print("Array too small")
10else:
11 # Find min
12 min_val = min(arr)
13
14 # Find second min
15 second_min = None
16 for element in arr:
17 if element != min_val:
18 if second_min is None or element < second_min:
19 second_min = element
20
21 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