← Coding round practice

Second Largest Element in an Array

MediumArrays

The problem

Find the second largest distinct value in an array in a single pass.

Sample input

[10, 5, 20, 8]

Sample output

10
Show the solution · 8 languages
fun main() {
    val arr = intArrayOf(10, 5, 20, 8)
    var largest = Int.MIN_VALUE
    var second = Int.MIN_VALUE
    for (x in arr) {
        if (x > largest) {
            second = largest
            largest = x
        } else if (x > second && x != largest) {
            second = x
        }
    }
    println(second)
}