Logic Building
# Take array
n = int(input("Enter array size: "))
arr = []
for i in range(n):
arr.append(int(input(f"Element {i+1}: ")))
# Find second smallest
if n < 2:
print("Array too small")
else:
# Find min
min_val = min(arr)
# Find second min
second_min = None
for element in arr:
if element != min_val:
if second_min is None or element < second_min:
second_min = element
if second_min is None:
print("All elements are same")
else:
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
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