Algorithm-Day16-Product-of-Array-Except-Self-lc#238
π§© Problem Description
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 algorithm must run in O(n) time and without using division.
Example:
1 | Input: nums = [1,2,3,4] |
π‘ Brute Force (Not Acceptable)
For each index, multiply all other elements:
- Time: O(nΒ²)
- β Not efficient for large inputs
π‘ Optimal Approach: Prefix Product + Suffix Product
β¨ Key Idea
We calculate:
prefix[i]
: product of all elements before indexi
suffix[i]
: product of all elements after indexi
Then:answer[i] = prefix[i] * suffix[i]
But we can optimize to use only one output array.
π’ Java Code
1 | class Solution { |
β± Time and Space Complexity
- Time Complexity: O(n)
Two passes over the array. - Space Complexity: O(1) extra space (output array does not count as extra space in the problem statement)
βοΈ Summary
- This is a classic prefix + suffix product pattern.
- No division is used.
- Space-optimized by combining both steps into a single result array.
Learning this approach helps with problems involving βall elements exceptβ¦β patterns, such as sum, XOR, or custom aggregates.