Finding the Largest and Second Largest Elements in an Array
Problem Statement
Write a JavaScript program to find the largest and second largest elements in an array of integers.
Approaches
Brute Force Approach
Example Code
Dry Run:
For the array [10, 20, 4, 45, 99]:
- Initialization:
largest = 10, secondLargest = -Infinity.
- First Loop (Finding Largest):
- Compare
20 with 10: largest = 20.
- Compare
4 with 20: No change.
- Compare
45 with 20: largest = 45.
- Compare
99 with 45: largest = 99.
- Second Loop (Finding Second Largest):
- Compare
10 with 99: No change.
- Compare
20 with 99: secondLargest = 20.
- Compare
4 with 20: No change.
- Compare
45 with 99: secondLargest = 45.
Output: Largest: 99, Second Largest: 45
Efficient Approach
Example Code
Dry Run:
For the array [10, 20, 4, 45, 99]:
- Initialization:
largest = 10, secondLargest = -Infinity.
- Loop:
- Compare
20 with 10: secondLargest = 10, largest = 20.
- Compare
4 with 20: No change.
- Compare
45 with 20: secondLargest = 20, largest = 45.
- Compare
99 with 45: secondLargest = 45, largest = 99.
Output: Largest: 99, Second Largest: 45
Example Test Cases
-
Input: [10, 20, 4, 45, 99]
Output: Largest: 99, Second Largest: 45
-
Input: [5, 5, 5, 5]
Output: Largest: 5, Second Largest: Not Found
-
Input: [-1, -2, -3, -4]
Output: Largest: -1, Second Largest: -2
-
Input: [1]
Output: Largest: 1, Second Largest: Not Found
Complexity Analysis
Brute Force Approach
- Time Complexity: O(n)
- Space Complexity: O(1)
Efficient Approach
- Time Complexity: O(n)
- Space Complexity: O(1)
Note :-
Both approaches solve the problem, but the efficient approach is preferable for larger datasets as it requires only a single pass through the array.