BackeasyDynamic ProgrammingHCLPhonePe

Cumulative Path Weight Solution

Problem Statement

You are given an integer array nums of length N. The task is to compute the cumulative product of all elements in the array, traversing them from index 0 to N-1. This value represents the total weight accumulated along a linear path where each step multiplies the current weight by the value at that position.

If any element in the array is zero, the final product is zero. The sign of the result depends on the count of negative integers: an even number of negatives yields a positive result, while an odd number yields a negative result. Note that for large arrays or large values, the product can exceed standard integer limits; however, for this problem, assume the result fits within a 64-bit signed integer.

Input: A single line containing an integer N, followed by a line containing N space-separated integers representing the array nums. Output: A single integer representing the cumulative product of the array elements.

Example 1
Input
3 2 3 4
Output
24

Explanation: Start with 1. Multiply by 2 -> 2. Multiply by 3 -> 6. Multiply by 4 -> 24. Final result is 24.

Example 2
Input
4 -2 3 -4 5
Output
120

Explanation: Start with 1. Multiply by -2 -> -2. Multiply by 3 -> -6. Multiply by -4 -> 24. Multiply by 5 -> 120. Two negatives make a positive result.

Example 3
Input
5 1 0 7 8 9
Output
0

Explanation: Start with 1. Multiply by 1 -> 1. Multiply by 0 -> 0. Any subsequent multiplication remains 0. Final result is 0.

Example 4
Input
2 -1 -1
Output
1

Explanation: Start with 1. Multiply by -1 -> -1. Multiply by -1 -> 1. Two negatives yield a positive result.

Constraints

  • 1 <= N <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • The final product is guaranteed to fit within a 64-bit signed integer (-2^63 to 2^63 - 1)
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Cumulative Path Weight — Problem Statement & Solution Guide

Dynamic ProgrammingEasyKnapsack State
TimeO(N)
|
SpaceO(1)

Problem Description

You are given an integer array nums of length N. The task is to compute the cumulative product of all elements in the array, traversing them from index 0 to N-1. This value represents the total weight accumulated along a linear path where each step multiplies the current weight by the value at that position.

If any element in the array is zero, the final product is zero. The sign of the result depends on the count of negative integers: an even number of negatives yields a positive result, while an odd number yields a negative result. Note that for large arrays or large values, the product can exceed standard integer limits; however, for this problem, assume the result fits within a 64-bit signed integer.

Input: A single line containing an integer N, followed by a line containing N space-separated integers representing the array nums.

Output: A single integer representing the cumulative product of the array elements.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Cumulative Path Weight"

easy

WHY DOES IT MATTER?

Prefix accumulation is a foundational pattern for many problems—running sums, products, min/max prefixes, and sliding window calculations—all rely on efficiently propagating state across a sequence.

OPTIMIZATION CHALLENGE

The key insight is recognizing that each step only needs the previous product, eliminating the need for nested loops or recomputation of earlier prefixes, thus collapsing O(N^2) work into a single linear pass.

REAL-WORLD CONNECTION

In a supply‑chain simulation, each node’s inventory weight multiplies by a factor (e.g., tax, loss) as goods move along the route; the final weight is the product of all factors, mirroring the cumulative product computation.

During an interview, write the loop that updates a 'prod' variable, break early on zero, and explicitly mention overflow handling; this shows awareness of edge cases and production‑grade robustness.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
đź’ľ Space:O(1)

Core Theory — Why This Approach?

The cumulative product problem is a classic example of a linear scan where each element’s contribution depends multiplicatively on the prefix of the array. A naive solution would recompute the product for each prefix from scratch, leading to O(N^2) time, which quickly becomes infeasible for large N (e.g., N up to 10^6) due to the quadratic blow‑up. The optimal paradigm leverages the associative property of multiplication: (a·b)·c = a·(b·c). By maintaining a running product while iterating once through the array, we can update the result in constant time per element.

Dynamic programming concepts appear here in the form of prefix accumulation—each state (the product up to index i) is derived from the previous state (product up to i‑1) and the current element. This one‑dimensional DP reduces both time and space because we only need the immediate previous product, not the entire history. Edge cases such as zeros or integer overflow are handled separately: a zero anywhere forces the final product to zero, and using a larger numeric type (e.g., 64‑bit or big integer) prevents overflow in languages with fixed‑size integers.

Thus, the optimal solution runs in O(N) time with O(1) auxiliary space, making it suitable for real‑time systems and massive data streams where a single pass is mandatory.

Interview Questions on This Problem

Q1How would you modify the algorithm to return the cumulative product array (prefix products) instead of a single total product?

Initialize an output array of size N, set output[0] = nums[0]; then iterate i from 1 to N‑1, setting output[i] = output[i‑1] * nums[i]. Handle zeros by resetting subsequent products to zero. This still runs in O(N) time and O(N) space for the result.

Q2If the array can contain very large numbers causing overflow, what strategies can you employ to compute the product safely?

Use a language’s arbitrary‑precision integer type (e.g., Python's int, Java's BigInteger) or work in logarithmic space by summing logarithms and exponentiating at the end, while being careful with sign and zero handling.

Q3Explain how you would parallelize the cumulative product computation on a distributed system.

Divide the array into chunks, compute the product of each chunk locally, then perform a prefix scan over the chunk products to propagate the cumulative factor to each segment. Finally, each node multiplies its local prefix results by the received factor. This yields O(log P) synchronization steps for P processors.

Examples

Example 1

Input

3
2 3 4

Output

24

Explanation: Start with 1. Multiply by 2 -> 2. Multiply by 3 -> 6. Multiply by 4 -> 24. Final result is 24.

Example 2

Input

4
-2 3 -4 5

Output

120

Explanation: Start with 1. Multiply by -2 -> -2. Multiply by 3 -> -6. Multiply by -4 -> 24. Multiply by 5 -> 120. Two negatives make a positive result.

Example 3

Input

5
1 0 7 8 9

Output

0

Explanation: Start with 1. Multiply by 1 -> 1. Multiply by 0 -> 0. Any subsequent multiplication remains 0. Final result is 0.

Example 4

Input

2
-1 -1

Output

1

Explanation: Start with 1. Multiply by -1 -> -1. Multiply by -1 -> 1. Two negatives yield a positive result.

Constraints

  • 1 <= N <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • The final product is guaranteed to fit within a 64-bit signed integer (-2^63 to 2^63 - 1)

Optimal Approach & Strategy

Maintain a single running product while scanning the array once, updating it with each element, and handling zeros early.

Brute Force Approach

Recompute the product for each prefix by looping over the array from the start up to the current index, resulting in a nested loop.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function main() {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        terminal: false
    });

    let lines = [];
    rl.on('line', line => lines.push(line));
    rl.on('close', () => {
        const n = parseInt(lines[0]);
        const nums = lines[1].split(' ').map(Number);
        
        let product = 1;
        for (let i = 0; i < n; i++) {
            product *= nums[i];
        }
        
        console.log(product);
    });
}

main();

Asked in Top Tech Interviews

HCLPhonePe

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.