The High Mark
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L3
- Asked in
- Infosys
Problem
We're monitoring a batch of integer sensor readings that arrive in order, and we need the running peak: the highest value seen so far after each reading. Return one peak-so-far value per reading, and an empty batch returns an empty list.
Scan the list. Report the max.
Example 1
Input:
nums = [3,1,4,1,5,9]
Output:
[3,3,4,4,5,9]
Example 2
Input:
nums = []
Output:
[]
Worked solution and explanation
What this is really testing
Under the sensor costume this is a prefix-maximum scan: at every position you report the highest reading seen so far, and the output is the whole sequence, not one number. That last part is why the obvious tools miss. A bare max() collapses the batch to a single scalar and throws the per-position history away; a set forgets order entirely. The only thing that works is walking the list once while carrying a running maximum and emitting it at each step. The trap is the seed: start highest at 0, feed it [-5, -1, -8], and the first peak comes back 0, a value that was never read. The other half is the empty batch: with no first element to seed from, an unguarded scan raises instead of returning an empty list.
Build it
Step 1: Guard the empty batch first
No readings means no peaks. Return [] up front so the rest of the function can assume there is at least one element to seed from.
Step 2: Seed from the first element
Seed the running maximum from the data, not from a constant. nums[0] is guaranteed real because you already ruled out the empty case, so it can never be an impossible value the way 0 can for an all-negative batch.
Step 3: Emit the running max at every step
Walk the list once. At each reading, bump the running maximum if this value beats it, then record the running maximum. One append per position gives you exactly one peak-so-far per reading.
The solution
def running_peak(nums: list[int]) -> list[int]:
if not nums:
return []
peaks = []
highest = nums[0]
for value in nums:
if value > highest:
highest = value
peaks.append(highest)
return peaksCommon follow-up questions
- What if you needed the running minimum instead of the running maximum? (Tests carrying a running minimum with the same seed-from-data discipline.)
- How would you also return the index where each new peak was first set? (Tests tracking both the running max and where each new peak first appeared.)
- Could you produce these peaks lazily for a stream that never ends? (Tests turning the batch scan into a lazy generator that never materializes the full list.)