05(June) Swapping pairs make sum equal

05. Swapping Pairs to Make Sum Equal

The problem can be found at the following link: Question Link

Problem Description

Given two arrays of integers a[] and b[] of size n and m, the task is to check if a pair of values (one value from each array) exists such that swapping the elements of the pair will make the sum of the two arrays equal.

Example:

Input:

n = 6, m = 4
a[] = {4, 1, 2, 1, 1, 2}
b[] = {3, 6, 3, 3}

Output:

1

Explanation: Sum of elements in a[] = 11, Sum of elements in b[] = 15. To get the same sum from both arrays, we can swap the following values: 1 from a[] and 3 from b[].

My Approach

  1. Calculate Sums:

    • Compute the sum of elements in arrays a[] and b[], denoted as sumA and sumB.

  2. Check for Even Difference:

    • If the difference (sumA - sumB) is odd, return -1, as we cannot balance the sums by swapping integer values.

  3. Calculate Target Difference:

    • The target difference for a successful swap is (sumA - sumB) / 2.

  4. Use a Set for Efficient Lookup:

    • Store all elements of array b[] in a set for O(1) average-time complexity lookups.

  5. Find Swap Pair:

    • Iterate through each element in array a[]. For each element, check if element - target exists in the set of b[]. If found, return 1 indicating a successful swap exists.

  6. Return Result:

    • If no such pair is found after checking all elements, return -1.

Time and Auxiliary Space Complexity

Expected Time Complexity: O(mlogm+nlogn), where (n) is the size of array a[] and (m) is the size of array b[]. This includes the time to compute sums, populate the set, and check for potential swaps.

Expected Auxiliary Space Complexity: O(1), as we store all elements of array b[] in a set for quick lookups.

Code (C++)

Code (Java)

Code (Python)

Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


📍Visitor Count

Last updated