Register for our webinar

How to Nail your next Technical Interview

1 hour
Loading...
1
Enter details
2
Select webinar slot
*Invalid First Name
*Invalid Last Name
*Invalid Phone Number
By sharing your contact details, you agree to our privacy policy.
Select your webinar time
Step 1
Step 2
Congratulations!
You have registered for our webinar
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
Step 1
Step 2
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.
About usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar
Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career

Array Product Problem

Array Product Problem Statement

Given an array of numbers, return an array of the same size where i-th element is the product of all elements except the i-th one.

Calculate the products modulo 109 + 7.

Using division is not allowed anywhere in the solution. Using more than constant auxiliary space is not allowed.

Example

{
"nums": [1, 2, 3, 4, 5]
}

Output:

[120, 60, 40, 30, 24]

[(2 * 3 * 4 * 5), (1 * 3 * 4 * 5), (1 * 2 * 4 * 5), (1 * 2 * 3 * 5), (1 * 2 * 3 * 4)] = [120, 60, 40, 30, 24]

Notes

Constraints:

  • 2 <= length of the array <= 100000
  • -109 <= a number in the array <= 109

If you are getting a wrong answer for some test cases, but think your logic is correct, check for the overflow.

Let mod = 109 + 7.

If a = 109 and b = 109, then int c = (a * b) % mod will overflow but this will work: int c = (a * (long long) 1 * b) % mod. By multiplying with (long long) 1, we make sure that the calculation is done in long long, instead of int.

We provided two solutions.

Let us refer to the length of input array nums as n.

Array Product Solution 1: Brute Force

A naive approach would be to find the i-th element of the output array (i.e. products[i]), iterate over the entire input array to get the product of all elements nums[j], such that j != i.

Time Complexity

O(n2).

As we are iterating over the entire array to find products[i] and as it can be 0 <= i <= (n - 1). Each calculation of element of products array will take O(n) so total complexity will be O(n2).

Auxiliary Space Used

O(1).

As we are not storing anything extra and excluding space used to store output array products.

Space Complexity

O(n).

Space used for input: O(n).

Auxiliary space used: O(1).

Space used for output: O(n).

So, total space complexity: O(n) + O(1) + O(n) = O(n).

Code For Array Product Solution 1: Brute Force

    /*
    * Asymptotic complexity in terms of the size of the input array \`n\`:
    * Time: O(n^2).
    * Auxiliary space: O(1).
    * Total space: O(n).
    */

    static int mod = (int)Math.pow(10, 9) + 7;

    static ArrayList<Integer> get_product_array(ArrayList<Integer> nums) {
        // Size of output array is same as that of input array
        ArrayList<Integer> products = new ArrayList<Integer>(Collections.nCopies(nums.size(), 1));

        for (int currentIndex = 0; currentIndex < nums.size(); currentIndex++) {
            for (int iterator = 0; iterator < nums.size(); iterator++) {
                if (iterator != currentIndex) {
                    nums.set(iterator, (nums.get(iterator).intValue() > 0 ? (nums.get(iterator).intValue() % mod) : ((mod + nums.get(iterator)) % mod)));
                    products.set(currentIndex, (int)((products.get(currentIndex).intValue() * 1l * nums.get(iterator).intValue()) % mod));
                }
            }
        }

        return products;
    }

Array Product Solution 2: Optimal

Notice that for products[i], product of all input array elements other than i-th element is nothing but (product of all elements nums[j], 0 <= j <= (i - 1)) * (product of all elements nums[j], (i + 1) <= j <= (n - 1)) = (nums[0] * nums[1] * ... * nums[i - 1]) * (nums[i + 1] * nums[i + 2] * ...* nums[n - 1]).

So, iterate over the input array twice to fill output array products, once for updating products[i] with (nums[0] * nums[1] *...* nums[i - 1]), and next one for updating products[i] with (nums[i + 1] * nums[i + 2] * … * nums[n - 1]).

Time Complexity

O(n).

As we are iterating over the input array two times it will take O(n).

Auxiliary Space Used

O(1).

We are not storing anything extra.

Space Complexity

O(n).

Space used for input: O(n).

Auxiliary space used: O(1).

Space used for output: O(n).

So, total space complexity: O(n) + O(1) + O(n) = O(n).

Code For Array Product Solution 2: Optimal

    /*
    * Asymptotic complexity in terms of the size of the input array \`n\`:
    * Time: O(n).
    * Auxiliary space: O(1).
    * Total space: O(n).
    */

    static int mod = (int)Math.pow(10, 9) + 7;

    static ArrayList<Integer> get_product_array(ArrayList<Integer> nums) {

        // Size of output array is same as that of input array
        ArrayList<Integer> products = new ArrayList<>(Collections.nCopies(nums.size(), 0));

        // For finding value of products[i], product of all nums elements
        // other than ith element is nothing but
        // (product of all nums[j], 0 <= j <= (i - 1)) * (product of all nums[j], (i + 1) <= j <= (nums.size() - 1))
        // i.e. (nums[0] * nums[1] * ...* nums[i - 1]) * (nums[i + 1] * nums[i + 2] * ... * nums[nums.size() - 1])

        int leftProduct = 1;

        // Filling products, such that products[i] contains
        // product of all elements nums[j], 0 <= j <= (i - 1)
        for (int currentIndex = 0; currentIndex < nums.size(); currentIndex++) {
            // Here, leftProduct contains product of all elements
            // nums[j], 0 <= j <= (currentIndex - 1)
            products.set(currentIndex, leftProduct);

            // After this updation of leftProduct, leftProduct contains product of all
            // elements nums[j], 0 <= j <= currentIndex
            nums.set(currentIndex, (nums.get(currentIndex) > 0 ? nums.get(currentIndex) : (mod + nums.get(currentIndex)) % mod));
            leftProduct = (int)((leftProduct * 1l * nums.get(currentIndex)) % mod);
        }

        int rightProduct = 1;

        // Updating products, such that products[i] contains new value
        // ((products[i]) * (product of all elements nums[j], 0 <= j <= (i - 1)))
        for (int currentIndex = nums.size() - 1; currentIndex >= 0; currentIndex--) {
            // Here, rightProduct contains product of all elements
            // nums[j], (currentIndex + 1) <= j <= (nums.size() - 1)
            products.set(currentIndex, ((int)((products.get(currentIndex) * 1l * rightProduct) % mod)));

            // after this updation of rightProduct, rightProduct contains product of all
            // elements nums[j], currentIndex <= j <= (nums.size() - 1)
            rightProduct = (int)((rightProduct * 1l * nums.get(currentIndex)) % mod);
        }
        return products;
    }

We hope that these solutions to array product problem have helped you level up your coding skills. You can expect problems like these at top tech companies like Amazon and Google.

If you are preparing for a tech interview at FAANG or any other Tier-1 tech company, register for Interview Kickstart's FREE webinar to understand the best way to prepare.

Interview Kickstart offers interview preparation courses taught by FAANG+ tech leads and seasoned hiring managers. Our programs include a comprehensive curriculum, unmatched teaching methods, and career coaching to help you nail your next tech interview.

We offer 18 interview preparation courses, each tailored to a specific engineering domain or role, including the most in-demand and highest-paying domains and roles, such as:

‍To learn more, register for the FREE webinar.

Try yourself in the Editor

Note: Input and Output will already be taken care of.

Recommended Posts

All Posts