Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Equal Arrays

Moderate
0/80
Average time to solve is 20m
profile
Contributed by
10 upvotes
Asked in company
Prodapt Solutions

Problem statement

You are given two arrays 'A' and 'B' of length 'N' and 'M' respectively. You can perform the following operation any number of times on 'A' and 'B'.

1. Replace any subarray of the array with the sum of the elements in the subarray. For example :- If we have an array 'A' = [2, 3, 5, 6, 1], then we can replace the subarray from index 1 to index 3 (0-based indexing) i.e. [3, 5, 6] with its sum i.e. 3 + 5 + 6 = 14 to get 'A' =  [2, 14, 1].

You want to make 'A' and 'B' equal. Return the maximum possible length of arrays 'A' and 'B' such that 'A' is equal to 'B'. If it is impossible to make 'A' and 'B' equal then return -1.

A subarray is a contiguous part of the array.

For Example:-
Let 'N' = 4, 'M' = 5, 'A' = [2, 1, 4, 3], 'B' = [2, 5, 1, 1, 1].
 We can perform operations on 'A' from index 2 to 3 and on 'B' from index 3 to 5 (1-based indexing).
'A' and 'B' after performing the operation is [2, 5, 3].
The maximum possible length is 3.
Detailed explanation ( Input/output format, Notes, Images )
Constraints:-
1 <= 'T' <= 10
1 <= 'N','M' <= 10^5
1 <= 'A[i]', 'B[i]' <= 10^5

The Sum of 'N' overall test cases does not exceed 10^5.
Time Limit: 1 sec
Sample Input 1:-
2
3 4
3 2 2
1 3 1 3
5 3
1 3 2 2 3
4 2 5
Sample Output 1:-
-1
3
Explanation of sample input 1:-
First test case:-
It can be proven that we cannot make 'A' and 'B' equal.
So our answer is -1.

Second test case:-
We can perform operations on 'A' from index 1 to 2 and from index 4 to 5 (1-based indexing).
'A' and 'B' after performing the operation is [4, 2, 5].
The maximum possible length is 3.
Sample Input 2:-
2
5 2
3 2 5 1 6
4 7 
4 4
4 3 2 1
1 2 3 4
Sample Output 2:-
 -1
 1
Full screen
Console