Suppose we have an array of size N; we have to find an element which divides the array into two different sub-arrays with equal product. Return -1 if no such partition is possible.
So, if the input is like [2,5,3,2,5], then the output will be 3 then subarrays are: {2, 5} and {2, 5}
To solve this, we will follow these steps −
- n := size of array
- multiply_pref := a new list
- insert array[0] at the end of multiply_pref
- for i in range 1 to n, do
- insert multiply_pref[i-1]*array[i] at the end of multiply_pref
- multiply_suff := a list of size n, and fill with none
- multiply_suff[n-1] := array[n-1]
- for i in range n-2 to -1, decrease by 1, do
- multiply_suff[i] := multiply_suff[i+1]*array[i]
- for i in range 1 to n-1, do
- if multiply_pref[i] is same as multiply_suff[i], then
- return array[i]
- if multiply_pref[i] is same as multiply_suff[i], then
- return -1
Example Code
Let us see the following implementation to get better understanding −
def search_elem(array): n = len(array) multiply_pref = [] multiply_pref.append(array[0]) for i in range(1, n): multiply_pref.append(multiply_pref[i-1]*array[i]) multiply_suff = [None for i in range(0, n)] multiply_suff[n-1] = array[n-1] for i in range(n-2, -1, -1): multiply_suff[i] = multiply_suff[i+1]*array[i] for i in range(1, n-1): if multiply_pref[i] == multiply_suff[i]: return array[i] return -1 array = [2,5,3,2,5] print(search_elem(array))
Input
[2,5,3,2,5]
Output
3