01. Find the Largest Element in an Array
Given an array of numbers, find the largest element.
How It Works & Algorithmic Design
To find the maximum element without sorting, we use a Single-Pass Linear Scan pattern.
- Initialization: Assume the first element (
arr[0]) is the largest seen so far. Storing an element from the array ensures that negative numbers or zero values do not break the comparison logic (unlike initializing to0). - Iteration: Loop through each remaining element from left to right.
- Comparison & Update: For every element, check if it is strictly greater than our current maximum variable (
max). If it is, overwritemaxwith the new value. - Edge Case Handling: If the input array is empty (
arr.length === 0), there is no valid maximum; returnnullor an equivalent empty-state value.
Why This Approach Works Best
Alternative approaches like sorting the array first take $O(n \log n)$ time complexity. This iterative scan inspects every element exactly once, giving an optimal linear $O(n)$ runtime while using $O(1)$ constant auxiliary memory.
Specifications & Requirements
- Empty Input:
Returns null immediately - Comparison Count:
Exactly n - 1 comparisons for n elements
Example Walkthrough 1
Input:
[4, 8, 2, 10, 3]Unsorted array with positive integers.
Step-by-Step State:
Init: max=4 | Check 8 -> max=8 | Check 2 -> max=8 | Check 10 -> max=10 | Check 3 -> max=10Tracks the running maximum state across iterations.
Output:
1010 is the largest value in the array.
Example Walkthrough 2 (Negative Numbers)
Input:
[-15, -3, -45, -8]Array containing only negative values.
Output:
-3Initializing with arr[0] (-15) correctly allows -3 to be chosen as max.
Answer: Find maximum element
function largest(arr) {
if (!arr || arr.length === 0) return null;
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}💡 Iterate through the array sequentially and maintain a tracking variable initialized to the first element.
Key Takeaways
- Always initialize the tracking variable with an actual element from the array (like
arr[0]), not0or arbitrary values. - A single pass linear scan inspects every element once, providing $O(n)$ time complexity.
- No dynamic memory allocation is required, giving $O(1)$ constant space complexity.