14. Find the Index of the Smallest Element
Given an array of numbers, find the index of the smallest element.
How It Works & Algorithmic Design
Use the same tracking pattern as maximum-index search, but compare for smaller values:
- Initialize
minIndex = 0. - Traverse the remaining elements.
- If
arr[i] < arr[minIndex], updateminIndex. - Return
minIndex. - Return
-1if the array is empty.
Why This Approach Works Best
No sorting is required. One pass gives $O(n)$ time with $O(1)$ extra space.
Example Walkthrough
Input:
[8, 3, 12, 1, 6]The smallest value is 1.
Index Tracking:
minIndex=0 -> 1 -> 3The index changes whenever a smaller value is discovered.
Output:
3The smallest element is at index 3.
Answer: Find index of minimum
function smallestIndex(arr) {
if (!arr.length) return -1;
let minIndex = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[i] < arr[minIndex]) {
minIndex = i;
}
}
return minIndex;
}💡 Maintain the index of the smallest value encountered during the traversal.
Key Takeaways
- Track the index of the smallest element instead of only the value.
- Initialize the index using the first valid element.
- The algorithm runs in O(n) time and O(1) space.