⬅ Previous Topic
Find Maximum and Minimum in Array using LoopNext Topic ⮕
Find Second Smallest in Array⬅ Previous Topic
Find Maximum and Minimum in Array using LoopNext Topic ⮕
Find Second Smallest in ArrayTopic Contents
Given an array of integers, your task is to find the second largest element in the array.
-1
.arr
.max_val
and second_max
to -Infinity
.max_val
, update second_max
to max_val
, and then update max_val
.second_max
and not equal to max_val
, update second_max
.second_max
.def find_second_largest(arr):
max_val = float('-inf')
second_max = float('-inf')
for num in arr:
if num > max_val:
second_max = max_val
max_val = num
elif num > second_max and num != max_val:
second_max = num
return second_max
# Sample Input
arr = [30, 20, 10, 50, 60, 40]
print("Second Largest:", find_second_largest(arr))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n) | The algorithm always traverses the entire array once to ensure it captures both the largest and second largest elements. |
Average Case | O(n) | Regardless of the input distribution, the algorithm iterates through all elements to maintain max and second max values. |
Average Case | O(n) | Even in the worst case where the second largest is the last element, the algorithm still requires a full pass through the array. |
O(1)
Explanation: The algorithm uses only a fixed number of variables (max_val and second_max) and does not require any extra space that grows with input size.
Let's find the second largest number in the array using a loop.
Initialize max = -Infinity
and secondMax = -Infinity
.
Current element is 30
. Compare with max = -Infinity
and secondMax = -Infinity
.
30 is greater than current max. Update: secondMax = -Infinity
, max = 30
.
Current element is 20
. Compare with max = 30
and secondMax = -Infinity
.
20 is greater than current secondMax and not equal to max. Update: secondMax = 20
.
Current element is 10
. Compare with max = 30
and secondMax = 20
.
No update required.
Current element is 50
. Compare with max = 30
and secondMax = 20
.
50 is greater than current max. Update: secondMax = 30
, max = 50
.
Current element is 60
. Compare with max = 50
and secondMax = 30
.
60 is greater than current max. Update: secondMax = 50
, max = 60
.
Current element is 40
. Compare with max = 60
and secondMax = 50
.
No update required.
Second Largest Element = 50
⬅ Previous Topic
Find Maximum and Minimum in Array using LoopNext Topic ⮕
Find Second Smallest in ArrayYou 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.