Skip to the code
cf.
+25 XP

#199 How Deep Does Quick Sort Go

medium

Deep recursion can crash a browser tab with "Maximum call stack size exceeded". To see when that risk grows, measure quick sort's recursion depth. Use the Lomuto partition with the last item as the pivot, as on the quick sort page.

The call on the whole list has depth 1, a call made from it has depth 2, and so on. Only calls on parts with at least 2 items count (they partition); calls on smaller parts return at once.

Write maxDepth(nums) that returns the largest depth of any call that partitions. Return 0 if the list has fewer than 2 items.

Example 1

Input: nums = [7,2,9,4,3,8,5]
Output: 3

Depth 1 splits around 5; [2, 4, 3] and [9, 8, 7] are depth 2; [8, 9] (after 7 is placed) is depth 3.

Example 2

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

Sorted input peels off one item per level: parts of 5, 4, 3, and 2 items.

Constraints

  • 0 <= nums.length <= 500
  • -1000 <= nums[i] <= 1000
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).