MEDIUM NC#6 Blind #4 Arrays & Hashing
238. Product of Array Except Self
๐ Problem
Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division operation.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
๐ก Approach
- โ Compute prefix products from left to right
- โ Compute suffix products from right to left
- โ Result[i] = prefix[i] * suffix[i]
- โ Can do in two passes without extra space for prefix/suffix arrays
- โ Time: O(n), Space: O(1) excluding result array
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขCompute prefix products from left to right
- โขCompute suffix products from right to left
- โขResult[i] = prefix[i] * suffix[i]
Common Pitfalls
- โขCan do in two passes without extra space for prefix/suffix arrays
- โขTime: O(n), Space: O(1) excluding result array
๐งช Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
productExceptSelf([1,2,3,4]); Expected:
[24, 12, 8, 6] Test Case 2
Not run Input:
productExceptSelf([-1,1,0,-3,3]); Expected:
[0, 0, 9, 0, 0] Test Case 3
Not run Input:
productExceptSelf([1,0]); Expected:
[0, 1] ๐ Code Editor
๐ค Output