← Questions

Maximum element in an array

0
Coding

Return the largest element of a list of numbers, scanning it once. It is a warm-up: the interviewer cares about the edge cases you raise, the code being clean, and how you would test it, more than the loop itself.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • max_element(values: list[int]) -> int — the largest value. Raises ValueError on an empty list. Don't call the built-in max.

Example

max_element([3, 9, -2, 9, 4])  -> 9
max_element([-7, -3, -12])     -> -3     # starting from 0 would be wrong
max_element([5])               -> 5
max_element([])                -> ValueError

Constraints

  • Up to 10^6 values.
  • O(n) time, O(1) extra space.

Clarifying questions

  • What should an empty list return: an error, None, or a default?
  • Can the values be floats, including NaN? How should NaN compare?
  • Do you want the value, its index, or both? Which index on a tie?
  • Can the input be a stream or iterator that can only be read once?

What a strong answer covers

  • Starting from the first element, not from 0 or a magic minimum.
  • One pass, constant memory, and a clear statement of the empty-input behaviour.
  • Working on any iterable, not just a list, if asked.
  • Tests: one element, all negative, duplicates of the maximum, the maximum first and last, empty input.

Follow-ups

  • Return the index of the first maximum.
  • Return the k largest elements: a heap of size k, O(n log k).
  • The values arrive as a stream and the maximum is asked for after every new value, with old values expiring after a window: a monotonic deque.
  • Split a huge array across workers and combine the partial maxima.

What it tests

arrays · scanning

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding