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: Product of [1, 2, 3, 4] is 24
Example 2: Product is 0 when array contains 0
Example 3: Product of [2, 3] is 6
Algorithm Flow

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:
Then multiply each number into it:
Each step updates the running product to include one more array element.
At the end, return the accumulated result:
This handles zeros, negatives, and positive numbers naturally. The time complexity is O(n), and the extra space complexity is O(1).
Best Answers
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
