Medium
Product of Array Except Self
- Time limit
- 2 s
- Memory limit
- 256 MB
- Estimated
- 20 min
- Prefix Sums and Difference Arrays
Description
Description
Given an integer array nums, return an array answer where answer[i] is the product of every element of nums except nums[i]. Division is not required to solve this; use prefix and suffix products instead.
Examples
Example 1
- Input:
nums = [1, 2, 3, 4] - Output:
[24, 12, 8, 6]
Example 2
- Input:
nums = [-1, 1, 0, -3, 3] - Output:
[0, 0, 9, 0, 0]
Example 3
- Input:
nums = [2, 2] - Output:
[2, 2]
Expected Function Behavior
Implement productExceptSelf(nums) and return the resulting array.
Constraints
2 <= nums.length <= 1000-20 <= nums[i] <= 20- The product of all elements of
nums, and of every prefix and suffix ofnums, is guaranteed to fit in a signed 64-bit integer.
Sample cases
3Sample 1
Input
nums = [1,2,3,4]
Expected output
[24,12,8,6]
Sample 2
Input
nums = [-1,1,0,-3,3]
Expected output
[0,0,9,0,0]
Skills and languages
Patterns
- Prefix and Suffix Precomputation
- Two-Pass Greedy
Languages
- Python 3
Solve this problem
Create a free account to write, run and submit your solution.
- Write Python or Java in the browser, with your draft saved as you type
- Run your code on the examples as often as you like
- Submit to a sandboxed judge and see exactly which case failed
- Ask the AI mentor for a hint without being handed the answer