given an array of integers(positive or negative), and two integers x, y. write a function that can find a subarray whose sum equals to x and product equals to y
Anonymous
Subarray suggests a consecutive array within the original array. Let's say this is the case. Say you are given array A of length N. Create two more arrays: 1. B, whose n-th number is the sum of the first n numbers in A. 2. C, whose n-th number is the product of the first n numbers in A. Say we are given subarray indices i i in these collisions. We can find them in linear time by using a hashmap. Store the contents of B2 into a hashmap and iterate over B checking for collisions. Do the same thing with C and C2. The collisions will return pairs of indices (i, j). What do these mean? Collisions in B and B2 will produce sub-arrays that sum to x. Collisions in C and C2 will produce sub-arrays that multiply to y. All we do now is check for collisions between these. We can again use a hashmap. All of the steps are linear so the algorithm is linear.
Check out your Company Bowl for anonymous work chats.