Skip to content

Comments

Working Solution#1965

Open
avcode3 wants to merge 1 commit intosuper30admin:masterfrom
avcode3:master
Open

Working Solution#1965
avcode3 wants to merge 1 commit intosuper30admin:masterfrom
avcode3:master

Conversation

@avcode3
Copy link

@avcode3 avcode3 commented Feb 22, 2026

No description provided.

@super30admin
Copy link
Owner

Your solution for "Product Except Self" has a good intention of using two passes to achieve O(n) time and O(1) space, but the implementation is incorrect. Let me explain the standard approach:

The common solution for this problem involves:

  1. Creating an output array.
  2. First pass: For each element, compute the product of all elements to the left and store it in the output array.
  3. Second pass: For each element, compute the product of all elements to the right and multiply it with the existing value in the output array (which is the left product).

Here's a corrected version of your code:

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        n = len(nums)
        result = [1] * n
        
        # First pass: compute left products
        left_product = 1
        for i in range(n):
            result[i] = left_product
            left_product *= nums[i]
        
        # Second pass: compute right products and multiply with left products
        right_product = 1
        for i in range(n-1, -1, -1):
            result[i] *= right_product
            right_product *= nums[i]
        
        return result

In your code, you used variables rp and temp in a way that doesn't accumulate the product correctly. For example, in the first pass, you set final_arr[i] = rp and then update temp = nums[i], but then in the next iteration, you multiply temp and rp which doesn't correctly build the left product.

I notice you also provided solutions for two other problems. While that shows your enthusiasm, please focus on one problem at a time. For the "Product Except Self" problem, I recommend testing your code with the provided examples to see the incorrect output.

Keep practicing! You have the right idea of using running products, but the implementation needs refinement.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants