Array / String· 25 min
Product of Array Except Self
LeetCode #238 · Medium · Interactive step-by-step visualization
Setup
Example input
nums = [1, 2, 3, 4]Step 1 / 18
Current step
1 / 18Start a prefix pass. The answer at each index first receives the product strictly to its left. Prefix starts at 1.
Step log
nums
Cursor
1
02
13
24
3answer
1
01
11
21
3prefix
1
Active cursor
Comparing
Best or completed
Leaving or removed
product-of-array-except-self.java
1public int[] productExceptSelf(int[] nums) {2 int[] answer = new int[nums.length];3 int prefix = 1;4 for (int i = 0; i < nums.length; i++) {5 answer[i] = prefix;6 prefix *= nums[i];7 }8 int suffix = 1;9 for (int i = nums.length - 1; i >= 0; i--) {10 answer[i] *= suffix;11 suffix *= nums[i];12 }13 return answer;14}● Java
Time
O(n)
Space
O(1) extra
Pattern
array scan
Frames
18
