Find sub-arrays from given two arrays such that they have equal sum in Python

When working with two arrays, you may need to find sub-arrays that have equal sums. This problem involves finding contiguous elements from each array where the sum of elements in one sub-array equals the sum in another sub-array.

Given two arrays P and Q of size N containing numbers 1 to N, we need to find sub-arrays with equal sums and return their indices. If no solution exists, return -1.

Example

For arrays P = [2, 3, 4, 5, 6] and Q = [9, 3, 2, 6, 5], the solution is:

  • P[0..2] = 2 + 3 + 4 = 9
  • Q[0] = 9

Algorithm Approach

The solution uses cumulative sums and a hash map to efficiently find equal-sum sub-arrays ?

  1. Convert both arrays to cumulative sum arrays
  2. Use a hash map to store differences between cumulative sums
  3. When the same difference appears again, we found equal-sum sub-arrays

Implementation

def show_result(start, end, array_num):
    print(f"Indices of array {array_num} :", end=" ")
    for i in range(start, end):
        print(i, end=", ")
    print(end)

def get_subarray(P, Q, swap):
    N = len(P)
    index = {}
    difference, j = 0, 0
    index[0] = (-1, -1)
    
    for i in range(0, N):
        while j < N and Q[j] < P[i]:
            j += 1
        
        if j < N:
            difference = Q[j] - P[i]
            
            if difference in index:
                if swap:
                    idx = index[difference]
                    show_result(idx[1] + 1, j, 1)
                    show_result(idx[0] + 1, i, 2)
                else:
                    idx = index[difference]
                    show_result(idx[0] + 1, i, 1)
                    show_result(idx[1] + 1, j, 2)
                return
            
            index[difference] = (i, j)
    
    print(-1)

def cumulative_sum(arr):
    """Convert array to cumulative sum array"""
    n = len(arr)
    for i in range(1, n):
        arr[i] += arr[i - 1]

def find_equal_sum_subarrays(P, Q):
    """Find sub-arrays with equal sums from two arrays"""
    # Create copies to avoid modifying original arrays
    P_copy = P.copy()
    Q_copy = Q.copy()
    
    # Convert to cumulative sums
    cumulative_sum(P_copy)
    cumulative_sum(Q_copy)
    
    N = len(P_copy)
    
    # Choose which array to process first based on final sum
    if Q_copy[N - 1] > P_copy[N - 1]:
        get_subarray(P_copy, Q_copy, False)
    else:
        get_subarray(Q_copy, P_copy, True)

# Example usage
P = [2, 3, 4, 5, 6]
Q = [9, 3, 2, 6, 5]

print("Original arrays:")
print(f"P = {P}")
print(f"Q = {Q}")
print("\nFinding equal-sum sub-arrays:")

find_equal_sum_subarrays(P, Q)
Original arrays:
P = [2, 3, 4, 5, 6]
Q = [9, 3, 2, 6, 5]

Finding equal-sum sub-arrays:
Indices of array 1 : 0, 1, 2
Indices of array 2 : 0

How It Works

The algorithm works by:

  1. Cumulative Sums: Transform arrays to [2,5,9,14,20] and [9,12,14,20,25]
  2. Difference Tracking: Store differences between cumulative sums in a hash map
  3. Pattern Recognition: When the same difference reappears, it indicates equal-sum sub-arrays

Time and Space Complexity

Aspect Complexity Explanation
Time O(N) Single pass through arrays
Space O(N) Hash map for storing differences

Conclusion

This algorithm efficiently finds equal-sum sub-arrays using cumulative sums and hash maps. The approach transforms the problem into finding repeated differences between cumulative sums, making it solvable in linear time.

---
Updated on: 2026-03-25T09:24:25+05:30

433 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements