Skip to content

Commit 58beb64

Browse files
authored
Merge pull request #1634 from ivanpenaloza/may11
adding updates
2 parents f9b799e + 5c58799 commit 58beb64

3 files changed

Lines changed: 73 additions & 0 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
4+
class Solution:
5+
def productExceptSelf(self, nums: List[int]) -> List[int]:
6+
"""
7+
Calculate product of all elements except self without division.
8+
9+
Strategy: Two-pass with prefix and suffix products
10+
- First pass: Build prefix products (product of all elements to the left)
11+
- Second pass: Build suffix products (product of all elements to the right)
12+
- Result[i] = prefix[i] * suffix[i]
13+
14+
Optimization: Use output array to store prefix, then multiply by suffix in-place
15+
16+
Time: O(n), Space: O(1) excluding output array
17+
"""
18+
19+
n = len(nums)
20+
answer = [1] * n
21+
22+
# First pass: Calculate prefix products
23+
# answer[i] contains product of all elements to the left of i
24+
prefix = 1
25+
for i in range(n):
26+
answer[i] = prefix
27+
prefix *= nums[i]
28+
29+
# Second pass: Calculate suffix products and multiply with prefix
30+
# For each position, multiply existing prefix with product of all elements to the right
31+
suffix = 1
32+
for i in range(n - 1, -1, -1):
33+
answer[i] *= suffix
34+
suffix *= nums[i]
35+
36+
return answer
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
function productExceptSelf(nums: number[]): number[] {
2+
const n = nums.length;
3+
const answer: number[] = new Array(n).fill(1);
4+
5+
// First pass: prefix products
6+
let prefix = 1;
7+
for (let i = 0; i < n; i++) {
8+
answer[i] = prefix;
9+
prefix *= nums[i];
10+
}
11+
12+
// Second pass: suffix products multiplied in-place
13+
let suffix = 1;
14+
for (let i = n - 1; i >= 0; i--) {
15+
answer[i] *= suffix;
16+
suffix *= nums[i];
17+
}
18+
19+
return answer;
20+
};
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import unittest
2+
from src.my_project.interviews.top_150_questions_round_23\
3+
.ex_13_product_of_array_except_itself import Solution
4+
5+
class ProductExcetItselfTestCase(unittest.TestCase):
6+
7+
def test_product_first_case(self):
8+
solution = Solution()
9+
output = solution.productExceptSelf(nums = [1,2,3,4])
10+
target = [24,12,8,6]
11+
self.assertEqual(output, target)
12+
13+
def test_product_second_case(self):
14+
solution = Solution()
15+
output = solution.productExceptSelf(nums = [-1,1,0,-3,3])
16+
target = [0,0,9,0,0]
17+
self.assertEqual(output, target)

0 commit comments

Comments
 (0)