← Practice problem bank

Jan 28, 2026

Elemental Alchemist's Formula

Daily Challenge Archive · Open

mediumsorting

150 pts · 2000 ms · 256 MB · Practice only

Problem

Given a list of n elements (1 <= n <= 10^3) that are in some arbitrary order, and another list of the same elements but in the specific order required by your formula, your task is to re-arrange the first list into the order of the second list using the fewest number of swaps. Each swap operation can change the places of exactly two elements. Note that the elements are distinguishable and all elements in the list are distinct. For example, if the initial sequence of elements is [3, 2, 1, 5, 4] and the required sequence is [1, 2, 3, 4, 5], the minimum number of swaps is 2.

Hints
Use a hash map to improve the time complexity of finding the index of an element in the array. Also, consider edge cases where the array is already sorted or is sorted in reverse order. The array may contain any integer values, not only consecutive integers.

Input format

The first line contains an integer n, the number of elements. The second line contains n space-separated integers, the initial sequence of elements. The third line contains n space-separated integers, the required sequence of elements.

Output format

A single integer - the minimum number of swaps required to arrange the elements as per the formula's specific order.

Constraints

1 <= n <= 10^3, -10^3 <= elements <= 10^3

Sample input

5
3 2 1 5 4
1 2 3 4 5

Sample output

2

Sign in to submit solutions

Run your code against all test cases and get instant feedback.

Sign in