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^9
  • 1 <= n <= 10^5
  • 0 <= len(broken_steps) <= n
  • kth_smallest is evaluated by the automated judge in expected O(len(nums)) time; also define count_ways(n, broken_steps) in the same module.

Step-by-step walkthrough

  1. Understand both tasks

    We need to implement two standalone functions:

    1. Task A (kth_smallest, checked directly by the judge): Given an unsorted integer list nums and a 1-based rank k (1 <= k <= len(nums)), return the element that sits at position k (index k - 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], so k = 4 yields 4. We need expected O(n) time.
    2. Task B (count_ways): Beginning on floor 0, each move climbs +1 or +2 stairs toward stair n without landing on any 1-based stair in broken_steps. Return how many distinct valid routes reach stair n (or 0 when stair n itself is off-limits).
  2. Task A baseline: why sorting everything wastes work

    The shortest one-line baseline is sorted(nums)[k - 1], taking O(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 position k.

    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.

  3. 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 < pivot
    • equal: items == pivot
    • larger: items strictly > pivot

    Without sorting inside smaller or larger, 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 k against those sizes narrows the search to at most one bucket: 1. k <= len(smaller): rank k sits inside smaller, still at rank k. Discard equal and larger. 2. k <= len(smaller) + len(equal): rank k lands inside equal, where every item equals pivot. Return pivot right away! 3. Otherwise (k > len(smaller) + len(equal)): we skipped len(smaller) + len(equal) elements smaller than or equal to pivot, so look for rank k - len(smaller) - len(equal) inside larger.

    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% of candidates at once. Geometric shrinking (n + (3/4)n + (3/4)^2 * n + ...) totals at most 4n work, which is O(n).

    Why split into three buckets rather than two? On 100,000 copies of 7, a two-way < pivot vs >= pivot split peels off at most one item per pass (O(n^2)), whereas putting duplicates into equal captures all 100,000 copies on pass 1 and finishes immediately.

  4. Code the three-way partition helper

    split_around walks values once and populates smaller, equal, and larger, 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, larger
    
  5. Code `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 True loop avoids recursion-depth limits completely.

    Termination is guaranteed because pivot comes from candidates, meaning len(equal) >= 1: every iteration either returns pivot or drops equal and shrinks candidates by 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 = larger
    
  6. Trace Task A on Example 2

    Walk through nums = [4, -2, 9, 4, 1, -2], k = 4 for 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.choice picks, every step preserves the target value and finishes with 4.

  7. Task B: count restricted staircase paths bottom-up

    Let dp[step] store how many valid sequences start at floor 0 and land on step. Consider the final move arriving at any intact stair step >= 2: - Either you stepped +1 from step - 1, or - You jumped +2 from step - 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 step is off-limits (step in broken), no sequence may land there, so dp[step] remains 0 — which also ensures future moves pushing off from step contribute 0.

    Handling dp[0] and dp[1] before the loop prevents negative indexing: - dp[0] = 1: standing at floor 0 before moving is the single starting configuration (so 0 -> 2 adds dp[0] = 1). - dp[1] = 1 when stair 1 is intact (else 0), since 0 -> 1 is the sole path to stair 1. - Starting the loop at step = 2 guarantees step - 2 >= 0, avoiding Python's dp[-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_steps to a set makes membership checks O(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]
    
  8. Complete solution

    Putting both functions together (kth_smallest is invoked by the automated judge, and count_ways solves 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 remaining candidates once, and a uniformly random pivot shrinks candidates by at least one quarter on average, so expected work sums geometrically (n + (3/4)n + (3/4)^2 * n + ... <= 4n) to O(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_around builds fresh smaller, equal, and larger lists holding at most n elements in the initial pass. (When mutating nums in place is acceptable, a Dutch National Flag partition — a three-pointer swap pass grouping < pivot, == pivot, and > pivot inside the existing list — lowers auxiliary space to O(1).)
  • count_ways — O(n + b) time and O(n + b) space: building the broken hash set visits b entries once, and the loop visits stairs 2..n once doing O(1) set lookups and integer additions, storing n + 1 counts in dp plus up to b elements in broken. (Without modular arithmetic, path counts grow exponentially like Fibonacci numbers, so big-integer addition on huge n adds an O(n) bit-length factor.)

Edge cases

  • Boundary ranks k = 1 and k = 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 = 1 and k = 2 both return -2, while k = 4 and k = 5 both return 4.
  • All elements identical (e.g., 100,000 copies of 7): equal collects all elements in round 1 and returns in O(n) time.
  • Already sorted or reverse-sorted inputs: random pivot choice keeps expected time linear.
  • n = 1 (single stair): returns 1 if stair 1 is usable and 0 if stair 1 is damaged, skipping range(2, n + 1) cleanly.
  • Destination stair n is damaged: n in broken leaves dp[n] = 0.
  • Two adjacent damaged stairs (i and i + 1 with i + 1 <= n): neither a +1 nor a +2 move can clear two blocked stairs in a row, so every higher stair naturally stays 0.
  • Stair 1 is damaged: dp[1] = 0, requiring any valid sequence (when n >= 2 and stair 2 is intact) to open with 0 -> 2.
  • Duplicate or out-of-bounds entries in broken_steps: storing broken_steps in a set deduplicates automatically and ignores values outside 1..n without raising IndexError.

Common mistakes

  • Mixing up 1-based k with 0-based indexing: rank k = 1 means sorted(nums)[0], not index 1.
  • Forgetting to subtract skipped elements from k: moving into larger discards len(smaller) + len(equal) smaller-or-equal elements, so k must decrease by that exact total.
  • Two-way < pivot / >= pivot partitioning with duplicates: on all-equal inputs, >= pivot keeps n - 1 items per round (O(n^2)) or loops infinitely (n items) if the pivot element isn't removed.
  • Deterministic first-element pivot: degrades to O(n^2) on sorted arrays.
  • Evaluating dp[step - 2] at step == 1 in Python: dp[-1] reads the tail of the list instead of failing! Setting dp[0] and dp[1] explicitly before starting at step = 2 avoids negative indices altogether.
  • Storing -1 inside dp to mark damaged stairs: corrupts dp[step - 1] + dp[step - 2] unless checked everywhere and crashes if broken_steps contains an index > n; leaving damaged stairs at 0 with a broken set 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 in O(1) time with O(log k) updates; implemented in Python's heapq via negated values) tracks the k smallest items across streaming data using only O(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 an O(n^2) worst case, whereas building a min-heap (a binary tree keeping its smallest element at the root) with heapq.heapify in O(n) time and popping k elements takes O(n + k log n) deterministic worst-case time — or O(n log k) using a size-k max-heap. Choose QuickSelect when all n numbers reside in memory and fast average single-query throughput matters most. Choose a heap when you need strict worst-case latency bounds, when k is much smaller than n, or when values arrive as an unbounded stream where only O(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 step now originates from step - 1, step - 2, or step - 3, expanding the recurrence to dp[step] = dp[step - 1] + dp[step - 2] + dp[step - 3] (treating negative indices step - jump < 0 as 0). More generally, for an arbitrary set of allowed positive jump sizes J, summing dp[step - jump] over all jump in J with step - jump >= 0 computes the answer in O(n * |J|) time while damaged stairs still evaluate to 0.
  • 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] and dp[step - 2]), you can replace the O(n) array with two rolling integers two_back = 0 and one_back = 1: for each step from 1 to n, set current = 0 if step in broken else one_back + two_back and shift two_back, one_back = one_back, current. That drops the DP table to O(1) space; if broken_steps is already sorted (or sorted in place), advancing a single index pointer through broken_steps instead of allocating a set removes the O(b) set allocation too.

Follow-up questions

Similar questions

More Nio interview questions

All 1 Nio questions →