VOOZH about

URL: https://www.geeksforgeeks.org/dsa/equal-arrays/

⇱ Equal Arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Equal Arrays

Last Updated : 8 Dec, 2025

Given two arrays A[ ] and B[ ]. We can perform the following operation multiple times on the arrays:

  • Select two integers i and j (i != j, 1 ≤ i, j ≤ n).
  • Increase A[i] and B[j] by 1 and decrease A[j] and B[i] by 1.

We need to find whether it is possible to make the two arrays equal by using some number (possible zero) of operations.

Examples:

Input: A[] = [1, 2, 3], B[] = [3, 2, 1]
Output: true
Explanation: By choosing i = 1 and j = 3 and performing the operations, arrays A and B become equal.

Input: A[] = [1, 2], B[] = [2, 1]
Output: false
Explanation: It is not possible to make these two arrays equal.

[Naive Approach] - Brute Force Simulation - O(n^3) Time and O(n) Space

The idea is to simulate the operations step by step. For each index i, if A[i] is less than B[i], we search for another index j where A[j] > B[j] and perform the allowed operation. This moves extra value from A[j] to A[i], while also updating B[j] and B[i] accordingly. We continue this process iteratively until no further changes are possible.


Output
true

[Better Approach] - Using Parity and Sum Check- O(n) Time and O(1) Space

We first check the parity of each element in the two arrays. Since the allowed operation always changes values by ±1, the parity of each element must match for it to be possible to make the arrays equal. Next, we check the sum of both arrays, because the operation preserves the total sum, so the sums must be equal for a solution to exist. If both conditions hold - matching parity for all elements and equal sums—the arrays can be made equal otherwise, it’s impossible.


Output
true


Comment
Article Tags:
Article Tags: