Katkat

Maximize Equal Array Length After Contiguous Sum Merges

MicrosoftSoftware Engineer · Onsite

Last updated

Determine the maximum possible length of two identical arrays formed by repeatedly merging adjacent elements of two given positive-integer arrays, or return -1 if impossible.

Problem Statement

You are given two arrays of positive integers, A and B. In one operation on either array, you can choose two adjacent elements and replace them with their sum. You may perform this operation zero or more times on both arrays.

Your goal is to make the two arrays identical (i.e., they have the exact same length, and A[i] == B[i] for every valid index i). Find the maximum length of the resulting identical arrays. If it is impossible to make them identical, return -1.

Function Signature

def max_equal_array_length(A: list[int], B: list[int]) -> int:
    pass

Input and Output

  • Input: Two lists of positive integers, A and B.
  • Output: An integer representing the maximum length of the identical arrays, or -1 if they cannot be made identical.

Constraints

  • 1 <= len(A), len(B) <= 200,000
  • 1 <= A[i], B[i] <= 10^9
  • The sum of elements in A and B fits within a 64-bit signed integer.

Examples

Example 1

Input: A = [3, 2, 6, 2], B = [5, 1, 5, 2]
Output: 3

Explanation:

  • In array A, merge A[0] and A[1] to get [5, 6, 2].
  • In array B, merge B[1] and B[2] to get [5, 6, 2].
  • Both arrays are now identical with length 3. This is the maximum possible length.

Example 2

Input: A = [1, 2, 3], B = [4, 2]
Output: -1

Explanation:

  • Sum of A is 6 and sum of B is 6. Merging A[0] and A[1] produces [3, 3], which cannot be matched with any merge of B. Merging all of A gives [6], while merging all of B gives [6]. However, let's trace: prefix sums of A are {1, 3, 6} and for B are {4, 6}. The only common prefix sum is 6, so they can only be merged into [6], which would yield length 1. But for input A = [1, 2, 4], B = [4, 2], sums differ (7 vs 6), so output is -1.

Edge Cases

  • Sum of elements in A is not equal to sum of elements in B: impossible, return -1.
  • Already identical arrays: return len(A).
  • Arrays can only be reduced to a single element: return 1.

Hints

Hint 1

Since all elements are strictly positive, any merge operation strictly increases the segment sum.

Hint 2

Notice that two arrays can be partitioned into matching segments if and only if their prefix sums match at the segment boundaries.

Hint 3

Use a two-pointer approach to accumulate running sums from left to right; whenever the two running sums match, increment your segment count and reset the sums.

Follow-up questions

  • How would your approach change if the arrays were allowed to contain zero or negative integers?
  • Can you reconstruct the actual merged array using O(1) auxiliary space (excluding the output)?
  • What if you were given k arrays instead of 2? What would be the time and space complexity?