Dsa in python
#day1 finding the second largest number in a list
class Solution:
def getSecondLargest(self, arr):
n = len(arr)
if n < 2:
return -1
first = second = float('-inf')
for num in arr:
if num > first:
second = first
first = num
elif num > second and num != first:
second = num
if second == float('-inf'):
return -1
else:
return second
Algorithm:
1. Input Validation:
o If the array has fewer than two elements, return -1 because a second largest element
cannot exist.
2. Initialize Variables:
o Use two variables, first and second, initialized to negative infinity (float('-inf')):
first will store the largest value encountered.
second will store the second largest value encountered.
3. Traverse the Array:
o For each element num in the array:
Case 1: If num is greater than first:
Update second to the current value of first.
Update first to num.
Case 2: If num is greater than second but not equal to first:
Update second to num.
4. Check Result:
o If second is still float('-inf'), it means there was no valid second largest element (e.g.,
all elements were the same), so return -1.
o Otherwise, return second.
Stepwise Execution:
Input: arr = [12, 35, 1, 10, 34, 1]
1. Initialization:
o first = float('-inf')
o second = float('-inf')
2. Iterate through the array:
o Iteration 1 (num = 12):
num > first → Update:
second = first = float('-inf')
first = 12
o Iteration 2 (num = 35):
num > first → Update:
second = first = 12
first = 35
o Iteration 3 (num = 1):
Neither condition satisfied (num is not greater than first or second).
o Iteration 4 (num = 10):
num > second but num != first → Update:
second = 10
o Iteration 5 (num = 34):
num > second but num != first → Update:
second = 34
o Iteration 6 (num = 1):
Neither condition satisfied.
3. Final Check:
o second = 34, which is not float('-inf'), so return 34.