Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

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

In this one

  • Exclude every minimum
  • Track a nullable candidate
  • Separate size from distinctness

How it works

  1. 1

    Handle input with fewer than two entries.

  2. 2

    Find min_val and skip every equal value.

  3. 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.