To solve this problem efficiently in ( O(n) ) time and ( O(1) ) auxiliary space, you can iterate through the array while keeping track of the largest and the second largest distinct elements. Here's how you can approach it:
-
Initialize Two Variables:
first_max to store the largest element, initialized to negative infinity.
second_max to store the second largest distinct element, also initialized to negative infinity.
-
Iterate Through the Array:
- For each element in the array:
- Update
first_max:
- If the current element is greater than
first_max, update second_max to be first_max and then update first_max to the current element.
- Update
second_max:
- If the current element is less than
first_max but greater than second_max, and it's not equal to second_max (to ensure distinctness), update second_max to the current element.
-
Final Check:
- After traversing the array, if
second_max remains unchanged (i.e., negative infinity), it means there was no distinct second largest element. Return -1 in this case.
- Otherwise, return
second_max.
Here's the implementation in Python:
def find_second_largest(arr):
first_max = second_max = -1
for num in arr:
if num > first_max:
if num != first_max:
second_max = first_max
first_max = num
elif first_max > num > second_max:
if num != second_max:
second_max = num
return second_max if second_max != -1 else -1
# Example Usage:
if __name__ == "__main__":
# Test Case 1
arr1 = [12, 35, 1, 10, 34, 1]
print(find_second_largest(arr1)) # Output: 34
# Test Case 2
arr2 = [10, 10]
print(find_second_largest(arr2)) # Output: -1
# Additional Test Cases
arr3 = [5, 5, 5, 5]
print(find_second_largest(arr3)) # Output: -1
arr4 = [2, 3]
print(find_second_largest(arr4)) # Output: 2
arr5 = [1, 2, 3, 4, 5]
print(find_second_largest(arr5)) # Output: 4
arr6 = [5, 3, 9, 1, 9, 5]
print(find_second_largest(arr6)) # Output: 5
Explanation of the Code:
-
Initialization:
first_max and second_max are initialized to -1. This works under the given constraints where array elements are at least 1. If elements can be negative, consider initializing them to float('-inf').
-
Iterating Through the Array:
- Updating
first_max and second_max:
- If the current number
num is greater than first_max, update second_max to be first_max, and then update first_max to num.
- If
num is not greater than first_max but is greater than second_max, update second_max to num.
- The condition
num != second_max ensures that second_max remains distinct.
-
Final Return Statement:
- After the loop, if
second_max is still -1, it means there was no distinct second largest element, so return -1.
- Otherwise, return the value of
second_max.
Complexity Analysis:
- Time Complexity: ( O(n) ) – Only a single pass through the array is required.
- Space Complexity: ( O(1) ) – Only two extra variables are used, regardless of the input size.
This approach ensures that you meet the expected time and space complexity constraints efficiently.