Suppose we have a list of numbers called nums, we have to find a new list such that each element at index i of the newly generated list is the product of all the numbers in the original list except the one at index i. Here we have to solve it without using division.
So, if the input is like nums = [2, 3, 4, 5, 6], then the output will be [360, 240, 180, 144, 120]
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution: def solve(self, nums): if len(nums) < 1: return nums l = len(nums) left = [None] * l right = [None] * l temp = 1 for i in range(len(nums)): if i == 0: left[i] = temp else: temp = temp * nums[i - 1] left[i] = temp temp = 1 for i in range(len(nums) - 1, -1, -1): if i == len(nums) - 1: right[i] = temp else: temp = temp * nums[i + 1] right[i] = temp for i in range(len(nums)): left[i] = left[i] * right[i] return left ob = Solution() nums = [2, 3, 4, 5, 6] print(ob.solve(nums))
[2, 3, 4, 5, 6]
[360, 240, 180, 144, 120]