AmazonAlgorithmsEasy

Find the maximum element in an array

ArrayAlgorithmsSearch

Question

Write a function to find the maximum element in an array.

Interview Answer

Scan the array once, track a running maximum, and update it whenever a larger value appears. Initialize with the first element (not zero) to handle negative values correctly. This yields optimal O(n) time and O(1) space.

Explanation

This is a linear pass problem. Because every element can potentially be the maximum, lower than O(n) time is not possible in the general case. Keep validation for empty arrays and discuss stream-based alternatives briefly.

Key Points

  • One-pass linear scan is optimal
  • Initialize max from first element to handle negatives
  • Validate empty input to avoid undefined behavior
  • Simple solution demonstrates fundamentals clearly

Common Mistakes

  • Initializing max to 0 and failing for all-negative arrays
  • Not handling empty arrays
  • Using unnecessary extra space

Likely Follow-Up Questions

  • How would you find second largest element in one pass?
  • How would you find top-k largest elements efficiently?
  • How does approach change for streaming data?

Interview Timing

Target speaking time: about 3 minutes.

Related Questions