Skip to content

Commit cdf64c2

Browse files
committed
feat(algorithms, two-pointers): product of array except self
1 parent f52c20c commit cdf64c2

19 files changed

Lines changed: 209 additions & 69 deletions
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
# Product of Array Except Self
2+
3+
Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of
4+
nums except nums[i].
5+
6+
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
7+
8+
You must write an algorithm that runs in O(n) time and without using the division operation.
9+
10+
Example 1:
11+
```plain
12+
Input: nums = [1,2,3,4]
13+
Output: [24,12,8,6]
14+
```
15+
16+
Example 2:
17+
```text
18+
Input: nums = [-1,1,0,-3,3]
19+
Output: [0,0,9,0,0]
20+
```
21+
22+
Example 3:
23+
```text
24+
Input: nums = [2,4,0,6]
25+
Output: [0,0,48,0]
26+
```
27+
28+
Example 4:
29+
```text
30+
Input: nums = [1, -3, 5, 7, -11]
31+
Output: [1155, -385, 231, 165, -105]
32+
```
33+
34+
## Related Topics
35+
36+
- Array
37+
- Prefix Sum
38+
39+
## Solution
40+
41+
The idea is that we can break down the problem into two parts: the product of elements to the left of each index and the
42+
product of elements to the right of each index. By maintaining two separate running products as we traverse the array
43+
from both ends, we can accumulate the product values to populate the res array. This approach eliminates the need for
44+
repeated multiplications and effectively calculates the product except for the element at the current index. The Two
45+
Pointers pattern is employed here to handle both the left and right products in a single traversal.
46+
47+
Here’s how the algorithm works:
48+
49+
- Initialize the following variables that will assist us in performing the algorithm:
50+
- res: This array will be used to store the output. It is initialized to 1
51+
- l, r: These are the pointers used to traverse the array. They are initialized to the left and right ends of the
52+
array, respectively.
53+
- `left_product`: This variable stores the product of the elements to the left of the l pointer.
54+
- `right_product`: This variable stores the product of the elements to the right of the r pointer.
55+
- Traverse the array while the l and r pointers are not out of bounds:
56+
- Calculate the product to the left of nums[l] and store it in res[l] using the following formula:
57+
> res[l] = res[l] * left_product
58+
- Calculate the product to the right of the nums[r] and store it in res[r] using the following formula:
59+
> res[r] = res[r] * right_product
60+
- Update left_product to include the current element, nums[l], in the accumulated product for the next iteration.
61+
- Update right_product to include the current element, nums[r], in the accumulated product for the next iteration.
62+
- Finally, increment the l pointer and decrement the r pointer to evaluate the next elements.
63+
- The steps above are repeated until the l and r pointers go out of bounds.
64+
65+
> - When l == r, both pointers point to the middle element of the array. For this element, both the products to its left
66+
> and right are being computed one after another and stored in res[l] (or res[r] since l == r in this case). Therefore,
67+
> for the case of the middle element, the final product of all the elements, excluding it, is computed in one step.
68+
> - After the l and r pointers cross each other, the following behavior occurs:
69+
> - The l pointer computes the product to the left of nums[l] as expected, but now the product to the right of
70+
> nums[l] has already been computed in a previous iteration by the r pointer. Now both the right and left products
71+
> have been calculated and combined, the resultant product in this entry is the final product of all the elements,
72+
> excluding the current one.
73+
> - The r pointer computes the product to the right of nums[r] as expected, but now the product to the left of nums[r]
74+
> has already been computed in a previous iteration by the l pointer. Now both the right and left products have been
75+
> calculated and combined, the resultant product in this entry is the final product of all the elements, excluding
76+
> the current one.
77+
78+
- Lastly, the res array contains the desired result, so return it.
79+
80+
![Solution 1](./images/solutions/product_of_array_except_self_solution_1.png)
81+
![Solution 2](./images/solutions/product_of_array_except_self_solution_2.png)
82+
![Solution 3](./images/solutions/product_of_array_except_self_solution_3.png)
83+
![Solution 4](./images/solutions/product_of_array_except_self_solution_4.png)
84+
![Solution 5](./images/solutions/product_of_array_except_self_solution_5.png)
85+
![Solution 6](./images/solutions/product_of_array_except_self_solution_6.png)
86+
![Solution 7](./images/solutions/product_of_array_except_self_solution_7.png)
87+
![Solution 8](./images/solutions/product_of_array_except_self_solution_8.png)
88+
![Solution 9](./images/solutions/product_of_array_except_self_solution_9.png)
89+
![Solution 10](./images/solutions/product_of_array_except_self_solution_10.png)
90+
![Solution 11](./images/solutions/product_of_array_except_self_solution_11.png)
91+
![Solution 12](./images/solutions/product_of_array_except_self_solution_12.png)
92+
![Solution 13](./images/solutions/product_of_array_except_self_solution_13.png)
93+
94+
### Solution Summary
95+
96+
The solution can be summarized in the following steps:
97+
98+
- Create a list with the same length as the input list, initialized with 1s.
99+
- Keep track of products on the left and right sides of the current element.
100+
- Use two pointers—one starting from the beginning and the other from the end of the list.
101+
- Multiply and update values in the output array based on accumulated products and current element values.
102+
- Move the pointers toward each other to process the entire list.
103+
-
104+
105+
### Time Complexity
106+
107+
The time complexity of this solution is O(n), since both the pointers simultaneously traverse the length of the array
108+
once.
109+
110+
### Space Complexity
111+
112+
The space complexity of this solution is O(1), since it doesn’t use any additional array for computations but only
113+
constant additional space.
114+
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
from typing import List
2+
3+
4+
def product_except_self_prefix_sums(nums: List[int]) -> List[int]:
5+
if len(nums) <= 1:
6+
return nums
7+
8+
result = [1] * len(nums)
9+
prefix = 1
10+
11+
for i in range(len(nums)):
12+
result[i] = prefix
13+
prefix *= nums[i]
14+
15+
postfix = 1
16+
for i in range(len(nums) - 1, -1, -1):
17+
result[i] *= postfix
18+
postfix *= nums[i]
19+
20+
return result
21+
22+
23+
def product_except_self_two_pointers(nums):
24+
# Get the length of the input list
25+
n = len(nums)
26+
27+
# Initialize a result list with 1's for products
28+
res = [1] * n
29+
30+
# Initialize variables for left and right products
31+
left_product, right_product = 1, 1
32+
33+
# Initialize pointers for the left and right ends of the list
34+
l = 0
35+
r = n - 1
36+
37+
# Iterate through the list while moving the pointers towards each other
38+
while l < n and r > -1:
39+
# Update the result at the left index with the accumulated left product
40+
res[l] *= left_product
41+
42+
# Update the result at the right index with the accumulated right product
43+
res[r] *= right_product
44+
45+
# Update the left product with the current element's value
46+
left_product *= nums[l]
47+
48+
# Update the right product with the current element's value
49+
right_product *= nums[r]
50+
51+
# Move the left pointer to the right
52+
l += 1
53+
54+
# Move the right pointer to the left
55+
r -= 1
56+
57+
# Return the final product result list
58+
return res
15.7 KB
Loading
88.5 KB
Loading
100 KB
Loading
89.3 KB
Loading
52.4 KB
Loading
82.1 KB
Loading
82.1 KB
Loading
84.5 KB
Loading

0 commit comments

Comments
 (0)