Column Range

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

Problem

Readings in our sensor batches can be negative or fractional, and a batch always holds at least one value. For a batch nums, return the range it spans: its lowest reading and its highest.

From minimum to maximum. What is the spread?

Example 1

Input:

nums = [3,1,4,1,5,9]

Output:

[1,9]

Example 2

Input:

nums = [5]

Output:

[5,5]

Worked solution and explanation

What this really is

This is a two-accumulator scan dressed up as a sensor report. Anyone can write the loop; what separates candidates is where the running low and high start. Seed them at 0 and you have quietly assumed the readings straddle zero: the all-negative batch [-5, -1, -10, -3] comes back with a high of 0, a reading that never happened, and an all-positive batch reports a low of 0 just as confidently.

Build it

Step 1: Anchor both extremes to the first reading

nums[0] is the only starting value guaranteed to be right for both ends: it is a real reading, and the batch is never empty, so it always exists. A literal 0 or a hard-coded huge number is a guess about the data's range.

Step 2: Check every later reading against both ends

Each reading can lower the low, raise the high, or do neither, so it gets two independent comparisons in the same pass. A single-reading batch never enters the loop and returns that reading twice, which is exactly the range it spans.

Single-pass min and max tracking
def min_and_max(nums):
    current_min = nums[0]
    current_max = nums[0]
    for i in range(1, len(nums)):
        if nums[i] < current_min:
            current_min = nums[i]
        if nums[i] > current_max:
            current_max = nums[i]
    return [current_min, current_max]

Common follow-up questions