Ruby Program to Find Second Largest in Array
array.uniq.sort[-2], which removes duplicates, sorts the array, and picks the second last element.Examples
How to Think About It
Algorithm
Code
def second_largest(arr) unique = arr.uniq return 'No second largest element' if unique.size < 2 unique.sort[-2] end puts second_largest([1, 2, 3, 4, 5]) puts second_largest([10, 10, 9, 8, 8]) puts second_largest([5])
Dry Run
Let's trace the array [10, 10, 9, 8, 8] through the code
Remove duplicates
Original array: [10, 10, 9, 8, 8] -> Unique array: [10, 9, 8]
Sort unique array
Sorted unique array: [8, 9, 10]
Check size
Unique array size is 3, which is >= 2, so continue
Return second largest
Second largest is element at index -2: 9
| Step | Unique Array | Sorted Array | Second Largest |
|---|---|---|---|
| 1 | [10, 9, 8] | - | - |
| 2 | - | [8, 9, 10] | - |
| 3 | - | - | Check size >= 2 |
| 4 | - | - | 9 |
Why This Works
Step 1: Remove duplicates
Using uniq removes repeated numbers so the second largest is distinct.
Step 2: Sort the array
Sorting puts numbers in order so we can easily pick the second largest by position.
Step 3: Check array size
If there are fewer than two unique numbers, a second largest does not exist.
Step 4: Pick second largest
The second largest is the second last element in the sorted unique array.
Alternative Approaches
def second_largest(arr)
max = -Float::INFINITY
second = -Float::INFINITY
arr.each do |num|
if num > max
second = max
max = num
elsif num > second && num != max
second = num
end
end
second == -Float::INFINITY ? 'No second largest element' : second
end
puts second_largest([1, 2, 3, 4, 5])def second_largest(arr) unique = arr.uniq return 'No second largest element' if unique.size < 2 unique.sort.reverse[1] end puts second_largest([1, 2, 3, 4, 5])
Complexity: O(n log n) time, O(n) space
Time Complexity
Sorting the array takes O(n log n) time, which dominates the process. Removing duplicates is O(n).
Space Complexity
Creating a unique array uses O(n) extra space. Sorting is done on this new array.
Which Approach is Fastest?
The iterative comparison method is O(n) time and O(1) space, faster for large arrays but less straightforward.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Sort and pick second largest | O(n log n) | O(n) | Simplicity and small to medium arrays |
| Iterative comparison | O(n) | O(1) | Large arrays needing speed |
| Sort descending and pick second | O(n log n) | O(n) | Readable code with descending order |
uniq before sorting to avoid duplicates affecting the second largest result.