Kth Order Statistic and Broken-Staircase Paths
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement two independent algorithmic functions:
Task A — Order Statistic (kth_smallest)
Accept an unsorted integer list nums together with a 1-based rank k, and return the value that sits at 1-based position k (0-based index k - 1) when nums is arranged in non-decreasing order. Repeated numbers keep separate positions in the sorted sequence. Your algorithm must run in expected O(n) time, where n = len(nums).
Task B — Restricted Staircase Paths (count_ways)
Starting at floor level 0 below a flight of n stairs (numbered 1 through n), each move advances upward by either 1 stair or 2 stairs. A list broken_steps specifies 1-based stair numbers that are damaged and off-limits. Return how many distinct valid move sequences start at 0 and land on stair n without ever landing on a stair listed in broken_steps (return 0 whenever stair n itself is off-limits).
def kth_smallest(nums: List[int], k: int) -> int:
...
def count_ways(n: int, broken_steps: List[int]) -> int:
...
Examples
Example 1
Input: nums = [12, 5, 8, 19, 3, 14], k = 3
Output: 8
Ordering nums produces [3, 5, 8, 12, 14, 19], so the 3rd value from the front is 8.
Example 2
Input: nums = [4, -2, 9, 4, 1, -2], k = 4
Output: 4
Ordering nums with duplicates preserved gives [-2, -2, 1, 4, 4, 9]. Positions 1 through 4 hold -2, -2, 1, and 4, making position 4 equal to 4.
Example 3
Input: nums = [42], k = 1
Output: 42
With only one element present, rank 1 immediately selects 42.
Example 4
Input: nums = [30, 10, 50, 20, 40], k = 5
Output: 50
Ordering nums yields [10, 20, 30, 40, 50], whose 5th (largest) element is 50.
Example 5
Input: n = 5, broken_steps = [3]
Output: 2
Stair 3 cannot be visited, so every valid route must jump across it from stair 2 to stair 4. Exactly two sequences succeed: 0 -> 1 -> 2 -> 4 -> 5 and 0 -> 2 -> 4 -> 5.
Constraints
1 <= k <= len(nums) <= 10^5-10^9 <= nums[i] <= 10^91 <= n <= 10^50 <= len(broken_steps) <= nkth_smallestis evaluated by the automated judge in expectedO(len(nums))time; also definecount_ways(n, broken_steps)in the same module.
Step-by-step walkthrough
Understand both tasks
We need to implement two standalone functions:
- Task A (
kth_smallest, checked directly by the judge): Given an unsorted integer listnumsand a 1-based rankk(1 <= k <= len(nums)), return the element that sits at positionk(indexk - 1) after non-decreasing ordering. Duplicate numbers occupy separate slots — for[4, -2, 9, 4, 1, -2], the ordered values are[-2, -2, 1, 4, 4, 9], sok = 4yields4. We need expectedO(n)time. - Task B (
count_ways): Beginning on floor0, each move climbs+1or+2stairs toward stairnwithout landing on any 1-based stair inbroken_steps. Return how many distinct valid routes reach stairn(or0when stairnitself is off-limits).
- Task A (
Task A baseline: why sorting everything wastes work
The shortest one-line baseline is
sorted(nums)[k - 1], takingO(n log n)time. Calling that out first in an interview is helpful, and its bottleneck is easy to spot: full sorting puts every slice of the list in exact order, even values far away from positionk.To bring expected work down to
O(n), we want to discard large chunks of irrelevant numbers in each pass without sorting inside those discarded chunks.Core idea for Task A: three-way QuickSelect
Pick a random element from our remaining
candidates— the pivot — and deal every element into one of three lists:smaller: items strictly< pivotequal: items== pivotlarger: items strictly> pivot
Without sorting inside
smallerorlarger, we already know the exact 1-based rank intervals covered by the three buckets:1-based ranks: 1 ... len(smaller) | len(smaller)+1 ... len(smaller)+len(equal) | remaining ... Bucket: [ smaller (< p) | equal (== p) | larger (> p) ]Comparing
kagainst those sizes narrows the search to at most one bucket: 1.k <= len(smaller): rankksits insidesmaller, still at rankk. Discardequalandlarger. 2.k <= len(smaller) + len(equal): rankklands insideequal, where every item equalspivot. Returnpivotright away! 3. Otherwise (k > len(smaller) + len(equal)): we skippedlen(smaller) + len(equal)elements smaller than or equal topivot, so look for rankk - len(smaller) - len(equal)insidelarger.Why does random pivot selection run in expected
O(n)time? Half the pivots fall in the middle 50% of the sorted order, throwing away at least 25% ofcandidatesat once. Geometric shrinking (n + (3/4)n + (3/4)^2 * n + ...) totals at most4nwork, which isO(n).Why split into three buckets rather than two? On
100,000copies of7, a two-way< pivotvs>= pivotsplit peels off at most one item per pass (O(n^2)), whereas putting duplicates intoequalcaptures all100,000copies on pass 1 and finishes immediately.Code the three-way partition helper
split_aroundwalksvaluesonce and populatessmaller,equal, andlarger, leaving the caller's input list unmodified.from typing import List, Tuple def split_around(values: List[int], pivot: int) -> Tuple[List[int], List[int], List[int]]: """Partition values into three lists: (< pivot, == pivot, > pivot).""" # Three buckets: e.g. for [5, 3, 3, 1] and pivot=3 -> ([1], [3, 3], [5]). smaller: List[int] = [] equal: List[int] = [] larger: List[int] = [] for value in values: if value < pivot: smaller.append(value) elif value > pivot: larger.append(value) else: equal.append(value) return smaller, equal, largerCode `kth_smallest` with an iterative loop
Unlike QuickSort, which recurses into both left and right halves, QuickSelect keeps at most one bucket per round, so a plain
while Trueloop avoids recursion-depth limits completely.Termination is guaranteed because
pivotcomes fromcandidates, meaninglen(equal) >= 1: every iteration either returnspivotor dropsequaland shrinkscandidatesby at least one element.import random from typing import List def kth_smallest(nums: List[int], k: int) -> int: """Part 1: return the 1-indexed k-th smallest element in nums in average O(n) time.""" if k < 1 or k > len(nums): raise ValueError("k must be between 1 and len(nums)") # candidates: remaining elements that still contain our target k-th smallest value. candidates = nums while True: # Random pivot prevents sorted or reverse-sorted inputs from degrading to O(n^2). pivot = random.choice(candidates) smaller, equal, larger = split_around(candidates, pivot) num_smaller = len(smaller) num_smaller_or_equal = num_smaller + len(equal) # Case 1: rank k falls strictly inside the "< pivot" bucket (positions 1 .. num_smaller). if k <= num_smaller: candidates = smaller # Case 2: rank k lands inside the "== pivot" bucket, so pivot itself is the answer. # Grouping all duplicates in `equal` finishes an all-equal array in one pass. elif k <= num_smaller_or_equal: return pivot # Case 3: rank k is in `larger`; subtract everything we skipped in `smaller` and `equal`. else: k -= num_smaller_or_equal candidates = largerTrace Task A on Example 2
Walk through
nums = [4, -2, 9, 4, 1, -2],k = 4for a representative sequence of random pivots:Round 1: candidates = [4, -2, 9, 4, 1, -2], k = 4 Suppose random pivot = 1 smaller = [-2, -2] (len = 2, covers ranks 1..2) equal = [1] (len = 1, covers rank 3) larger = [4, 9, 4] (len = 3, covers ranks 4..6) k = 4 > 2 + 1 -> continue into `larger`, update k = 4 - 3 = 1 Round 2: candidates = [4, 9, 4], k = 1 Suppose random pivot = 9 smaller = [4, 4] (len = 2, covers ranks 1..2) equal = [9] (len = 1, covers rank 3) larger = [] k = 1 <= 2 -> continue into `smaller`, k stays 1 Round 3: candidates = [4, 4], k = 1 Random pivot = 4 smaller = [] (len = 0) equal = [4, 4] (len = 2, covers ranks 1..2) larger = [] k = 1 <= 0 + 2 -> return 4!Regardless of which pivots
random.choicepicks, every step preserves the target value and finishes with4.Task B: count restricted staircase paths bottom-up
Let
dp[step]store how many valid sequences start at floor0and land onstep. Consider the final move arriving at any intact stairstep >= 2: - Either you stepped+1fromstep - 1, or - You jumped+2fromstep - 2.Because those two sets of paths differ in their second-to-last position, they are completely disjoint, giving:
dp[step] = dp[step - 1] + dp[step - 2]Whenever
stepis off-limits (step in broken), no sequence may land there, sodp[step]remains0— which also ensures future moves pushing off fromstepcontribute0.Handling
dp[0]anddp[1]before the loop prevents negative indexing: -dp[0] = 1: standing at floor0before moving is the single starting configuration (so0 -> 2addsdp[0] = 1). -dp[1] = 1when stair1is intact (else0), since0 -> 1is the sole path to stair1. - Starting the loop atstep = 2guaranteesstep - 2 >= 0, avoiding Python'sdp[-1]wrap-around trap.Example 5: n = 5, broken = {3} step: 0 1 2 3 4 5 dp: [ 1 | 1 | 2 | 0 | 2 | 2 ] base 0->1 dp[1] + dp[0] BROKEN dp[3] + dp[2] dp[4] + dp[3] = 1 + 1 = 2 = 0 + 2 = 2 = 2 + 0 = 2 Valid sequences: 0 -> 1 -> 2 -> 4 -> 5 and 0 -> 2 -> 4 -> 5 (dp[5] = 2)Converting
broken_stepsto asetmakes membership checksO(1)and tolerates duplicate or out-of-range stair numbers safely.from typing import List, Set def count_ways(n: int, broken_steps: List[int]) -> int: """Part 2: count distinct ways to climb from ground (0) to step n avoiding broken_steps.""" if n < 0: return 0 # broken: O(1)-lookup set of forbidden 1-indexed stairs, e.g. {3}. broken: Set[int] = set(broken_steps) # dp[step]: number of valid paths from ground (step 0) to `step`. dp: List[int] = [0] * (n + 1) dp[0] = 1 # Base case: 1 way to stand at the bottom before taking any step. if n >= 1 and 1 not in broken: dp[1] = 1 # Step 1 can only be reached via a single 1-step climb from ground. # Start at step 2 so `step - 2` is always >= 0 (avoiding Python negative indexing!). for step in range(2, n + 1): if step in broken: # Cannot land on a broken stair, so dp[step] stays 0. continue # Every valid arrival at `step` came from a 1-step climb (step - 1) or 2-step climb (step - 2). dp[step] = dp[step - 1] + dp[step - 2] return dp[n]Complete solution
Putting both functions together (
kth_smallestis invoked by the automated judge, andcount_wayssolves Task B):from typing import Any, Dict, List, Optional, Set, Tuple import random def split_around(values: List[int], pivot: int) -> Tuple[List[int], List[int], List[int]]: """Partition values into three lists: (< pivot, == pivot, > pivot).""" # Three buckets: e.g. for [5, 3, 3, 1] and pivot=3 -> ([1], [3, 3], [5]). smaller: List[int] = [] equal: List[int] = [] larger: List[int] = [] for value in values: if value < pivot: smaller.append(value) elif value > pivot: larger.append(value) else: equal.append(value) return smaller, equal, larger def kth_smallest(nums: List[int], k: int) -> int: """Part 1: return the 1-indexed k-th smallest element in nums in average O(n) time.""" if k < 1 or k > len(nums): raise ValueError("k must be between 1 and len(nums)") # candidates: remaining elements that still contain our target k-th smallest value. candidates = nums while True: # Random pivot prevents sorted or reverse-sorted inputs from degrading to O(n^2). pivot = random.choice(candidates) smaller, equal, larger = split_around(candidates, pivot) num_smaller = len(smaller) num_smaller_or_equal = num_smaller + len(equal) # Case 1: rank k falls strictly inside the "< pivot" bucket (positions 1 .. num_smaller). if k <= num_smaller: candidates = smaller # Case 2: rank k lands inside the "== pivot" bucket, so pivot itself is the answer. # Grouping all duplicates in `equal` finishes an all-equal array in one pass. elif k <= num_smaller_or_equal: return pivot # Case 3: rank k is in `larger`; subtract everything we skipped in `smaller` and `equal`. else: k -= num_smaller_or_equal candidates = larger def count_ways(n: int, broken_steps: List[int]) -> int: """Part 2: count distinct ways to climb from ground (0) to step n avoiding broken_steps.""" if n < 0: return 0 # broken: O(1)-lookup set of forbidden 1-indexed stairs, e.g. {3}. broken: Set[int] = set(broken_steps) # dp[step]: number of valid paths from ground (step 0) to `step`. dp: List[int] = [0] * (n + 1) dp[0] = 1 # Base case: 1 way to stand at the bottom before taking any step. if n >= 1 and 1 not in broken: dp[1] = 1 # Step 1 can only be reached via a single 1-step climb from ground. # Start at step 2 so `step - 2` is always >= 0 (avoiding Python negative indexing!). for step in range(2, n + 1): if step in broken: # Cannot land on a broken stair, so dp[step] stays 0. continue # Every valid arrival at `step` came from a 1-step climb (step - 1) or 2-step climb (step - 2). dp[step] = dp[step - 1] + dp[step - 2] return dp[n]✅ Submit now — all tests should pass.
Intuition & how it works
For Task A (kth_smallest), picture finding the 4th shortest runner on a track team without lining up the entire roster. Pick a random runner as a reference height — a pivot (a benchmark value used to divide a collection) — and direct everyone into one of three lanes: shorter than the pivot, identical height, or taller. Counting the runners in each lane immediately tells you which single lane holds rank 4, letting you send the other two lanes home untouched. Repeating that single-sided narrowing is QuickSelect (an order-statistic algorithm that splits around pivots and continues into only the bucket containing the target rank).
For Task B (count_ways), picture writing a tally on every stair recording how many valid routes reach it from floor 0. Any damaged stair gets 0 because nobody may stand there; every intact stair simply adds the tallies written one stair below and two stairs below, since the last upward move onto step had to push off from step - 1 or step - 2. Filling answers upward from 0 so each sub-staircase is solved once and reused is dynamic programming (solving overlapping subproblems in dependency order and storing intermediate results).
Why do simpler attempts fall short? Full sorting in Task A spends O(n log n) work ordering parts of the array we never inspect, while QuickSelect with a deterministic first-element pivot or a 2-way split degrades to O(n^2) on pre-sorted or all-equal inputs. In Task B, naive recursion into +1 and +2 branches without memoizing revisits identical stairs exponentially (O(2^n) time).
Here is a concrete trace of each task from the examples:
- Task A (Example 2): nums = [4, -2, 9, 4, 1, -2], k = 4. Choosing pivot = 1 produces smaller = [-2, -2] (2 items), equal = [1] (1 item), and larger = [4, 9, 4] (3 items). Because 4 > 2 + 1, we drop the first 3 items and search for rank k = 4 - 3 = 1 inside [4, 9, 4], returning 4.
- Task B (Example 5): n = 5, broken_steps = [3]. Starting from dp[0] = 1 and dp[1] = 1, we compute dp[2] = 1 + 1 = 2, dp[3] = 0 (damaged), dp[4] = dp[3] + dp[2] = 0 + 2 = 2, and dp[5] = dp[4] + dp[3] = 2 + 0 = 2 (routes 0 -> 1 -> 2 -> 4 -> 5 and 0 -> 2 -> 4 -> 5).
Complexity
Let n = len(nums) in Task A, and in Task B let n be the destination stair and b = len(broken_steps).
kth_smallest—O(n)average time,O(n^2)worst-case time: each pass scans the remainingcandidatesonce, and a uniformly random pivot shrinkscandidatesby at least one quarter on average, so expected work sums geometrically (n + (3/4)n + (3/4)^2 * n + ... <= 4n) toO(n). Only an adversarial streak of extreme random pivots shrinks the list by 1 per round (O(n^2)).kth_smallest—O(n)extra space:split_aroundbuilds freshsmaller,equal, andlargerlists holding at mostnelements in the initial pass. (When mutatingnumsin place is acceptable, a Dutch National Flag partition — a three-pointer swap pass grouping< pivot,== pivot, and> pivotinside the existing list — lowers auxiliary space toO(1).)count_ways—O(n + b)time andO(n + b)space: building thebrokenhash set visitsbentries once, and the loop visits stairs2..nonce doingO(1)set lookups and integer additions, storingn + 1counts indpplus up tobelements inbroken. (Without modular arithmetic, path counts grow exponentially like Fibonacci numbers, so big-integer addition on hugenadds anO(n)bit-length factor.)
Edge cases
- Boundary ranks
k = 1andk = len(nums): return the minimum and maximum values respectively. - Repeated numbers: duplicates hold distinct positions in sorted order; in
[4, -2, 9, 4, 1, -2],k = 1andk = 2both return-2, whilek = 4andk = 5both return4. - All elements identical (e.g.,
100,000copies of7):equalcollects all elements in round 1 and returns inO(n)time. - Already sorted or reverse-sorted inputs: random pivot choice keeps expected time linear.
n = 1(single stair): returns1if stair1is usable and0if stair1is damaged, skippingrange(2, n + 1)cleanly.- Destination stair
nis damaged:n in brokenleavesdp[n] = 0. - Two adjacent damaged stairs (
iandi + 1withi + 1 <= n): neither a+1nor a+2move can clear two blocked stairs in a row, so every higher stair naturally stays0. - Stair
1is damaged:dp[1] = 0, requiring any valid sequence (whenn >= 2and stair2is intact) to open with0 -> 2. - Duplicate or out-of-bounds entries in
broken_steps: storingbroken_stepsin asetdeduplicates automatically and ignores values outside1..nwithout raisingIndexError.
Common mistakes
- Mixing up 1-based
kwith 0-based indexing: rankk = 1meanssorted(nums)[0], not index1. - Forgetting to subtract skipped elements from
k: moving intolargerdiscardslen(smaller) + len(equal)smaller-or-equal elements, sokmust decrease by that exact total. - Two-way
< pivot/>= pivotpartitioning with duplicates: on all-equal inputs,>= pivotkeepsn - 1items per round (O(n^2)) or loops infinitely (nitems) if the pivot element isn't removed. - Deterministic first-element pivot: degrades to
O(n^2)on sorted arrays. - Evaluating
dp[step - 2]atstep == 1in Python:dp[-1]reads the tail of the list instead of failing! Settingdp[0]anddp[1]explicitly before starting atstep = 2avoids negative indices altogether. - Storing
-1insidedpto mark damaged stairs: corruptsdp[step - 1] + dp[step - 2]unless checked everywhere and crashes ifbroken_stepscontains an index> n; leaving damaged stairs at0with abrokenset is cleaner.
Alternative approaches
- Full sort (
sorted(nums)[k - 1]):O(n log n)worst-case time in one line, practical for small lists. - Bounded max-heap (
O(n log k)time,O(k)space): a max-heap (a tree structure keeping its largest item at the root inO(1)time withO(log k)updates; implemented in Python'sheapqvia negated values) tracks theksmallest items across streaming data using onlyO(k)RAM. - Median of medians (
O(n)deterministic worst-case time): partitions into groups of five to guarantee a balanced pivot without randomness, though higher constant factors make randomized QuickSelect faster in practice.
Follow-up questions
- How do the worst-case runtime guarantees of QuickSelect and a heap-based approach differ, and which scenarios favor each method? Randomized QuickSelect achieves
O(n)expected time but has anO(n^2)worst case, whereas building a min-heap (a binary tree keeping its smallest element at the root) withheapq.heapifyinO(n)time and poppingkelements takesO(n + k log n)deterministic worst-case time — orO(n log k)using a size-kmax-heap. Choose QuickSelect when allnnumbers reside in memory and fast average single-query throughput matters most. Choose a heap when you need strict worst-case latency bounds, whenkis much smaller thann, or when values arrive as an unbounded stream where onlyO(k)memory is available. - What changes in the recurrence if each move can advance by 1, 2, or 3 stairs instead of at most 2? Any valid landing on an intact
stepnow originates fromstep - 1,step - 2, orstep - 3, expanding the recurrence todp[step] = dp[step - 1] + dp[step - 2] + dp[step - 3](treating negative indicesstep - jump < 0as0). More generally, for an arbitrary set of allowed positive jump sizesJ, summingdp[step - jump]over alljump in Jwithstep - jump >= 0computes the answer inO(n * |J|)time while damaged stairs still evaluate to0. - Can you compute the broken-staircase path count using constant extra memory beyond the input? Because
dp[step]depends only on the two immediately preceding stairs (dp[step - 1]anddp[step - 2]), you can replace theO(n)array with two rolling integerstwo_back = 0andone_back = 1: for eachstepfrom1ton, setcurrent = 0 if step in broken else one_back + two_backand shifttwo_back, one_back = one_back, current. That drops the DP table toO(1)space; ifbroken_stepsis already sorted (or sorted in place), advancing a single index pointer throughbroken_stepsinstead of allocating asetremoves theO(b)set allocation too.
Follow-up questions
- How do the worst-case runtime guarantees of QuickSelect and a heap-based approach differ, and which scenarios favor each method?
- What changes in the recurrence if each move can advance by 1, 2, or 3 stairs instead of at most 2?
- Can you compute the broken-staircase path count using constant extra memory beyond the input?
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