Python Program to Find Second Largest in Array
sorted(set(arr))[-2] or by iterating through the array to track the largest and second largest values.Examples
How to Think About It
Algorithm
Code
def second_largest(arr): unique_nums = list(set(arr)) if len(unique_nums) < 2: return "No second largest element" unique_nums.sort() return unique_nums[-2] # Example usage arr = [10, 10, 9, 8] print(second_largest(arr))
Dry Run
Let's trace the example array [10, 10, 9, 8] through the code
Remove duplicates
Input array: [10, 10, 9, 8] -> Unique numbers: [8, 9, 10]
Check length
Unique numbers length is 3, which is >= 2, so continue
Sort unique numbers
Sorted unique numbers: [8, 9, 10]
Return second largest
Second largest number is unique_nums[-2] = 9
| Step | Unique Numbers | Action | Result |
|---|---|---|---|
| 1 | [10, 10, 9, 8] | Remove duplicates | [8, 9, 10] |
| 2 | [8, 9, 10] | Check length >= 2 | True |
| 3 | [8, 9, 10] | Sort | [8, 9, 10] |
| 4 | [8, 9, 10] | Return second largest | 9 |
Why This Works
Step 1: Remove duplicates
Using set() removes repeated numbers so we only consider unique values.
Step 2: Check if second largest exists
If there are fewer than two unique numbers, there is no second largest number.
Step 3: Sort unique numbers
Sorting helps us easily pick the second largest by accessing the second last element.
Step 4: Return result
The second largest number is the element before the largest in the sorted list.
Alternative Approaches
def second_largest(arr): first = second = float('-inf') for num in arr: if num > first: second = first first = num elif first > num > second: second = num return second if second != float('-inf') else "No second largest element" print(second_largest([10, 10, 9, 8]))
import heapq def second_largest(arr): unique_nums = list(set(arr)) if len(unique_nums) < 2: return "No second largest element" largest_two = heapq.nlargest(2, unique_nums) return largest_two[1] print(second_largest([10, 10, 9, 8]))
Complexity: O(n log n) time, O(n) space
Time Complexity
Sorting the unique elements takes O(n log n) time, where n is the number of elements in the array.
Space Complexity
Creating a set of unique elements uses O(n) extra space.
Which Approach is Fastest?
The iterative tracking method runs in O(n) time and O(1) space, making it faster and more memory efficient than sorting.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Sorting unique elements | O(n log n) | O(n) | Simple code, small to medium arrays |
| Iterative tracking | O(n) | O(1) | Large arrays, performance critical |
| Heapq.nlargest | O(n log k) | O(n) | When needing top k largest elements efficiently |