02. Find the Smallest Element in an Array

Difficulty:EasyTime:O(n)Space:O(1)

Given an array of numbers, locate and return the smallest element.

How It Works & Algorithmic Design

Finding the minimum value uses the exact inverse logic of finding the maximum value:

  1. Initialization: Set min = arr[0]. This establishes a benchmark value present inside the input dataset.
  2. Linear Pass: Loop through the array from index 1 to arr.length - 1.
  3. Conditional Update: Compare each element with min. If the current value is strictly lower (arr[i] < min), update min = arr[i].
  4. Completion: Once all $n$ elements are evaluated, min holds the smallest value.

Why This Approach Works Best

This algorithm requires no sorting or external memory data structures. It evaluates the array in $O(n)$ time while operating in-place ($O(1)$ space).

Example Walkthrough
Input: [12, 5, 25, 1, 9]
Unsorted numbers including positive integers.
Execution Trace: Init: min=12 | Check 5 -> min=5 | Check 25 -> min=5 | Check 1 -> min=1 | Check 9 -> min=1
Updates 'min' whenever a strictly smaller value is found.
Output: 1
1 is the smallest element in the input list.

Answer: Find minimum element

function smallest(arr) {
  if (!arr || arr.length === 0) return null;
  let min = arr[0];
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] < min) min = arr[i];
  }
  return min;
}
💡 Traverse the array sequentially and retain the lowest value encountered.
Key Takeaways
  • Reversing the comparison operator (< instead of >) turns maximum-finding into minimum-finding.
  • Linear traversal inspects all items in $O(n)$ time.
  • Always account for empty inputs before referencing index 0 to prevent runtime exceptions.