Code Logo

Multiply Array

Published at10 Jan 2026
1D Array Easy 19 views
Like27

Given an array of integers, compute the product of all elements. Return the product as an integer. If the array is empty, return 0.

For example, the product of [2, 3, 4] is 24. The product of [-2, 3, -4] is 24 (negative times negative gives positive). The product of [5, 0, 3] is 0. An empty array returns 0.

Computing the product of array elements teaches accumulation with multiplication instead of addition. Unlike sums, products can change sign and become zero when any element is zero.

The solution initializes a product variable to 1 and multiplies each element during iteration. After the loop, return the product.

Edge cases include an empty array (return 0), a single element (return that element), zero values (the entire product becomes 0), and negative numbers (an odd count of negatives produces a negative 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

Solution Approach

Iterate through the array and accumulate the product of all elements by multiplying each one.

function arrayProduct(arr)
  if arr is empty then return 0
  prod = 1
  for i = 0 to length(arr) - 1
    prod = prod * arr[i]
  return prod

Handle empty array by returning 0. Initialize prod to 1 (the multiplicative identity). Loop through each element and multiply it into the running product using the * operator. Return the final accumulated product after processing all elements.

Time complexity is O(n), 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;
    }
}