![]() |
VOOZH | about |
Given two arrays a[] and b[] of the same length, containing the same values but in different orders (with no duplicates).
The task is to make b[] identical to a[] using the minimum number of swaps.
Examples:
Input: a[] = [3, 6, 4, 8], b[] = [4, 6, 8, 3]
Output: 2
Explanation: To make b[] identical to a[], we need 2 swaps:
1. Swap 4 with 8, resulting in b[] = [8, 6, 4, 3].
2. Swap 8 with 3, resulting in b[] = [3, 6, 4, 8].Input: a[] = [1, 2, 3], b[] = [1, 3, 2]
Output: 1
Explanation: To make b[] identical to a[], we need 1 swap:
1. Swap 3 with 2, resulting in b[] = [1, 2, 3].Input: a[] = [5, 2, 6, 9], b[] = [5, 2, 6, 9]
Output: 0
Explanation: b[] is already identical to a[], so no swaps are needed.
Table of Content
The idea is compare each element a[i] and if the element doesn't match, search the correct one in the rest of b[] and swap. This approach ensures each mismatch is corrected one at a time, even if it takes multiple passes. Since elements are distinct and positions known, swapping will eventually align both arrays
2
Time Complexity: O(n^2), due to two nested loops for each mismatch check.
Space Complexity: O(1), as no extra space used beyond variables.
The idea is to use a hash map for quick index lookups. First, we store the positions of elements in a in a hash map, allowing constant-time retrieval of their correct positions. Then, we iterate through b, and whenever an element is out of place, we swap it with the element at its correct position using the hashmap. This ensures that each swap moves an element closer to its target position. If a swap occurs, we recheck the current index to ensure correctness before proceeding.
Output:
2Time Complexity: O(n), as each element is processed once, and swaps are performed in constant time.
Space Complexity: O(n), due to hash map is used to store element indices, requiring additional space.