02. Find the Smallest Element in an Array
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:
- Initialization: Set
min = arr[0]. This establishes a benchmark value present inside the input dataset. - Linear Pass: Loop through the array from index
1toarr.length - 1. - Conditional Update: Compare each element with
min. If the current value is strictly lower (arr[i] < min), updatemin = arr[i]. - Completion: Once all $n$ elements are evaluated,
minholds 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=1Updates 'min' whenever a strictly smaller value is found.
Output:
11 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
0to prevent runtime exceptions.