How to find the two largest elements in a list with Kotlin

1 Answer

0 votes
// A function that finds the two largest elements in an iterable collection.
// Returns a Pair of (largest, secondLargest), or null if the collection has fewer than 2 elements.
fun findTwoLargest(numbers: Iterable<Int>): Pair<Int, Int>? {
    val iterator = numbers.iterator()
    
    // Guard clause: ensure there is at least a first element
    if (!iterator.hasNext()) return null
    var largest = iterator.next()
    
    // Guard clause: ensure there is at least a second element
    if (!iterator.hasNext()) return null
    var secondLargest = iterator.next()

    // Ensure initial assignment properly sorts the first two elements
    if (secondLargest > largest) {
        val temp = largest
        largest = secondLargest
        secondLargest = temp
    }

    // Iterate through the remainder of the collection in a single O(N) pass
    for (num in iterator) {
        if (num > largest) {
            // New absolute maximum found; old max shifts down to second largest
            secondLargest = largest
            largest = num
        } else if (num > secondLargest) {
            // Greater than second largest, but not the absolute maximum
            secondLargest = num
        }
    }

    return Pair(largest, secondLargest)
}

fun main() {
    // Define the dataset using a Kotlin list
    val data = listOf(3, 4, 9, 6, 7, 1, 2, 5)

    // Call our function and handle the nullable Pair result idiomatically
    val result = findTwoLargest(data)

    if (result != null) {
        println("Dataset: $data")
        println("The largest element is: ${result.first}")
        println("The second largest element is: ${result.second}")
    } else {
        println("Error: The collection must contain at least two elements.")
    }
}


/*
run:

Dataset: [3, 4, 9, 6, 7, 1, 2, 5]
The largest element is: 9
The second largest element is: 7

*/

 



answered 14 hours ago by avibootz
...