Skip to the code
cf.
+10 XP

#185 Leaderboard After K Passes

easy

A teaching tool shows bubble sort one pass at a time. One pass walks from the start of the list and swaps each pair of neighbors where the left one is bigger. Pass number p (starting at 1) stops before the last p - 1 items, which are already in place.

Write afterPasses(nums, k) that returns the list after k passes of bubble sort (ascending). If the list becomes sorted earlier, extra passes change nothing. Do not change nums; return a new array.

Example 1

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

One pass carries 5 right until it meets the bigger 8.

Example 2

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

The second pass swaps 4 and 2.

Constraints

  • 0 <= nums.length <= 1000
  • 0 <= k <= 1000
  • -10^6 <= nums[i] <= 10^6
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).