Skip to the code
+25 XP

#187 Fewest Swaps to Order Tabs

medium

A browser extension reorders open tabs by their numeric IDs, ascending. Moving tabs is slow, so it only uses swaps: one swap exchanges the positions of any two tabs, not just neighbors.

Write minSwaps(ids) that returns the smallest number of swaps that sorts ids ascending. All IDs are different.

Example 1

Input: ids = [4,3,1,2]
Output: 3

Each tab is in another tab's spot, forming one loop of 4. A loop of 4 needs 3 swaps.

Example 2

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

Swap 5 with 2, then 4 with 3.

Constraints

  • 0 <= ids.length <= 3 * 10^5
  • All values are different.
  • -10^9 <= ids[i] <= 10^9
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).