0
0
KotlinProgramBeginner · 2 min read

Kotlin Program to Find Second Largest Number in List

You can find the second largest number in a list in Kotlin by sorting the list and accessing the second last element with list.sortedDescending()[1] or by iterating to track the largest and second largest values.
📋

Examples

Input[3, 5, 1, 2, 4]
Output4
Input[10, 10, 9, 8]
Output9
Input[1]
OutputNo second largest element
🧠

How to Think About It

To find the second largest number, first understand that the largest number is the highest value in the list. The second largest is the next highest value that is less than the largest. We can either sort the list and pick the second last unique value or scan the list once, keeping track of the largest and second largest numbers as we go.
📐

Algorithm

1
Check if the list has at least two unique elements; if not, return a message.
2
Initialize two variables to hold the largest and second largest values.
3
Loop through each number in the list.
4
If the current number is greater than the largest, update second largest to largest and largest to current number.
5
Else if the current number is between largest and second largest, update second largest.
6
Return the second largest value.
💻

Code

kotlin
fun findSecondLargest(numbers: List<Int>): String {
    if (numbers.distinct().size < 2) return "No second largest element"
    var largest = Int.MIN_VALUE
    var secondLargest = Int.MIN_VALUE
    for (num in numbers) {
        if (num > largest) {
            secondLargest = largest
            largest = num
        } else if (num > secondLargest && num < largest) {
            secondLargest = num
        }
    }
    return secondLargest.toString()
}

fun main() {
    val list = listOf(3, 5, 1, 2, 4)
    println(findSecondLargest(list))
}
Output
4
🔍

Dry Run

Let's trace the list [3, 5, 1, 2, 4] through the code to find the second largest number.

1

Initialize variables

largest = Int.MIN_VALUE, secondLargest = Int.MIN_VALUE

2

Check first number 3

3 > largest (-2147483648), so largest = 3, secondLargest = -2147483648

3

Check second number 5

5 > largest (3), so secondLargest = 3, largest = 5

4

Check third number 1

1 > secondLargest (3)? No, no change

5

Check fourth number 2

2 > secondLargest (3)? No, no change

6

Check fifth number 4

4 > secondLargest (3) and 4 < largest (5), so secondLargest = 4

7

Return result

secondLargest = 4

NumberLargestSecond Largest
33-2147483648
553
153
253
454
💡

Why This Works

Step 1: Check list size

We first check if the list has at least two unique numbers using distinct() to avoid errors.

Step 2: Track largest and second largest

We keep two variables to remember the largest and second largest numbers as we scan the list once.

Step 3: Update values carefully

When a number is bigger than the largest, we move the largest to second largest and update largest. If it's between largest and second largest, we update second largest.

🔄

Alternative Approaches

Sorting and picking second largest
kotlin
fun findSecondLargest(numbers: List<Int>): String {
    val distinctSorted = numbers.distinct().sortedDescending()
    return if (distinctSorted.size < 2) "No second largest element" else distinctSorted[1].toString()
}

fun main() {
    println(findSecondLargest(listOf(3, 5, 1, 2, 4)))
}
This method is simpler but slower for large lists because sorting takes more time.
Using max and filtering
kotlin
fun findSecondLargest(numbers: List<Int>): String {
    val max = numbers.maxOrNull() ?: return "No second largest element"
    val filtered = numbers.filter { it != max }
    val secondMax = filtered.maxOrNull() ?: return "No second largest element"
    return secondMax.toString()
}

fun main() {
    println(findSecondLargest(listOf(3, 5, 1, 2, 4)))
}
This approach uses built-in functions but scans the list multiple times.

Complexity: O(n) time, O(1) space

Time Complexity

The main approach scans the list once, so it runs in linear time O(n), where n is the number of elements.

Space Complexity

It uses only a few variables to track values, so space complexity is constant O(1).

Which Approach is Fastest?

The single scan method is fastest for large lists compared to sorting (O(n log n)) or filtering multiple times.

ApproachTimeSpaceBest For
Single scan trackingO(n)O(1)Large lists, best performance
Sorting and pickingO(n log n)O(n)Simple code, small lists
Max and filterO(n)O(n)Readable but less efficient
💡
Always check for at least two unique elements before finding the second largest to avoid errors.
⚠️
Beginners often forget to handle lists with all equal elements or only one element, causing errors.