0
0
RubyProgramBeginner · 2 min read

Ruby Program to Find Second Largest in Array

You can find the second largest number in an array in Ruby by using array.uniq.sort[-2], which removes duplicates, sorts the array, and picks the second last element.
📋

Examples

Input[1, 2, 3, 4, 5]
Output4
Input[10, 10, 9, 8, 8]
Output9
Input[5]
OutputNo second largest element
🧠

How to Think About It

To find the second largest number, first remove any repeated numbers so duplicates don't confuse the result. Then sort the numbers from smallest to largest. The second largest will be the number just before the last one in this sorted list. If the list has less than two unique numbers, there is no second largest.
📐

Algorithm

1
Remove duplicate numbers from the array.
2
Sort the unique numbers in ascending order.
3
Check if there are at least two unique numbers.
4
If yes, return the second last number as the second largest.
5
If no, return a message that no second largest element exists.
💻

Code

ruby
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])
Output
4 9 No second largest element
🔍

Dry Run

Let's trace the array [10, 10, 9, 8, 8] through the code

1

Remove duplicates

Original array: [10, 10, 9, 8, 8] -> Unique array: [10, 9, 8]

2

Sort unique array

Sorted unique array: [8, 9, 10]

3

Check size

Unique array size is 3, which is >= 2, so continue

4

Return second largest

Second largest is element at index -2: 9

StepUnique ArraySorted ArraySecond 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

Iterative comparison
ruby
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])
This method finds the second largest in one pass without sorting, which is faster for large arrays but more complex to understand.
Sort descending and pick second
ruby
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])
Sorting descending and picking the second element is intuitive but sorting ascending or descending has similar performance.

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.

ApproachTimeSpaceBest For
Sort and pick second largestO(n log n)O(n)Simplicity and small to medium arrays
Iterative comparisonO(n)O(1)Large arrays needing speed
Sort descending and pick secondO(n log n)O(n)Readable code with descending order
💡
Use uniq before sorting to avoid duplicates affecting the second largest result.
⚠️
Not removing duplicates first can cause the largest number to appear twice, giving wrong second largest.