Product of Array Except Self - LeetCode Java Solution
Tags: java, datastructures, algorithms, leetcode
Published: 2023-08-11 10:48:03

Hello readers, let’s solve a LeetCode problem today.

In this blog, let’s solve the problem [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) which is one of the [Blind 75 List of LeetCode Problems](https://leetcode.com/discuss/interview-question/460599/Blind-75-LeetCode-Questions).

This is a LeetCode Medium problem with multiple potential solutions, which we will go through in this blog.

### **Understand the Problem**

The Objective of the problem is to calculate the product of all elements in an input array, except for the element at each index. The problem also mentions writing an algorithm that runs in `O(n)` time and without using the division operation.

### Understand the Testcases

To test the solution, we can consider the following cases:

1. Input: `[1, 2, 3, 4]`
Output: `[24, 12, 8, 6]`
Explanation: The product of all elements except the one at index 0 is 2 * 3 * 4 = 24. The product of all elements except the one at index 1 is 1 * 3 * 4 = 12. Similarly, for index 2, the product is 1 * 2 * 4 = 8, and for index 3, the product is 1 * 2 * 3 = 6.
2. Input: `[4, 2, 1, 5, 3]`
Output: `[30, 60, 120, 24, 40]`
Explanation: The product of all elements except the one at index 0 is 2 * 1 * 5 * 3 = 30. The product of all elements except the one at index 1 is 4 * 1 * 5 * 3 = 60. Similarly, for index 2, the product is 4 * 2 * 5 * 3 = 120, for index 3, the product is 4 * 2 * 1 * 3 = 24, and for index 4, the product is 4 * 2 * 1 * 5 = 40.
3. Input: `[1, 1, 1, 1, 1]`
Output: `[1, 1, 1, 1, 1]`
Explanation: Since all elements are the same, the product of all elements except the one at each index will be the same element itself.
4. Input: `[0, 0, 0, 0]`
Output: `[0, 0, 0, 0]`
Explanation: Since there are zero values in the input array, the product of all elements except the one at each index will be zero.
5. Input: `[2, 3, 0, 4]`
Output: `[0, 0, 24, 0]`
Explanation: The product of all elements except the one at index 0 is 3 * 0 * 4 = 0. The product of all elements except the one at index 1 is 2 * 0 * 4 = 0. For index 2, the product is 2 * 3 * 4 = 24, and for index 3, the product is 2 * 3 * 0 = 0.

### Brute Force Approach

The brute force approach will be to calculate the product of all values in the array except the current value using two nested iterations.

Key Points:

- For each value, calculate the product of all other values by iterating through the array twice.
- This approach uses two nested loops to multiply each element with all other elements, excluding itself.
- However, this method is inefficient and may lead to a Time Limit Exceeded (TLE) error for larger test cases.

```java
class Solution {
    public int[] productExceptSelf(int[] nums) {
        int size = nums.length;
        int[] answer = new int[size];
        for(int i=0; i<size; i++) {
            answer[i] = 1;
        }
        for(int i=0; i<size; i++) {
            for(int j=0; j<size; j++) {
                if(i==j) continue;
                answer[i] *= nums[j];
            }
        }
        return answer;
    }
}
```

Time Complexity: O(N^2)

- The time complexity of the brute force approach is quadratic, as it involves nested loops that iterate through the array.

Space Complexity: O(1)

- The brute force approach doesn't require any additional space other than the answer array, so the space complexity is constant.

### Better Approach

```java
class Solution {
    public int[] productExceptSelf(int[] nums) {
        int size = nums.length;
        int[] answer = new int[size];
        int[] prefix =  new int[size];
        int[] suffix =  new int[size];
        int temp = 1;
        for(int i=0; i<size; i++) {
            prefix[i] = temp;
            temp *= nums[i];
        }
        temp = 1;
        for(int j=size-1; j>=0; j--) {
            suffix[j] = temp;
            temp *= nums[j];
        }
        for(int i=0; i<size; i++) {
            answer[i] = prefix[i] * suffix[i];
        }
        return answer;
    }
}
```

Key Points:

- The better approach uses separate iterations to calculate prefix and suffix values for each element.
- In this approach, we calculate the prefix products while traversing the array from left to right and storing them in the prefix array.
- Then, we calculate the suffix products while traversing the array from right to left and storing them in the suffix array.
- Finally, we multiply the corresponding prefix and suffix values to get the final products.

Time Complexity: O(N)

- The better approach performs two linear passes through the array, resulting in a linear time complexity.

Space Complexity: O(N)

- The better approach requires additional space to store the prefix and suffix arrays, resulting in linear space complexity.

### Optimal Approach

```java
class Solution {
    public int[] productExceptSelf(int[] nums) {
        int[] answer = new int[nums.length];

        int prefix = 1;
        for(int i=0; i<nums.length; i++) {
            answer[i] = prefix;
            prefix *= nums[i];
        }

        int suffix = 1;
        for(int j=nums.length-1; j>=0; j--) {
            answer[j] *= suffix;
            suffix *= nums[j];
        }

        return answer;
    }
}
```

Key Points:

- The optimal approach further improves efficiency by using the output array to store the prefix products.
- In this approach, we calculate the prefix products while traversing the array from left to right.
- Then, we calculate the suffix products while traversing the array from right to left.
- Finally, we multiply the suffix product with the corresponding prefix product to obtain the final answer.

Time Complexity: O(N)

- The optimal approach also performs two linear passes through the array, resulting in a linear time complexity.

Space Complexity: O(1)

- The optimal approach doesn't require any additional space other than the output array, so the space complexity is constant.

**Conclusion**

- The brute force solution has a time complexity of O(N²) but no extra memory usage.
- Using two extra arrays improves the time complexity to O(N) but also requires extra memory with the complexity of O(N).
- Using the linear traversals and answer array offers the best time complexity of O(N) but doesn't require any additional space other than the output array, so the space complexity is constant, O(1).

**NeetCode Solution Video**

https://www.youtube.com/watch?v=bNvIQI2wAjk

## **Recommended Resources to Learn Data Structures and Algorithms**

Basics of DS Algo Blogs:

1. [Hashing in Java](https://medium.com/techsoftware/understanding-hashing-in-java-exploring-hashmap-and-hashset-b2c7d28453c)

Recommended YouTubers for LeetCode Problems:

1. [NeetCode](https://www.youtube.com/@NeetCode)

2. [Take U Forward](https://www.youtube.com/@takeUforward/featured)

Free Resources for Learning Data Structures and Algorithms:

1. [NeetCode Roadmap](https://neetcode.io/roadmap?utm_source=aswin)

2. [Striver’s SDE Sheet](https://takeuforward.org/interviews/strivers-sde-sheet-top-coding-interview-problems/)

Recommended Courses for Learning Data Structures and Algorithms:

1. [NeetCode Courses](https://neetcode.io/courses?utm_source=aswin)
2. ZTM: Mastering the Coding Interview (Big Tech): Available on [Udemy](https://click.linksynergy.com/link?id=JDofPMV5KuY&offerid=1060092.3919716491451706865583445&type=2&murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fmaster-the-coding-interview-big-tech-faang-interviews%2F) and [ZTM Academy](https://academy.zerotomastery.io/a/aff_rml6679s/external?affcode=441520_dcwk-s8s)
3. ZTM: Mastering the Coding Interview: Available on [Udemy](https://click.linksynergy.com/link?id=JDofPMV5KuY&offerid=1060092.391976131953022569348758&type=2&murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fmaster-the-coding-interview-data-structures-algorithms%2F) and [ZTM Academy](https://academy.zerotomastery.io/a/aff_nqb6sg6w/external?affcode=441520_dcwk-s8s)
4. [Data Structures & Algorithms, Level-up for Coding Interviews Course](https://click.linksynergy.com/link?id=JDofPMV5KuY&offerid=1060092.391975289945963380819471&type=2&murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fcpp-data-structures-algorithms-levelup-prateek-narang%2F)
5. [Striver’s A2Z (Free) Course](https://takeuforward.org/strivers-a2z-dsa-course/strivers-a2z-dsa-course-sheet-2/)

Top Coursera Courses for Learning Data Structures and Algorithms:

1. [Coding Interview Preparation (Meta)](https://imp.i384100.net/QyNgyo)
2. [Algorithms Course Part I (Princeton University)](https://imp.i384100.net/KjqAe9)
3. [Algorithms Course Part II (Princeton University)](https://imp.i384100.net/VmbWyE)
4. [Data Structures and Algorithms Specialization (UC San Diego)](https://imp.i384100.net/g1AVOA)
5. [Algorithms Specialization (Stanford)](https://imp.i384100.net/75G7ag)

(Note: The Coursera courses can be audited to get free access to the lectures)

**🎙 Disclosure:** Please note that some of the links mentioned on this page may be affiliate links. This means that if you click on one of these links and make a purchase, I may earn a small commission from the sale.

**Who Am I?**

I’m Aswin Barath, a Software Engineering Nerd who loves building Web Applications, now sharing my knowledge through [Blogging](https://medium.com/techsoftware) during the busy time of my freelancing work life. Here’s the link to all of my craziness categorized by platforms under one place: https://linktr.ee/AswinBarath

**Keep Learning**

Now, I guess this is where I say goodbye 👋. But, hey it’s time for you to start **learning** with your newfound Knowledge(Power)👨‍💻👩‍💻. Good Job that you made it this far 👏 & **Thank you** so much for reading my Blog 🙂.