[LeetCode] 238. Product of Array Except Self

Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Solve it without division and in O(n).
For example, given [1,2,3,4], return [24,12,8,6].
Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)

Thought process:
Use one array to record the product of numbers to the left of each number, and use another to record the product of numbers to the right of each number. Then iterate through the array and multiply left[i] and right[i].

Solution 1:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Solution {
    public int[] productExceptSelf(int[] nums) {
        int length = nums.length;
        if (length == 0) {
            return nums;
        }
        int[] left = new int[length];
        left[0] = 1;
        int[] right = new int[length];
        right[length - 1] = 1;
        
        for (int i = 1; i < length; i++) {
            left[i] = left[i - 1] * nums[i - 1];
        }
        for (int i = length - 2; i >= 0; i--) {
            right[i] = right[i + 1] * nums[i + 1];
        }
        
        int[] product = new int[length];
        for (int i = 0; i < length; i++) {
            product[i] = left[i] * right[i];
        }
        
        return product;
    }
}

Time complexity: O(n). Space complexity: O(n).

Follow up:
The idea is to keep track of left and right directly using the result array. First, I iterate through the array from left to right, and record the product of numbers to the left of each number. Second, I iterate through the array from right to left, and multiply current product with product of numbers to the right of each number.

Solution 2:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Solution {
    public int[] productExceptSelf(int[] nums) {
        int length = nums.length;
        if (length == 0) {
            return nums;
        }
        int[] product = new int[length];
        product[0] = 1;
        
        int left = 1;
        for (int i = 1; i < length; i++) {
            product[i] = left * nums[i - 1];
            left *= nums[i - 1];
        }
        
        int right = 1;
        for (int i = length - 2; i >= 0; i--) {
            right *= nums[i + 1];
            product[i] = right * product[i];
        }
        
        return product;
    }
}

Time complexity: O(n). Space complexity: O(1).

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula