Problem 302918 · medium · Level 03 Linear Management & Searching

How Deep Does the Recursion Go?

sorting · quicksort · worst case

Run quicksort with Lomuto's partition and the last element of each range as the pivot. Count how deeply the partitioning nests: the first range counts as depth 1, the ranges it produces as depth 2, and so on. Ranges of fewer than two elements return immediately and do not count.

Write quicksort_depth(nums) returning the greatest depth reached, or 0 when nothing is ever partitioned.

Examples

Input:  nums = [1, 2, 3, 4]
Output: 3
Explanation: each partition peels off only the largest element, so the ranges are 4, 3 and 2 elements long.

Input:  nums = [2, 1, 3]
Output: 2

Constraints

  • 0 <= len(nums) <= 2000, -10**9 <= nums[i] <= 10**9
  • An already sorted list of length n reaches depth n - 1, which is why a real quicksort never takes the last element blindly.

Goals

  • Measure the recursion depth instead of guessing it
  • See that sorted input is the worst case for a last-element pivot
  • Separate the ranges that really partition from the ones that return at once
Starting Python…