← Questions
Maximum element in an array
0
I was asked this
No reports yet. Sign in to say where you were asked it.
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. RaisesValueErroron an empty list. Don't call the built-inmax.
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 shouldNaNcompare? - 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
klargest elements: a heap of sizek, 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
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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