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
2
Input: nums = [1,2,3,4]
Output: [24,12,8,6]

πŸ’‘ 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 index i
  • suffix[i]: product of all elements after index i

Then:
answer[i] = prefix[i] * suffix[i]

But we can optimize to use only one output array.


πŸ”’ Java Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] answer = new int[n];

// Step 1: Left products
answer[0] = 1;
for (int i = 1; i < n; i++) {
answer[i] = answer[i - 1] * nums[i - 1];
}

// Step 2: Right products (suffix) and multiply on the fly
int right = 1;
for (int i = n - 1; i >= 0; i--) {
answer[i] = answer[i] * right;
right *= nums[i];
}

return answer;
}
}

⏱ 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.