1151. Bubble Pass Count
A teacher sorts a row of exam scores with bubble sort. One pass scans the row from left to right and swaps every adjacent pair where the left score is strictly greater than the right score. The teacher stops as soon as a full pass makes no swap. Given nums, return how many passes perform at least one swap before the row is sorted, which is 0 for a row that is already sorted. Equal scores are never swapped.
1 <= nums.length <= 10^5 and -10^9 <= nums[i] <= 10^9, so simulating the passes is too slow. Each pass moves every element that has a larger element before it exactly one place to the left, so the answer is the largest distance any element must travel left: compare its original index with its index in the stable sorted order. Use O(n log n) time and O(n) space.
Example 1
- Input:
- nums = [3,1,2]
- Output:
- 1
- Explanation:
The first pass gives [1, 2, 3], and the second pass makes no swap, so one pass swaps.
Example 2
- Input:
- nums = [4,3,2,1]
- Output:
- 3
- Explanation:
The value 1 must travel three places left, one per pass, so three passes make swaps.
Example 3
- Input:
- nums = [1,2,3]
- Output:
- 0
- Explanation:
The array is already sorted, so no pass swaps anything.
Constraints
1 ≤ nums.length ≤ 105
-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)