Find Second Largest

Find second largest element in array.

AdvancedPhase 4 - Level 5: Logical & AppliedExample 3 of 14
find-second-largest.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 largest
8if n < 2:
9 print("Array too small")
10else:
11 # Find max
12 max_val = max(arr)
13
14 # Find second max
15 second_max = None
16 for element in arr:
17 if element != max_val:
18 if second_max is None or element > second_max:
19 second_max = element
20
21 if second_max is None:
22 print("All elements are same")
23 else:
24 print(f"Second largest: {second_max}")

Output

Enter array size: 5
Element 1: 10
Element 2: 5
Element 3: 20
Element 4: 15
Element 5: 20
Second largest: 15

What's going on

Find max first, then find largest that's not max.

Key Concepts:

First find maximum
Then find largest excluding max
Handle case where all same