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):startis the smallest index0 <= s < len(elevations) - 1whereelevations[s + 1] > elevations[s](the checkpoint immediately preceding the very first upward step). Any downhill or level checkpoints beforesare excluded. If no adjacent pair increases, return[]. - Closing index (
end, both modes): LetPbe the maximum altitude attained during the climb. The climb ends at the earliest index where that final summit altitudePis reached—any subsequent checkpoints sitting flat atPare excluded. Because at least one upward step occurs,start < endalways holds. - Strict mode (
tolerate_descent = False): Beginning atstart, 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 atstart, the climb advances whenever altitude rises or stays level at the running highP. As soon as a checkpoint falls strictly belowP, a candidate dip starts at that checkpoint and encompasses all consecutive checkpoints up to—but not including—the earliest later checkpoint with altitude strictly aboveP(revisitingPitself stays inside the dip and does not close it). Letgain = P - elevations[start]be the net vertical rise accumulated up toP, and letloss = P - valley_min, wherevalley_minis the minimum altitude inside the dip. A dip is accepted if and only if both conditions hold:- At least one later checkpoint after the dip starts has altitude strictly greater than
P, and -
lossis no more than20%ofgain, checked in exact integer arithmetic via5 * loss <= gain.When a dip is accepted, the climb resumes from that first checkpoint strictly above
P(establishing a new higherP, with any subsequent dips measured against the updatedPandgain). When a dip is rejected, the climb terminates back at the index wherePwas first reached.
- At least one later checkpoint after the dip starts has altitude strictly greater than
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]satisfying0 <= start < end < len(elevations).
Step-by-step walkthrough
Understand the climb rules on an altitude profile
Given checkpoint altitudes
elevationsand a boolean flagtolerate_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 IndexFour crisp rules govern every case:
- Opening index: the smallest
startwithelevations[start + 1] > elevations[start]. Leading downhill or level points beforestartstay outside the climb. - Closing index: the earliest index where the climb's final summit altitude
peakis achieved. Level points sitting atpeakafterward 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 belowpeak, a dip spans from that checkpoint up to the earliest later checkpoint strictly greater thanpeak(revisitingpeakstays inside the dip). Withgain = peak - elevations[start]andloss = peak - lowest_in_dip, if a checkpoint> peakexists and5 * loss <= gain, resume climbing from that higher checkpoint; otherwise finish at the earliest index ofpeak.
- Opening index: the smallest
Locate the opening index
Finding
startis identical under both modes: scan adjacent pairs left to right and return the firstisatisfyingelevations[i + 1] > elevations[i].Using strict
>(rather than>=) skips flat lead-ins like[10, 10, 15, ...]so we land on index1instead of0. 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 -1Track the summit and keep plateaus out of `peak_index`
Starting from
start, maintain two variables while advancingj:peak: the highest altitude reached during the climb so far,peak_index: the earliest index wherepeakwas 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 belowpeak" reduce to the same test (elevations[j] < peak)! At eachj:elevations[j] > peak: new high reached—update bothpeak = elevations[j]andpeak_index = j.elevations[j] == peak: level plateau at the current summit—incrementjwithout touchingpeak_index. If the climb terminates after this plateau,peak_indexalready marks the beginning of the plateau.elevations[j] < peak: a dip begins! In strict mode,breakimmediately and return[start, peak_index].
Evaluate a dip in one forward scan
When
tolerate_descentisTrueandelevations[j] < peak, resist checkingmax(elevations[j:]) > peakbefore finding the recovery checkpoint: scanning the entire remaining suffix on every dip costsO(n)per dip, turning a100,000-checkpoint staircase with50,000tiny dips intoO(n^2)(~2.5 billion steps).Instead,
scan_descent(elevations, dip_start, peak)walks forward fromdip_startonly until the first checkpoint strictly greater thanpeak(or the end of the array), trackinglowestalong the way:- Loop while
elevations[idx] <= peak(using<=, not<), because returning to exactpeakdoes not end the dip—only strictly exceedingpeakends it. - Reaching
idx == len(elevations)means no later checkpoint beatpeak, returning-1forrise_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, lowestBecause 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 runtimeO(n).- Loop while
Code the main loop and exact integer 20% check
Inside the dip branch, check the three conditions in order:
tolerate_descentisTrue.rise_index != -1(a later checkpoint strictly exceedspeak).lossis at most 20% ofgain: instead of floating-pointloss <= 0.2 * gain(which suffers binary rounding error), multiply both sides by5and test5 * loss <= gainin exact integers.
When all three pass, set
j = rise_indexso the very next iteration hitselevations[rise_index] > peak, updatingpeakandpeak_indexso future dips are judged against the higherpeakand widergain = 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]Trace Example 3 step by step
Let's trace
elevations = [5, 2, 17, 14, 18, 18, 16, 18]withtolerate_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(flat18) leftpeak_indexat4, and[16, 18]at the tail was rejected because reaching18again did not strictly beat18.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_startvisits each adjacent pair up tostartonce. Afterward,jadvances one step at a time on rises and plateaus; on each dip,scan_descentwalks across the valley once and either the loop exits (break) orjjumps directly torise_indexpast 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 ofn.
Edge cases
- No upward step (
[],[7],[4, 4, 4],[9, 7, 5, 1]):find_startreturns-1, producing[]under both modes. - Flat lead-in before rising (
[3, 3, 3, 4]): begins at index2right before4, excluding indices0and1. - Flat summit plateau (
[1, 2, 2, 2]): finishes at index1where2first appears. - Touching exact
peakmid-dip ([0, 10, 9, 10, 11]): revisiting10at index3remains inside the dip (<= peak), soscan_descentcontinues to11at index4and returns[0, 4]. - Exact 20% threshold (
gain = 15, loss = 3):5 * 3 == 15passes5 * loss <= gain;loss = 4(5 * 4 = 20 > 15) fails. - Shallow dip at the end that never beats
peak: even when5 * loss <= gain,rise_index == -1ends the climb atpeak_index. - Negative altitudes (
[-5, -10, -3, -4, 0]):gain = peak - elevations[start](-3 - (-10) = 7) andloss = peak - lowest(-3 - (-4) = 1) use signed differences, behaving identically to positive altitudes.
Common mistakes
- Using
>=infind_startor when updatingpeak_index:>=infind_startpulls flat lead-in checkpoints into the climb, and>=onpeak_indexpulls flat summit plateaus into the climb. - Testing only the first dipped sample rather than the valley minimum: in
[0, 10, 9, 7, 9, 11], index2drops by1, whereas index3drops to7(loss = 3,5 * 3 > 10), disqualifying the dip. - Halting
scan_descenton< peakinstead of<= peak: halting when altitude returns topeakmisclassifies[0, 10, 9, 10, 11]as failing to recover (10is not> 10). - Measuring
gainfromelevations[0]or0:gainis relative toelevations[start]; in[100, 0, 10, 8, 11],start = 1(0), givinggain = 10, not-90. - Using floating-point
loss / gain <= 0.2: IEEE-754 floats cannot represent0.2exactly; integer cross-multiplication5 * loss <= gainavoids 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_startafter each climb'speak_indexworks functionally, though a naive restart risksO(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 inO(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)inO(1)time using a sparse table (anO(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 checkdenominator * loss <= numerator * gain. Floating-point products like0.35 * 180evaluate to62.99999999999999in IEEE-754 binary math, making63 <= 0.35 * 180evaluate toFalseeven though63is35%of180. - 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
gainthreshold (such as at least 10 meters of vertical rise) before reporting a climb.
Follow-up questions
- How would you find every climb along the profile in linear or near-linear time instead of stopping after the first?
- If the maximum tolerated dip is passed as an arbitrary percentage such as 35%, how can you avoid floating-point rounding bugs?
- What preprocessing would you add before running this detector on noisy real-world GPS or barometric altitude data?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array