Skip to the code
cf.
+10 XP

#213 TimSort Minimum Run Length

easy

TimSort picks a minimum run length, minRun, from the array's length n, so that the number of runs is a power of two or a little less, which keeps merges balanced. V8 and Python compute it the same way:

  • While n is at least 64, remember whether the lowest bit of n is 1 (set a flag r to 1 if any shifted-out bit was 1), then shift n right by one bit.
  • The answer is the final n plus r.

Write minRunLength(n) that returns this value. For n below 64 it is just n: such arrays are sorted entirely with insertion sort.

Example 1

Input: n = 64
Output: 32

64 is 1000000 in binary. One shift gives 32, and no 1 bit was dropped.

Example 2

Input: n = 65
Output: 33

65 is 1000001. Shifting drops a 1, so add 1 to 32.

Constraints

  • 0 <= n <= 2^31 - 1
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).