Detecting the First Route Climb Under Strict and Dip-Tolerant Rules

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given an integer sequence elevations recorded at evenly spaced checkpoints along a trail and a boolean mode switch tolerate_descent, identify the [start, end] index bounds of the earliest climb, or return [] if the sequence never steps uphill:

def first_climb(elevations: list[int], tolerate_descent: bool) -> list[int]:

Climb rules:

  • Opening index (start, both modes): start is the smallest index 0 <= s < len(elevations) - 1 where elevations[s + 1] > elevations[s] (the checkpoint immediately preceding the very first upward step). Any downhill or level checkpoints before s are excluded. If no adjacent pair increases, return [].
  • Closing index (end, both modes): Let P be the maximum altitude attained during the climb. The climb ends at the earliest index where that final summit altitude P is reached—any subsequent checkpoints sitting flat at P are excluded. Because at least one upward step occurs, start < end always holds.
  • Strict mode (tolerate_descent = False): Beginning at start, the climb advances across every checkpoint whose altitude is greater than or equal to the preceding checkpoint, stopping just before the first drop (elevations[i] < elevations[i - 1]) or at the end of the list.
  • Dip-tolerant mode (tolerate_descent = True): Beginning at start, the climb advances whenever altitude rises or stays level at the running high P. As soon as a checkpoint falls strictly below P, a candidate dip starts at that checkpoint and encompasses all consecutive checkpoints up to—but not including—the earliest later checkpoint with altitude strictly above P (revisiting P itself stays inside the dip and does not close it). Let gain = P - elevations[start] be the net vertical rise accumulated up to P, and let loss = P - valley_min, where valley_min is the minimum altitude inside the dip. A dip is accepted if and only if both conditions hold:
    1. At least one later checkpoint after the dip starts has altitude strictly greater than P, and
    2. loss is no more than 20% of gain, checked in exact integer arithmetic via 5 * loss <= gain.

      When a dip is accepted, the climb resumes from that first checkpoint strictly above P (establishing a new higher P, with any subsequent dips measured against the updated P and gain). When a dip is rejected, the climb terminates back at the index where P was first reached.

Examples

Example 1

Input: elevations = [12, 8, 4, 4, 7, 9, 9, 14, 14, 10, 20], tolerate_descent = False
Output: [3, 7]

Walk-through: The earliest upward step goes from index 3 (4) to index 4 (7), skipping the flat 4 at index 2. Non-decreasing altitudes continue until the drop to 10 at index 9; the summit value 14 first appears at index 7 (leaving out the flat 14 at index 8).

Example 2

Input: elevations = [10, 10, 15, 25, 40, 35, 42, 50, 48], tolerate_descent = True
Output: [1, 7]

Walk-through: Starting at index 1 (10), the climb reaches P = 40 at index 4 (gain = 40 - 10 = 30). Dropping to 35 at index 5 loses 5 (5 * 5 = 25 <= 30) and index 6 (42) climbs strictly above 40, so the dip is accepted. The climb continues to 50 at index 7; the trailing dip to 48 at index 8 never beats 50, ending the climb at index 7.

Example 3

Input: elevations = [5, 2, 17, 14, 18, 18, 16, 18], tolerate_descent = True
Output: [1, 4]

Walk-through: Starting at index 1 (2), P = 17 at index 2 gives gain = 15. The drop to 14 at index 3 loses 3 (5 * 3 = 15 <= 15, exact 20% limit) and recovers to 18 > 17 at index 4. Index 5 sits flat at 18, and the dip to 16 at index 6 only returns to 18 at index 7 without exceeding 18, so the climb finishes at index 4.

Constraints

  • 0 <= len(elevations) <= 10^5
  • -10^5 <= elevations[i] <= 10^5
  • Output is either [] or [start, end] satisfying 0 <= start < end < len(elevations).

Step-by-step walkthrough

  1. Understand the climb rules on an altitude profile

    Given checkpoint altitudes elevations and a boolean flag tolerate_descent, we return [start, end] for the earliest climb, or [] if no uphill step occurs.

    Sketch Example 2 (elevations = [10, 10, 15, 25, 40, 35, 42, 50, 48], tolerate_descent = True):

    Elev
     50 |                              * (idx 7: final summit -> end = 7)
     48 |                                  * (idx 8: dips and never exceeds 50)
     42 |                          * (idx 6: exceeds 40 -> dip accepted!)
     40 |                  * (idx 4: peak=40, gain=30)
     35 |                      * (idx 5: loss=5 <= 20% of 30)
     25 |              *
     15 |          *
     10 |  *---* (idx 1: right before first rise -> start = 1; idx 0 is excluded)
           0   1   2   3   4   5   6   7   8   Index
    

    Four crisp rules govern every case:

    • Opening index: the smallest start with elevations[start + 1] > elevations[start]. Leading downhill or level points before start stay outside the climb.
    • Closing index: the earliest index where the climb's final summit altitude peak is achieved. Level points sitting at peak afterward stay outside the climb.
    • Strict mode (tolerate_descent = False): stop as soon as any checkpoint drops below the preceding checkpoint.
    • Dip-tolerant mode (tolerate_descent = True): whenever a checkpoint drops below peak, a dip spans from that checkpoint up to the earliest later checkpoint strictly greater than peak (revisiting peak stays inside the dip). With gain = peak - elevations[start] and loss = peak - lowest_in_dip, if a checkpoint > peak exists and 5 * loss <= gain, resume climbing from that higher checkpoint; otherwise finish at the earliest index of peak.
  2. Locate the opening index

    Finding start is identical under both modes: scan adjacent pairs left to right and return the first i satisfying elevations[i + 1] > elevations[i].

    Using strict > (rather than >=) skips flat lead-ins like [10, 10, 15, ...] so we land on index 1 instead of 0. And if fewer than two checkpoints exist or the path only goes flat/downhill, range(len(elevations) - 1) finishes cleanly and returns -1.

    def find_start(elevations: list[int]) -> int:
        """Return the index right before the first increase, or -1 if no climb exists."""
        # Strict `>` skips any flat stretch before the climb actually begins rising.
        for i in range(len(elevations) - 1):
            if elevations[i + 1] > elevations[i]:
                return i
        return -1
    
  3. Track the summit and keep plateaus out of `peak_index`

    Starting from start, maintain two variables while advancing j:

    • peak: the highest altitude reached during the climb so far,
    • peak_index: the earliest index where peak was reached.

    Notice a clean invariant: outside a dip, every non-decreasing step keeps the current altitude equal to peak. That means "dropped below the previous checkpoint" and "dropped below peak" reduce to the same test (elevations[j] < peak)! At each j:

    • elevations[j] > peak: new high reached—update both peak = elevations[j] and peak_index = j.
    • elevations[j] == peak: level plateau at the current summit—increment j without touching peak_index. If the climb terminates after this plateau, peak_index already marks the beginning of the plateau.
    • elevations[j] < peak: a dip begins! In strict mode, break immediately and return [start, peak_index].
  4. Evaluate a dip in one forward scan

    When tolerate_descent is True and elevations[j] < peak, resist checking max(elevations[j:]) > peak before finding the recovery checkpoint: scanning the entire remaining suffix on every dip costs O(n) per dip, turning a 100,000-checkpoint staircase with 50,000 tiny dips into O(n^2) (~2.5 billion steps).

    Instead, scan_descent(elevations, dip_start, peak) walks forward from dip_start only until the first checkpoint strictly greater than peak (or the end of the array), tracking lowest along the way:

    • Loop while elevations[idx] <= peak (using <=, not <), because returning to exact peak does not end the dip—only strictly exceeding peak ends it.
    • Reaching idx == len(elevations) means no later checkpoint beat peak, returning -1 for rise_index.
    def scan_descent(elevations: list[int], dip_start: int, peak: int) -> Tuple[int, int]:
        """Scan forward from `dip_start` until an elevation strictly above `peak` is found.
    
        Returns (rise_index, lowest_in_descent), where rise_index is -1 if no sample beats `peak`.
        """
        lowest = elevations[dip_start]
        idx = dip_start
        # `<= peak` keeps returns to exact `peak` inside the descent; only `> peak` ends it.
        while idx < len(elevations) and elevations[idx] <= peak:
            if elevations[idx] < lowest:
                lowest = elevations[idx]
            idx += 1
    
        if idx == len(elevations):
            return -1, lowest
        return idx, lowest
    

    Because a rejected dip immediately exits the main loop and an accepted dip jumps straight to j = rise_index, no valley checkpoint is ever visited twice—keeping the entire runtime O(n).

  5. Code the main loop and exact integer 20% check

    Inside the dip branch, check the three conditions in order:

    1. tolerate_descent is True.
    2. rise_index != -1 (a later checkpoint strictly exceeds peak).
    3. loss is at most 20% of gain: instead of floating-point loss <= 0.2 * gain (which suffers binary rounding error), multiply both sides by 5 and test 5 * loss <= gain in exact integers.

    When all three pass, set j = rise_index so the very next iteration hits elevations[rise_index] > peak, updating peak and peak_index so future dips are judged against the higher peak and wider gain = peak - elevations[start].

    def first_climb(elevations: list[int], tolerate_descent: bool) -> list[int]:
        start = find_start(elevations)
        if start == -1:
            return []
    
        # peak: highest elevation reached so far in this climb.
        # peak_index: FIRST index where `peak` was reached (flat samples at `peak` are excluded).
        peak = elevations[start]
        peak_index = start
        j = start + 1
    
        while j < len(elevations):
            if elevations[j] > peak:
                peak = elevations[j]
                peak_index = j
                j += 1
            elif elevations[j] == peak:
                # Flat plateau at the current peak: advance `j` without moving `peak_index`.
                j += 1
            else:
                # elevations[j] < peak: a descent starts at index `j`.
                if not tolerate_descent:
                    break
    
                rise_index, lowest = scan_descent(elevations, j, peak)
                if rise_index == -1:
                    break
    
                gain = peak - elevations[start]
                loss = peak - lowest
                # Check `loss <= 0.20 * gain` in exact integer arithmetic (`5 * loss <= gain`).
                if 5 * loss > gain:
                    break
    
                # Descent tolerated: jump straight to `rise_index` so we never re-scan the dip.
                j = rise_index
    
        return [start, peak_index]
    
  6. Trace Example 3 step by step

    Let's trace elevations = [5, 2, 17, 14, 18, 18, 16, 18] with tolerate_descent = True:

    Step             | j | elev[j] | peak (at idx) | Action
    -----------------+---+---------+---------------+------------------------------------------------------
    find_start       | - | -       | 2 (at 1)      | 5 -> 2 drops; 2 -> 17 rises, so start = 1, j = 2
    New high         | 2 | 17      | 17 (at 2)     | 17 > 2 -> peak = 17, peak_index = 2, j = 3
    First dip        | 3 | 14      | 17 (at 2)     | 14 < 17 -> scan_descent finds rise_index=4 (18), low=14
                     |   |         |               | gain=17-2=15, loss=17-14=3; 5*3 <= 15 -> jump j = 4
    New high         | 4 | 18      | 18 (at 4)     | 18 > 17 -> peak = 18, peak_index = 4, j = 5
    Flat plateau     | 5 | 18      | 18 (at 4)     | 18 == 18 -> keep peak_index = 4, j = 6
    Second dip       | 6 | 16      | 18 (at 4)     | 16 < 18 -> scan_descent sees [16, 18], never > 18
                     |   |         |               | rise_index = -1 -> break!
    
    Return [start, peak_index] = [1, 4].
    

    Notice how index 5 (flat 18) left peak_index at 4, and [16, 18] at the tail was rejected because reaching 18 again did not strictly beat 18.

  7. Complete solution

    Here is the complete O(n) solution:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def find_start(elevations: list[int]) -> int:
        """Return the index right before the first increase, or -1 if no climb exists."""
        # Strict `>` skips any flat stretch before the climb actually begins rising.
        for i in range(len(elevations) - 1):
            if elevations[i + 1] > elevations[i]:
                return i
        return -1
    
    
    def scan_descent(elevations: list[int], dip_start: int, peak: int) -> Tuple[int, int]:
        """Scan forward from `dip_start` until an elevation strictly above `peak` is found.
    
        Returns (rise_index, lowest_in_descent), where rise_index is -1 if no sample beats `peak`.
        """
        lowest = elevations[dip_start]
        idx = dip_start
        # `<= peak` keeps returns to exact `peak` inside the descent; only `> peak` ends it.
        while idx < len(elevations) and elevations[idx] <= peak:
            if elevations[idx] < lowest:
                lowest = elevations[idx]
            idx += 1
    
        if idx == len(elevations):
            return -1, lowest
        return idx, lowest
    
    
    def first_climb(elevations: list[int], tolerate_descent: bool) -> list[int]:
        start = find_start(elevations)
        if start == -1:
            return []
    
        # peak: highest elevation reached so far in this climb.
        # peak_index: FIRST index where `peak` was reached (flat samples at `peak` are excluded).
        peak = elevations[start]
        peak_index = start
        j = start + 1
    
        while j < len(elevations):
            if elevations[j] > peak:
                peak = elevations[j]
                peak_index = j
                j += 1
            elif elevations[j] == peak:
                # Flat plateau at the current peak: advance `j` without moving `peak_index`.
                j += 1
            else:
                # elevations[j] < peak: a descent starts at index `j`.
                if not tolerate_descent:
                    break
    
                rise_index, lowest = scan_descent(elevations, j, peak)
                if rise_index == -1:
                    break
    
                gain = peak - elevations[start]
                loss = peak - lowest
                # Check `loss <= 0.20 * gain` in exact integer arithmetic (`5 * loss <= gain`).
                if 5 * loss > gain:
                    break
    
                # Descent tolerated: jump straight to `rise_index` so we never re-scan the dip.
                j = rise_index
    
        return [start, peak_index]
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture tracking a hiker's ascent along an altitude profile with two markers: a summit flag planted at the earliest checkpoint where the running maximum altitude (peak) was achieved, and an advance scout dispatched whenever the trail drops below peak. Whenever the trail climbs to a new high, we move the summit flag forward; across a flat plateau at peak, we walk past without moving the flag (excluding flat summit stretches automatically); and when the trail dips, strict mode stops immediately while dip-tolerant mode sends the scout ahead only until the trail climbs strictly above peak, checking whether the deepest point in that dip lost at most 20% of the net rise so far (5 * loss <= gain).

A naive implementation checks dip recovery by scanning the entire remaining array max(elevations[j:]) > peak and slicing elevations[j:rise] on every dip. Across a 100,000-checkpoint staircase containing 50,000 tiny 1-meter dips, scanning the whole suffix at each dip performs billions of comparisons (O(n^2) time). Having scan_descent halt at the very first checkpoint strictly above peak and jumping j straight to rise_index ensures no dipped checkpoint is ever inspected twice, guaranteeing linear runtime.

Walk through Example 3 (elevations = [5, 2, 17, 14, 18, 18, 16, 18], tolerate_descent = True): 1. find_start skips 5 -> 2 and spots 2 -> 17 at start = 1, then j = 2 sets peak = 17, peak_index = 2. 2. At j = 3, 14 < 17 dispatches scan_descent, which stops at rise_index = 4 (18 > 17) with lowest = 14. 3. Because gain = 17 - 2 = 15 and loss = 17 - 14 = 3 satisfy 5 * 3 <= 15, j jumps to 4, updating peak = 18 and peak_index = 4. 4. At j = 5, 18 == 18 leaves peak_index = 4; at j = 6, scan_descent scans [16, 18] without finding > 18 (rise_index = -1), ending the loop and returning [1, 4].

Complexity

Let n be len(elevations).

  • Time: O(n). find_start visits each adjacent pair up to start once. Afterward, j advances one step at a time on rises and plateaus; on each dip, scan_descent walks across the valley once and either the loop exits (break) or j jumps directly to rise_index past the entire valley. Every index is read at most twice overall.
  • Space: O(1). Only a constant number of scalar integer variables (start, peak, peak_index, j, rise_index, lowest) are maintained regardless of n.

Edge cases

  • No upward step ([], [7], [4, 4, 4], [9, 7, 5, 1]): find_start returns -1, producing [] under both modes.
  • Flat lead-in before rising ([3, 3, 3, 4]): begins at index 2 right before 4, excluding indices 0 and 1.
  • Flat summit plateau ([1, 2, 2, 2]): finishes at index 1 where 2 first appears.
  • Touching exact peak mid-dip ([0, 10, 9, 10, 11]): revisiting 10 at index 3 remains inside the dip (<= peak), so scan_descent continues to 11 at index 4 and returns [0, 4].
  • Exact 20% threshold (gain = 15, loss = 3): 5 * 3 == 15 passes 5 * loss <= gain; loss = 4 (5 * 4 = 20 > 15) fails.
  • Shallow dip at the end that never beats peak: even when 5 * loss <= gain, rise_index == -1 ends the climb at peak_index.
  • Negative altitudes ([-5, -10, -3, -4, 0]): gain = peak - elevations[start] (-3 - (-10) = 7) and loss = peak - lowest (-3 - (-4) = 1) use signed differences, behaving identically to positive altitudes.

Common mistakes

  • Using >= in find_start or when updating peak_index: >= in find_start pulls flat lead-in checkpoints into the climb, and >= on peak_index pulls flat summit plateaus into the climb.
  • Testing only the first dipped sample rather than the valley minimum: in [0, 10, 9, 7, 9, 11], index 2 drops by 1, whereas index 3 drops to 7 (loss = 3, 5 * 3 > 10), disqualifying the dip.
  • Halting scan_descent on < peak instead of <= peak: halting when altitude returns to peak misclassifies [0, 10, 9, 10, 11] as failing to recover (10 is not > 10).
  • Measuring gain from elevations[0] or 0: gain is relative to elevations[start]; in [100, 0, 10, 8, 11], start = 1 (0), giving gain = 10, not -90.
  • Using floating-point loss / gain <= 0.2: IEEE-754 floats cannot represent 0.2 exactly; integer cross-multiplication 5 * loss <= gain avoids precision drift.

Follow-up questions

  • How would you find every climb along the profile in linear or near-linear time instead of stopping after the first? Restarting find_start after each climb's peak_index works functionally, though a naive restart risks O(n^2) time when repeated rejected dips scan the same long tail (e.g., [0, 50, 0, 1, 0, 1, ...]). To keep multi-climb detection fast, precompute for every index the earliest later index with a strictly greater altitude in O(n) time via a monotonic stack (a stack kept ordered by altitude so each index is pushed and popped at most once), and query the minimum altitude over [dip_start, rise_index) in O(1) time using a sparse table (an O(n log n) lookup table precomputing minimums across power-of-two ranges).
  • If the maximum tolerated dip is passed as an arbitrary percentage such as 35%, how can you avoid floating-point rounding bugs? Represent the percentage as an exact integer ratio (numerator, denominator)—such as (35, 100) or (7, 20)—and check denominator * loss <= numerator * gain. Floating-point products like 0.35 * 180 evaluate to 62.99999999999999 in IEEE-754 binary math, making 63 <= 0.35 * 180 evaluate to False even though 63 is 35% of 180.
  • What preprocessing would you add before running this detector on noisy real-world GPS or barometric altitude data? Raw sensor traces jitter by 1–3 meters even along steady grades, causing false starts and premature summits. Smooth the raw series first with a short moving average or median filter (replacing each reading with the mean or median of a small neighborhood to suppress single-sample spikes), and require a minimum net gain threshold (such as at least 10 meters of vertical rise) before reporting a climb.

Follow-up questions

Similar questions

More Strava interview questions

All 1 Strava questions →