PHP Program to Find Second Largest in Array
rsort() and then accessing the second element with $array[1].Examples
How to Think About It
Algorithm
Code
<?php function findSecondLargest(array $arr) { $unique = array_unique($arr); rsort($unique); if (count($unique) < 2) { return "No second largest element"; } return $unique[1]; } // Example usage $array = [3, 5, 1, 4]; echo findSecondLargest($array);
Dry Run
Let's trace the array [3, 5, 1, 4] through the code
Remove duplicates
Original array: [3, 5, 1, 4], after array_unique: [3, 5, 1, 4]
Sort descending
Sorted array: [5, 4, 3, 1]
Check length
Array length is 4, which is >= 2
Return second largest
Second element is 4
| Step | Array State |
|---|---|
| After unique | [3, 5, 1, 4] |
| After sort | [5, 4, 3, 1] |
Why This Works
Step 1: Remove duplicates
Using array_unique() ensures repeated numbers don't affect finding the second largest.
Step 2: Sort descending
Sorting with rsort() puts the largest numbers first, so the second element is the second largest.
Step 3: Check array length
If there are fewer than two unique numbers, we cannot find a second largest, so we handle that case.
Alternative Approaches
<?php function findSecondLargestSinglePass(array $arr) { $max = PHP_INT_MIN; $secondMax = PHP_INT_MIN; foreach ($arr as $num) { if ($num > $max) { $secondMax = $max; $max = $num; } elseif ($num > $secondMax && $num < $max) { $secondMax = $num; } } if ($secondMax === PHP_INT_MIN) { return "No second largest element"; } return $secondMax; } // Example usage $array = [3, 5, 1, 4]; echo findSecondLargestSinglePass($array);
<?php function findSecondLargestAsc(array $arr) { $unique = array_unique($arr); sort($unique); if (count($unique) < 2) { return "No second largest element"; } return $unique[count($unique) - 2]; } // Example usage $array = [3, 5, 1, 4]; echo findSecondLargestAsc($array);
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 in place or with extra space depending on implementation.
Which Approach is Fastest?
The single pass scan method is O(n) time and O(1) space, making it faster and more memory efficient for large arrays.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Sort descending and pick second | O(n log n) | O(n) | Simplicity and small arrays |
| Single pass scan | O(n) | O(1) | Large arrays and performance |
| Sort ascending and pick second last | O(n log n) | O(n) | Alternative sorting method |