Find the Second Largest Element in an Array
This method returns the second largest number in an integer array. If the array has fewer than 2 elements or all elements are the same, it returns -1
.
Approach:
-
Edge Case Check:
- Return
-1
if the array is null or has less than 2 elements.
- Return
-
Initialize Variables:
-
largest
: Tracks the largest element (Integer.MIN_VALUE
initially). -
secondLargest
: Tracks the second largest element (Integer.MIN_VALUE
initially).
-
-
Traverse the Array:
-
Update Largest: If the current number is greater than
largest
:- Assign
largest
tosecondLargest
. - Update
largest
with the current number.
- Assign
-
Update Second Largest: If the current number is not equal to
largest
but greater thansecondLargest
, updatesecondLargest
.
-
Update Largest: If the current number is greater than
-
Return Result:
- If
secondLargest
remainsInteger.MIN_VALUE
, return-1
. Otherwise, returnsecondLargest
.
- If
Code Explanation
public int getSecondLargest(int[] arr) {
// Handle edge cases
if (arr == null || arr.length < 2)
return -1;
// Initialize largest and second largest
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
// Traverse array
for (int num : arr) {
if (num > largest) {
secondLargest = largest; // Update second largest
largest = num; // Update largest
} else if (num != largest && num > secondLargest) {
secondLargest = num; // Update second largest
}
}
// Check if second largest exists
return (secondLargest == Integer.MIN_VALUE) ? -1 : secondLargest;
}
Key Points:
- The
n != largest
check ensures duplicates of the largest number are ignored. -
Integer.MIN_VALUE
acts as a placeholder to handle negative numbers effectively.
Complexity:
- Time: O(n) — Single pass through the array.
- Space: O(1) — No additional space used.
This code is efficient and handles edge cases gracefully.
Top comments (0)