Product of Array Except Self
LeetCode 238 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
answer[i] = prefix_product[i] × suffix_product[i].
আমি Product of Array Except Self (LeetCode 238) এভাবে সমাধান করেছি — Prefix Sum প্যাটার্নের একটি মাঝারি প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।
নিচের বিবরণ ইংরেজিতে।
Intuition
The answer at i is (product of everything left of i) × (product of everything right of i). Build the left products in one pass and the right products in a second pass — no division needed, so zeros are handled naturally.
Approach
- 1
First pass left→right: arr[i] = product of nums[0..i-1].
- 2
Second pass right→left with a running product of nums[i+1..].
- 3
Multiply the running right product into arr[i].
- 4
The final version reuses the output array, so extra space is O(1).
আমি কীভাবে সমাধান করেছি · প্রথম ভাবনা থেকে চূড়ান্ত সমাধান
Two helper arrays, multiplied at the end.
Fold the suffix product into the output.
Prefix and suffix arraysPythonO(n) time · O(n) space
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
"""
prefix arr - 1,1,2,6
suffix arr - 24,12,4,1
"""
n = len(nums)
prefix_arr = [1]*n
suffix_arr = [1]*n
left = 1
for i in range(1,n):
left = left*nums[i-1]
prefix_arr[i]=left
right = 1
for i in range(n-2,-1,-1):
right = right*nums[i+1]
suffix_arr[i]=right
for i in range(n):
prefix_arr[i]=prefix_arr[i]*suffix_arr[i]
return prefix_arrIn-place suffix passPythonO(n) time · O(1) extra
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
"""
prefix arr - 1,1,2,6
suffix arr - 24,12,4,1
"""
n = len(nums)
arr = [1]*n
left = 1
for i in range(1,n):
left = left*nums[i-1]
arr[i]=left
right = 1
for i in range(n-2,-1,-1):
right = right*nums[i+1]
arr[i]=arr[i]*right
return arrProduct of Array Except Self — সাধারণ প্রশ্ন
Product of Array Except Self-এর পেছনে intuition কী?
The answer at i is (product of everything left of i) × (product of everything right of i). Build the left products in one pass and the right products in a second pass — no division needed, so zeros are handled naturally.
Product of Array Except Self (LeetCode 238) কীভাবে সমাধান করবেন?
1. First pass left→right: arr[i] = product of nums[0..i-1]. 2. Second pass right→left with a running product of nums[i+1..]. 3. Multiply the running right product into arr[i]. 4. The final version reuses the output array, so extra space is O(1).
Product of Array Except Self-এর time আর space complexity কত?
Time: O(n)। Space: O(1) extra (output excluded)। (Accepted approach: In-place suffix pass।)
Product of Array Except Self-এ সাধারণ ভুলগুলো কী?
Dividing the total product breaks on zeros.
Product of Array Except Self সমাধানের কি একাধিক উপায় আছে?
Prefix and suffix arrays (O(n) time · O(n) space): Two helper arrays, multiplied at the end. In-place suffix pass (O(n) time · O(1) extra): Fold the suffix product into the output.