VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-swap-to-make-two-arrays-equal/

⇱ Minimum Swaps to Make Arrays Equal - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum Swaps to Make Arrays Equal

Last Updated : 14 Jun, 2026

Given two arrays a[] and b[] of the same size n, in one swap you can swap a[i] with b[i]. Find the minimum number of swaps required to make all elements of a[] equal or all elements of b[] equal. If it is not possible return -1.

Examples:

Input: a[] = [2, 1, 2, 2], b[] = [3, 2, 4, 4]
Output: 1
Explanation: Swap a[1] with b[1]. a[] becomes [2, 2, 2, 2] and b[] becomes [3, 1, 4, 4]. All elements of a[] are equal.

Input: a[] = [1, 1, 2], b[] = [1, 1, 1]
Output: 0
Explanation: All elements of b[] are already equal, no swaps needed.

[Naive Approach] Trying All Possible Target Values - O(n) Time and O(n) Space

The idea is to try every unique value present in both arrays as a potential target. For each candidate target, count how many swaps are needed to make all elements of a[] equal to that target. If at any index neither a[i] nor b[i] equals the target, it is impossible for that candidate. Return the minimum swaps across all valid candidates or -1 if none work.


Output
1

[Expected Approach] Using First Element as Candidate - O(n) Time and O(1) Space

The key insight is that the final equal element must be either a[0] or b[0] since index 0 can never be swapped with any other index - only a[0] and b[0] can occupy position 0. So we only need to check these two values as candidates for both arrays giving us at most 4 checks total.


Output
1


Comment
Article Tags:
Article Tags: