No Shortcuts
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
- L6
- Asked in
- Infosys
Problem
Our peak report crashes on sensor batches that arrive with no readings, and those batches should show None instead. For every other batch, return the highest value in readings without using the built-in max().
The peak value. Built-ins off the table.
Example 1
Input:
readings = [3,7,2,9,1]
Output:
9
Example 2
Input:
readings = [-5,-2,-8,-1]
Output:
-1
Worked solution and explanation
The answer has to come from the batch
On the surface this asks you to rebuild max() by hand. The real test is narrower: does your peak always come from the readings themselves? Everyone writes a loop that keeps the biggest value seen so far. Strong candidates differ in where that value starts. Start it at 0 and an all-negative batch like [-5, -2, -8, -1] reports 0, a reading no sensor ever sent. Read readings[0] without checking first and an empty batch crashes the report instead of showing None.
Step 1: Set the empty batch aside first
An empty batch has no peak, so return None before touching any index. Putting this guard first keeps the main path free of special cases.
Step 2: Start from a real reading
Once the batch is known to be non-empty, readings[0] is a value that truly exists, so it is a safe starting peak. Negatives, positives and single-reading batches all work without a magic number.
Step 3: Compare each remaining reading once
Walk from index 1 to the end and replace peak only when a reading is strictly greater. Ties keep the current value, which is correct because equal readings are the same peak.
def peak_reading(readings):
if not readings:
return None
peak = readings[0]
for i in range(1, len(readings)):
if readings[i] > peak:
peak = readings[i]
return peak- Sentinel start
peak = 0then compare everything. Passes[3, 7, 2, 9, 1], returns 0 on[-5, -2, -8, -1], and silently returns 0 for[]too.- Data start
- Return
Nonefor[], thenpeak = readings[0]. Every answer is a reading from the batch, and the empty batch has its own explicit result.
Common follow-up questions
- How would you return the second-highest reading in the same single pass? (Tracking two values and handling duplicates of the peak.)
- What changes if readings can be `None` for a sensor that dropped out? (Skipping missing values while still seeding from real data.)
- How would you report the peak per sensor when `readings` holds `(sensor_id, value)` pairs? (Moving from one running value to one per key.)