Intuition
The key insight is to use a two-pass approach with prefix and postfix products to avoid division and achieve O(n) time complexity.
- Prefix Pass: For each position i, store the product of all elements to the left of i.
- Postfix Pass: For each position i, multiply the prefix product by the product of all elements to the right of i.
- Result: result[i] = (product of elements before i) × (product of elements after i)
- No Division: We cleverly avoid division by constructing the answer through multiplication only.
- Space Efficient: Use the result array itself to store intermediate values.
Step-by-Step Code
Live Visualization
Input Array:
Result Array: Prefix Pass
Current Calculation:
Ready to start...
Algorithm States
Status: Ready
Current Phase: Initialization
Current Index (i): N/A
Prefix Value: 1
Postfix Value: 1