1364. After K Bubble Passes

A line of runners starts a "bubble drill". In one pass the coach walks from the front: for each index i from 0 to n - 2 in order, if nums[i] > nums[i + 1] the two runners swap places, and equal values never swap.

Given the array nums and an integer k, return the array after exactly k passes. Because k can reach 10^9 and n reaches 10^5, you cannot simulate the passes. Instead, let L[i] be the number of earlier elements strictly greater than nums[i]. Every element with L[i] at least k ends at index i - k, and the remaining free indices, from left to right, receive all other elements in ascending order. Once k reaches n the array is simply sorted. Aim for O(n log n) time and O(n) space.

Example 1

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

In one pass the 4 is carried past 3, 2 and 1 to the end, giving [3, 2, 1, 4].

Example 2

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

Two passes already sort the array and extra passes change nothing, so the answer is [1, 2, 3].

Example 3

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

With k = 0 no pass is made, so the array is unchanged.

Constraints

  • 1 ≤ nums.length ≤ 105

  • 0 ≤ k ≤ 109

  • -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.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

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…