⬅ Previous Topic
Find Second Largest in ArrayNext Topic ⮕
Reverse Array using Two Pointers⬅ Previous Topic
Find Second Largest in ArrayNext Topic ⮕
Reverse Array using Two PointersTopic Contents
Given an array of numbers, your task is to find the second smallest element in the array.
If a second smallest number cannot be found, return -1
.
arr
.min_val
and second_min
to Infinity
.min_val
, update second_min
to min_val
, and then update min_val
.second_min
and not equal to min_val
, update second_min
.second_min
.def find_second_smallest(arr):
min_val = float('inf')
second_min = float('inf')
for num in arr:
if num < min_val:
second_min = min_val
min_val = num
elif num < second_min and num != min_val:
second_min = num
return second_min
# Sample Input
arr = [30, 20, 10, 50, 60, 40]
print("Second Smallest:", find_second_smallest(arr))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n) | Even in the best case, all elements must be checked at least once to ensure the smallest and second smallest are correctly identified. |
Average Case | O(n) | The algorithm iterates through the array exactly once, making one comparison per element. |
Average Case | O(n) | Regardless of element arrangement, all values must be visited to determine the second smallest accurately. |
O(1)
Explanation: The algorithm uses a constant amount of space, with only two variables needed for tracking smallest and second smallest.
Let's find the second smallest number in the array using a loop.
Initialize min = Infinity
and secondMin = Infinity
.
Current element is 30
. Compare with min = Infinity
and secondMin = Infinity
.
30 is smaller than current min. Update: secondMin = Infinity
, min = 30
.
Current element is 20
. Compare with min = 30
and secondMin = Infinity
.
20 is smaller than current min. Update: secondMin = 30
, min = 20
.
Current element is 10
. Compare with min = 20
and secondMin = 30
.
10 is smaller than current min. Update: secondMin = 20
, min = 10
.
Current element is 50
. Compare with min = 10
and secondMin = 20
.
No update required.
Current element is 60
. Compare with min = 10
and secondMin = 20
.
No update required.
Current element is 40
. Compare with min = 10
and secondMin = 20
.
No update required.
Second Smallest Element = 20
⬅ Previous Topic
Find Second Largest in ArrayNext Topic ⮕
Reverse Array using Two PointersYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.