1334. Natural Run Passes

Medium3.5 points estimatedMerge SortArraySimulation

A natural merge sort exploits the order that is already present in the data. A run is a maximal stretch of consecutive elements in non-decreasing order. In one pass, the current array is split into its runs, which are recomputed from scratch before every pass, and the runs are merged in pairs: run 1 with run 2, run 3 with run 4, and so on. If the number of runs is odd, the last run is copied unchanged. Each merge produces a sorted block, and the blocks are laid out in the same order to form the next array. Return how many passes are needed until the whole array is a single run. An array that is already non-decreasing needs 0 passes. Simulate the passes directly.

Example 1

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

The runs [3] and [1, 2] merge into [1, 2, 3] in one pass.

Example 2

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

The array is already a single run, so no pass is needed.

Example 3

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

Five runs become three, then two, then one, which takes 3 passes.

Constraints

1 ≤ n ≤ 1000

-109 ≤ nums[i] ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n log n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…