Second Largest Number
January 1, 2024
Problem #
Given an array of integers, write an algorithm that returns the second largest number in the array. If there is no second largest number, return -1.
Solution #
Here’s the Python code to find the second largest number in an array of integers:
def secondLargest(nums):
"""
Find the second largest number in an array of integers.
Args:
nums (List[int]): The array of integers.
Returns:
int: The second largest number in the array, or -1 if it doesn't exist.
"""
if len(nums) < 2:
return -1
first = second = float('-inf')
for num in nums:
if num > first:
second = first
first = num
elif first > num > second:
second = num
return second if second != float('-inf') else -1
# Example usage
array = [3, 5, 2, 5, 6, 9, 1]
second_largest_num = secondLargest(array)
print(second_largest_num)
This code defines the function secondLargest
, which iterates through the array nums
and keeps track of the largest and second largest numbers. The function returns the second largest number if it exists; otherwise, it returns -1
. For the example array [3, 5, 2, 5, 6, 9, 1]
, the function correctly identifies 6
as the second largest number.