Coding Problem 4

           Product of elements of Array
                                                          asked by Uber

Ques. Given an array of integers, return a new array such that each element at index i of new array is the product of all the numbers in the original array except that one at i.
For example, if our input was [1, 2, 3, 4, 5] then the expected output would be [120, 60, 40, 30, 24]. If input is [3, 2, 1] then the expected output would be [2, 3, 6].

Solution.
We need to multiply all the elements of array except the one on the index at which we are currently. At index one we will multiply all the elements except the one at index 1. There can be many ways to solve this and different complexities. We can traverse the array two times using nested for loops. Lets see how-

inp = [1, 2, 3, 4, 5]        # input list
out = []                     # output list
for i in range(0, len(inp)):
product = 1
for j in range(0, len(inp)):
if j == i:
continue
product*=inp[j]
out.append(product)
print(out)  

Output: [120, 60, 40, 30, 24]

But the complexity is O(n^2) which is high. 
Well we have another efficient solution. We can take the product of all elements and then at the time of output we just divide the product with the element at current index and we can get desired result. Lets see this solution-

inp = [1, 2, 3, 4, 5]
out = []
product = 1

# taking product of all elements of input
for i in inp:
product*=i

# traverse the list and divide the product with current element.
for i in inp:
temp = product//i
out.append(temp)
print(out)      

Output: [120, 60, 40, 30, 24]

Now in this case we have two for loops which makes complexity of O(2n) which is equal to O(n).
If there is more efficient solution then let me know.

Comments

Popular posts from this blog

Coding Problem 10

Coding Problem 3

Coding Problem 9