|
| 1 | +""" |
| 2 | +238. Product of Array Except Self |
| 3 | +https://leetcode.com/problems/product-of-array-except-self/description/ |
| 4 | +
|
| 5 | +Solution: |
| 6 | + - Create two lists to store the product of elements from the left and right |
| 7 | + - Multiply the elements from the left and right lists to get the output |
| 8 | +
|
| 9 | + Example: |
| 10 | + nums = [4, 2, 3, 1, 7, 0, 9, 10] |
| 11 | +
|
| 12 | + left is numbers to the left of the current index |
| 13 | + right is numbers to the right of the current index |
| 14 | + from_left is the product of the numbers to the left of the current index |
| 15 | + from_right is the product of the numbers to the right of the current index |
| 16 | +
|
| 17 | + i = 0: (4) 2 3 1 7 0 9 10 |
| 18 | + i = 1: 4 (2) 3 1 7 0 9 10 |
| 19 | + i = 2: 4 2 (3) 1 7 0 9 10 |
| 20 | + i = 3: 4 2 3 (1) 7 0 9 10 |
| 21 | + i = 4: 4 2 3 1 (7) 0 9 10 |
| 22 | + i = 5: 4 2 3 1 7 (0) 9 10 |
| 23 | + i = 6: 4 2 3 1 7 0 (9) 10 |
| 24 | + i = 7: 4 2 3 1 7 0 9 (10) |
| 25 | +
|
| 26 | + from_left = [0, 4, 8, 24, 24, 168, 0, 0] |
| 27 | + from_right = [0, 0, 0, 0, 0, 90, 10, 0] |
| 28 | + output = [0, 0, 0, 0, 0, 15120, 0, 0] |
| 29 | +
|
| 30 | +Time complexity: O(n) |
| 31 | + - Calculating the product of the elements from the left: O(n) |
| 32 | + - Calculating the product of the elements from the right: O(n) |
| 33 | + - Calculating the output: O(n) |
| 34 | + - Total: O(n) |
| 35 | +
|
| 36 | +Space complexity: O(n) |
| 37 | + - Storing the product of the elements from the left: O(n) |
| 38 | + - Storing the product of the elements from the right: O(n) |
| 39 | + - Storing the output: O(n) |
| 40 | +""" |
| 41 | +from typing import List |
| 42 | + |
| 43 | + |
| 44 | +class Solution: |
| 45 | + def productExceptSelf(self, nums: List[int]) -> List[int]: |
| 46 | + output = [0] * len(nums) |
| 47 | + |
| 48 | + from_left = [0] * (len(nums)) |
| 49 | + from_right = [0] * (len(nums)) |
| 50 | + |
| 51 | + from_left[0] = nums[0] |
| 52 | + from_right[-1] = nums[-1] |
| 53 | + |
| 54 | + for i in range(1, len(nums) - 1): |
| 55 | + from_left[i] = from_left[i - 1] * nums[i] |
| 56 | + |
| 57 | + for i in reversed(range(1, len(nums) - 1)): |
| 58 | + from_right[i] = from_right[i + 1] * nums[i] |
| 59 | + |
| 60 | + output[0] = from_right[1] |
| 61 | + output[-1] = from_left[-2] |
| 62 | + for i in range(1, len(nums) - 1): |
| 63 | + output[i] = from_left[i - 1] * from_right[i + 1] |
| 64 | + |
| 65 | + return output |
0 commit comments