Problem Statement
You are given an array of integers. Your task is to find the second largest element in the array. The array may contain duplicate elements.
Example:
Input: arr = [12, 35, 1, 10, 34, 1]
Output: 34
Explanation: The largest element is 35, the second largest is 34.
Example 2:
Input: arr = [5, 5, 5, 2]
Output: 2
Explanation: The largest element is 5 (repeated), second largest is 2.
Solution Approach
- Initialize two variables:
largestandsecondLargestwithInt.MIN_VALUE. - Traverse the array once.
-
For each element:
- If element is greater than
largest, updatesecondLargesttolargestand then updatelargestto the element. - Else if element is greater than
secondLargestand not equal tolargest, updatesecondLargest.
- If element is greater than
- After traversal,
secondLargestcontains the second largest element.
Kotlin Solution
fun findSecondLargest(arr: Array): Int {
var largest = Int.MIN_VALUE
var secondLargest = Int.MIN_VALUE
arr.forEach { num ->
if (num > largest) {
secondLargest = largest
largest = num
} else if (num > secondLargest && num != largest) {
secondLargest = num
}
}
return secondLargest
}
fun main() {
val arr = arrayOf(12, 35, 1, 10, 34, 1)
val secondLargest = findSecondLargest(arr)
println("Second largest element is: $secondLargest") // Output: 34
}
Step-by-Step Example
For arr = [12, 35, 1, 10, 34, 1]:
- Start:
largest = MIN_VALUE,secondLargest = MIN_VALUE - 12 → largest = 12, secondLargest = MIN_VALUE
- 35 → largest = 35, secondLargest = 12
- 1 → largest = 35, secondLargest = 12
- 10 → largest = 35, secondLargest = 12
- 34 → largest = 35, secondLargest = 34
- 1 → largest = 35, secondLargest = 34
Result: secondLargest = 34
Explanation
- This approach keeps track of the two largest numbers in a single pass.
- No extra array or filtering is needed.
- Handles duplicates correctly by checking
num != largest.
Complexity Analysis
- Time Complexity: O(N) — Only one traversal of the array is needed.
- Space Complexity: O(1) — Only two variables are used.
Edge Cases
- If the array has all elements the same, the second largest might not exist — you may return a special value or handle separately.
- If the array has less than 2 distinct elements, handle accordingly.