14. Find the Index of the Smallest Element

Difficulty:EasyPattern:Linear ScanTime:O(n)Space:O(1)

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:

  1. Initialize minIndex = 0.
  2. Traverse the remaining elements.
  3. If arr[i] < arr[minIndex], update minIndex.
  4. Return minIndex.
  5. Return -1 if 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 -> 3
The index changes whenever a smaller value is discovered.
Output: 3
The 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.