KatInterview

Maximum Length of Identical Merged Arrays

Arrays & HashingAuto-graded · 23 test cases
EasyAuto-gradedArrays & Hashingarrayshash-tabletwo-pointers

Last updated

Find the maximum size of two matching arrays derived by repeatedly combining adjacent elements from two positive integer sequences, or return -1 if impossible.

You are given two sequences of positive integers, a and b. You can modify an array by selecting any two neighboring elements and replacing them with their sum. This merge step can be applied any number of times to either or both arrays.

Determine the maximum possible length of the resulting arrays such that array a and array b become identical (meaning both arrays have equal length and matching values at every corresponding position).

If it is impossible to transform a and b into identical sequences, return -1.

Constraints

  • $1 \le \text{len}(a), \text{len}(b) \le 200{,}000$
  • $1 \le a[i], b[i] \le 10^9$
  • The total sum of elements in each list fits within a standard 64-bit signed integer.

Examples

Example 1

Input: max_equal_array_length([3, 2, 6, 2], [5, 1, 5, 2])

Output: 3

Example 2

Input: max_equal_array_length([1, 2, 3], [4, 2])

Output: 1

Example 3

Input: max_equal_array_length([1, 2, 4], [4, 2])

Output: -1

Hints

Hint 1

Consider what property is preserved when adjacent elements in an array are merged into a single value.

Hint 2

Because all elements are strictly positive, cumulative running sums (prefix sums) strictly increase.

Hint 3

What is the relationship between shared prefix sums of the two arrays and valid common segment boundaries?