Problem Statement
Given an array of integers, find the largest and smallest numbers in the array.
Example:
Input: arr = [1, 2, 510, 0, 20]
Output: Smallest = 0, Largest = 510
Solution Approach
- Initialize two variables
smallestandlargestwith the first element of the array. - Iterate through each element of the array.
- For each element:
- If the element is smaller than
smallest, updatesmallest. - If the element is larger than
largest, updatelargest.
- If the element is smaller than
- After the iteration,
smallestandlargestwill hold the required values.
Kotlin Solution
fun main() {
val arr = arrayOf(1, 2, 510, 0, 20)
var smallest = arr[0]
var largest = arr[0]
arr.forEach { num ->
if (num < smallest) smallest = num
if (num > largest) largest = num
}
println("Smallest is \$smallest and Largest is \$largest")
}
Step-by-Step Example
For arr = [1, 2, 510, 0, 20]:
- Initialize
smallest = 1andlargest = 1. - Compare 2: update
largest = 2. - Compare 510: update
largest = 510. - Compare 0: update
smallest = 0. - Compare 20: no change.
- Final result: Smallest = 0, Largest = 510.
Explanation
- We iterate only once through the array, checking each element against current smallest and largest.
- This guarantees that after the loop, we have the correct minimum and maximum values.
- This is a linear scan algorithm with O(N) time complexity.
Complexity Analysis
- Time Complexity: O(N) — One pass through the array.
- Space Complexity: O(1) — Only two extra variables used.
Alternative Kotlin Approach
fun main() {
val arr = arrayOf(1, 2, 510, 0, 20)
val smallest = arr.minOrNull() ?: 0
val largest = arr.maxOrNull() ?: 0
println("Smallest is \$smallest and Largest is \$largest")
}
This uses Kotlin built-in functions minOrNull() and maxOrNull() for a concise solution.