Python: Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.

This post is one of my new series solving one problem per day.

For those of you solving coding challenges for your next software engineering job, here is one more problem.

This problem was asked by Uber.

Problem Statement

Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.

For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].

Here is a solution I came up with

def product_ar(arr):
	new_arr = []
	for i in range(0,len(arr)):
		new_arr.append(multiply_all(arr[0:i], arr[i+1:len(arr)]) )	
	
	return new_arr

def multiply_all(arr1, arr2):
	product = 1
	for item in arr1:
		product *= item		
	for item in arr2:
		product *= item	

	return product

# Some tests 

print(product_ar([1, 2, 3, 4, 5]) == [120, 60, 40, 30, 24])
print(product_ar([3,2,1]) == [2,3,6])

Follow-up: what if you can’t use division?

Leave a Reply

Your email address will not be published. Required fields are marked *