Problem Solving

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

  1. Initialize two variables smallest and largest with the first element of the array.
  2. Iterate through each element of the array.
  3. For each element:
    • If the element is smaller than smallest, update smallest.
    • If the element is larger than largest, update largest.
  4. After the iteration, smallest and largest will 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]:

  1. Initialize smallest = 1 and largest = 1.
  2. Compare 2: update largest = 2.
  3. Compare 510: update largest = 510.
  4. Compare 0: update smallest = 0.
  5. Compare 20: no change.
  6. 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.