Product of array except self#
Practice Link#
Description#
- Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Note:
- Please solve it without division and in O(n).
Python Solution#
1class Solution(object):
2 def productExceptSelf(self, nums):
3 """
4 :type nums: List[int]
5 :rtype: List[int]
6 """
7 out = [1 for idx in range(len(nums))]
8 for idx, _ in enumerate(nums):
9 outp = 1
10 for jdx, n in enumerate(nums):
11 if idx != jdx:
12 outp *= n
13 out[idx] = outp
14 return out
15
16
17class Solution2(object):
18 def productExceptSelf(self, nums):
19
20 # The length of the input array
21 length = len(nums)
22
23 # The left and right arrays as described in the algorithm
24 L, R, answer = [0] * length, [0] * length, [0] * length
25
26 # L[i] contains the product of all the elements to the left
27 # Note: for the element at index '0', there are no elements to the left,
28 # so the L[0] would be 1
29 L[0] = 1
30 for i in range(1, length):
31
32 # L[i - 1] already contains the product of elements to the left of 'i - 1'
33 # Simply multiplying it with nums[i - 1] would give the product of all
34 # elements to the left of index 'i'
35 L[i] = nums[i - 1] * L[i - 1]
36
37 # R[i] contains the product of all the elements to the right
38 # Note: for the element at index 'length - 1', there are no elements to the right,
39 # so the R[length - 1] would be 1
40 R[length - 1] = 1
41 for i in reversed(range(length - 1)):
42
43 # R[i + 1] already contains the product of elements to the right of 'i + 1'
44 # Simply multiplying it with nums[i + 1] would give the product of all
45 # elements to the right of index 'i'
46 R[i] = nums[i + 1] * R[i + 1]
47
48 # Constructing the answer array
49 for i in range(length):
50 # For the first element, R[i] would be product except self
51 # For the last element of the array, product except self would be L[i]
52 # Else, multiple product of all elements to the left and to the right
53 answer[i] = L[i] * R[i]
54
55 return answer
56
57
58in_arrs = [
59 [2, 1, 2, 1, 0, 1, 2],
60 [3, 3, 5, 0, 0, 3, 1, 4],
61 [3, 5, 0, 1, 4],
62 [1, 2, 3, 1],
63 [1, 2, 3, 4],
64 [1, 1, 1, 3, 3, 4, 3, 2, 4, 2],
65]
66if __name__ == "__main__":
67
68 sol = Solution2()
69 for nin in in_arrs:
70 r = sol.productExceptSelf(nin)
71 print(r)