Second Largest
š Problem Statement
Given an array of integers, find the second largest element. For example, given [10, 5, 20, 8], the output is 10. If all elements are the same (e.g., [10, 10, 10]) or the array has fewer than 2 elements, return -1 or None.
š” Intuition
Finding the second largest requires tracking two values simultaneously: largest and second_largest. As you traverse, each element either becomes the new largest (pushing the old largest down to second), becomes the new second largest, or is irrelevant. This single-pass approach avoids the cost of sorting.
š§ Approach
- If the array has fewer than 2 elements, return None.
- Initialize
largest = arr[0]andsecond_largest = None. - Traverse from index 1. For each element:
- If
arr[i] > largest: setsecond_largest = largest, thenlargest = arr[i]. - Else if
arr[i] < largestand (second_largest is Noneorarr[i] > second_largest): updatesecond_largest.
- If
- Skip duplicates of the largest to handle arrays like
[10, 10, 5]. - Return
second_largest, or -1 if no valid second largest exists.
ā” Complexity Analysis
ā single pass through the array
ā only two tracking variables
ā ļø Common Mistakes
- Sorting the array first ā when a single pass suffices
- Not handling duplicates:
[20, 20, 10]should return 10, not 20 - Initializing
second_largestto 0 or without considering that all elements might be negative
šÆ Final Thoughts
This problem teaches you to track multiple states during a single traversal. The key insight: you don't need to sort. One careful pass with well-maintained variables is enough.