13. Find the Index of the Largest Element

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

Given an array of numbers, find the index of the largest element.

How It Works & Algorithmic Design

Instead of storing only the maximum value, maintain the index where the maximum occurs:

  1. Start with maxIndex = 0.
  2. Compare each element with arr[maxIndex].
  3. If a larger element is found, update maxIndex.
  4. Return the index after completing the scan.
  5. Return -1 for an empty array.

Why This Approach Works Best

A single linear traversal is enough. The algorithm requires $O(n)$ time and $O(1)$ auxiliary space.

Example Walkthrough
Input: [10, 4, 25, 7, 18]
The largest value is 25.
Index Tracking: maxIndex=0 -> 2
When 25 is encountered, its index becomes the new maximum index.
Output: 2
The largest element is located at index 2.

Answer: Find index of maximum

function largestIndex(arr) {
  if (!arr.length) return -1;
  let maxIndex = 0;
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] > arr[maxIndex]) {
      maxIndex = i;
    }
  }
  return maxIndex;
}
💡 Track the index of the largest value instead of only storing the value.
Key Takeaways
  • Store the index rather than only the maximum value.
  • Comparing against arr[maxIndex] avoids maintaining two separate pieces of state.
  • The solution uses O(n) time and O(1) space.