Program to maximize the number of equivalent pairs after swapping in Python

Suppose we have two lists A and B of the same length, and a 2D list C containing pairs [i, j] that allow us to swap elements A[i] and A[j] as many times as needed. We need to find the maximum number of equivalent pairs where A[i] = B[i] after optimal swapping.

The key insight is that elements connected through swap operations form groups, and within each group, we can arrange elements in any order to maximize matches.

Example

If the input is A = [5, 6, 7, 8], B = [6, 5, 8, 7], and C = [[0, 1], [2, 3]], the output will be 4.

We can swap A[0] with A[1] (making A = [6, 5, 7, 8]) and A[2] with A[3] (making A = [6, 5, 8, 7]), achieving all matches.

Algorithm Steps

The solution uses graph traversal to identify connected components ?

  1. Build a graph where each swap pair creates bidirectional edges
  2. Find all connected components using BFS
  3. For each component, count available elements from B and match them optimally with A elements
  4. Sum up all possible matches

Implementation

from collections import Counter

class Solution:
    def solve(self, A, B, edges):
        N = len(A)
        graph = [[] for _ in range(N)]
        
        # Build adjacency graph from swap edges
        for u, v in edges:
            graph[u].append(v)
            graph[v].append(u)
        
        ans = 0
        seen = [False] * N
        
        # Process each connected component
        for u in range(N):
            if not seen[u]:
                # BFS to find all nodes in this component
                queue = [u]
                seen[u] = True
                
                for node in queue:
                    for neighbor in graph[node]:
                        if not seen[neighbor]:
                            queue.append(neighbor)
                            seen[neighbor] = True
                
                # Count available B values in this component
                count = Counter(B[i] for i in queue)
                
                # Match A values greedily with available B values
                for i in queue:
                    if count[A[i]] > 0:
                        count[A[i]] -= 1
                        ans += 1
        
        return ans

# Test the solution
ob = Solution()
A = [5, 6, 7, 8]
B = [6, 5, 8, 7]
C = [[0, 1], [2, 3]]
print(ob.solve(A, B, C))
4

How It Works

The algorithm treats swap operations as graph edges. Connected components represent groups of positions that can exchange values freely. Within each group:

  • Count how many times each value appears in the corresponding B positions
  • For each A value in the group, check if a matching B value is available
  • Greedily assign matches and decrement the available count

Another Example

# Example with partial matches
A = [1, 2, 3, 4]
B = [2, 1, 1, 4]
C = [[0, 1]]  # Only positions 0 and 1 can swap

ob = Solution()
result = ob.solve(A, B, C)
print(f"Maximum equivalent pairs: {result}")
Maximum equivalent pairs: 3

Here, positions 0 and 1 form one group [1, 2] that can match with B values [2, 1]. Positions 2 and 3 are isolated and position 3 matches by default (A[3] = B[3] = 4).

Conclusion

This solution uses graph theory to identify swappable groups and applies greedy matching within each group. The time complexity is O(N + E) where E is the number of edges, making it efficient for large inputs.

Updated on: 2026-03-25T11:25:04+05:30

286 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements