Code Logo

Multiply Array

Published at10 Jan 2026
Easy 5 views
Like27

This problem asks for the product of all numbers in the array. Instead of adding them together, you multiply them one by one until every element has been included.

A zero matters a lot here because once the array contains a zero, the whole product becomes zero. Negative values matter too, since multiplying by a negative number flips the sign of the result.

For example, if nums = [1,2,3,4], the answer is 24. If nums = [5,0,10], the answer is 0 because the zero wipes out the entire product. With nums = [-1,5], the answer is -5.

So the task is to multiply every element in the array and return the final product.

Example Input & Output

Example 1
Input
nums = [1, 2, 3, 4]
Output
24
Explanation

Example 1: Product of [1, 2, 3, 4] is 24

Example 2
Input
nums = [5, 0, 10]
Output
0
Explanation

Example 2: Product is 0 when array contains 0

Example 3
Input
nums = [2, 3]
Output
6
Explanation

Example 3: Product of [2, 3] is 6

Algorithm Flow

Recommendation Algorithm Flow for Multiply Array
Recommendation Algorithm Flow for Multiply Array

Solution Approach

The direct solution is to walk through the array while keeping a running product.

We begin with 1 because multiplying by 1 does not change the result:

let product = 1;

Then multiply each number into it:

for (const num of nums) {
  product *= num;
}

Each step updates the running product to include one more array element.

At the end, return the accumulated result:

return product;

This handles zeros, negatives, and positive numbers naturally. The time complexity is O(n), and the extra space complexity is O(1).

Best Answers

java
class Solution {
    public long multiply_array(int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        long product = 1;
        for (int num : nums) product *= num;
        return product;
    }
}