|
| 1 | +""" |
| 2 | +!! question 2 |
| 3 | +Given an array of integers, return a new array such that each element at index |
| 4 | + i of the new array is the product of all the numbers in the original array |
| 5 | + except the one at i. |
| 6 | +
|
| 7 | +For example, if our input was [1, 2, 3, 4, 5], |
| 8 | +the expected output would be [120, 60, 40, 30, 24]. |
| 9 | +If our input was [3, 2, 1], the expected output would be [2, 3, 6]. |
| 10 | +
|
| 11 | +Follow-up: what if you can't use division? |
| 12 | +------------------- |
| 13 | +
|
| 14 | +## brainstorming |
| 15 | +1. brute-force: for every number, calculate the product of all the |
| 16 | + other number. |
| 17 | + time O(n^2), space O(1) |
| 18 | +2. in the brute force, we do many duplcated calculation: |
| 19 | + the product of the same numbers. |
| 20 | + if we can prevent the duplicated calculation we can optimize it. |
| 21 | + We can first calculate the product of all the numbers in the array. |
| 22 | + for every element, we only need to use the current nuber to divide |
| 23 | + the total product and get the result we need. |
| 24 | + time O(n), space O(1) |
| 25 | +3. what if we can't use division? |
| 26 | + brute-force approach doesn't use division, but can we optimize it? |
| 27 | +
|
| 28 | + formula for #2 is totalProduct/currentNumber |
| 29 | + new formula: product of numbers in its left * product of numbers |
| 30 | + in its right |
| 31 | + prefix and suffix products |
| 32 | + so we need two arrays, the first is the product of left numbers |
| 33 | + and the second is the product of right numbers. |
| 34 | + left_prod[i] = arr[0]*arr[1]..*arr[i-1] |
| 35 | + right_prod[i] = arr[i+1]* arr[i+2]...arr[n-1] |
| 36 | + output[i] = left_prod[i] * right_prod[i] |
| 37 | +
|
| 38 | + !! optimze space - in-place calculation |
| 39 | + do the calculation directly in the result |
| 40 | + result[0] = 1 |
| 41 | + i from 1 to n-1: |
| 42 | + result[i] = result[i-1] * nums[i-1] |
| 43 | + prod = 1 |
| 44 | + i form n-2 to 0: |
| 45 | + prod *= nums[i+1] |
| 46 | + result[i] *= prod |
| 47 | +
|
| 48 | + time O(n), space O(n) |
| 49 | +
|
| 50 | + edge case: if there is a zero in the input array, the approach without |
| 51 | + division works correctly without specific handling this case. |
| 52 | +""" |
| 53 | + |
| 54 | + |
| 55 | +def test_2(): |
| 56 | + pass |
0 commit comments