13. Find the Index of the Largest Element
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:
- Start with
maxIndex = 0. - Compare each element with
arr[maxIndex]. - If a larger element is found, update
maxIndex. - Return the index after completing the scan.
- Return
-1for 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 -> 2When 25 is encountered, its index becomes the new maximum index.
Output:
2The 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.