albertonline· portal
blind75

Product of Array Except Self

Dec 23, 2023 · An efficient solution to find the product of all elements of an array except the one at each index.

In many coding challenges, especially in array manipulation problems, one often encounters the need to compute the product of all elements in an array except the one at the current index. The productExceptSelf function is a classic example of such a problem, demonstrating an efficient approach without using division.

The Function

javascript

The "Product of Array Except Self" problem is a classic challenge often encountered in coding interviews. It tests a candidate's ability to manipulate arrays and optimize algorithms.

Problem Statement

Given an array nums of n integers where n > 1, the task is to return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Constraints and Challenges

  • No division operation is allowed in the solution.
  • The goal is to achieve a linear runtime complexity, O(n).
  • A straightforward nested loop approach leads to O(n²) time complexity, which is inefficient.

Techniques for Solution

  1. Prefix and Postfix Products: This efficient approach involves two passes through the array:

    • Prefix Product: Traverse the array from left to right, calculating the cumulative product up to the current element. Store these products in a new array.
    • Postfix Product: Traverse the array from right to left, calculating the cumulative product from the end to the current element. Multiply these with the prefix products in the new array.
  2. Left and Right Product Lists: Use two additional arrays to store products of all elements to the left and right of each element, and then multiply corresponding elements from these arrays for the final result. This method uses extra space.

  3. Optimized Space Approach: Optimize the space complexity by using the output array for storing one of the lists (like left products) and a variable to track the right product during the second traversal.

Example

Consider nums = [1, 2, 3, 4]. The expected output is [24, 12, 8, 6].

  • After the first pass (prefix): [1, 1, 2, 6].
  • After the second pass (postfix): [24, 12, 8, 6].

This problem demonstrates the importance of array manipulation and optimizing solutions for better time and space efficiency.

References

https://www.enjoyalgorithms.com/blog/product-of-array-except-self


Rust Solution

rust

Rust takes nums: Vec<i32> by value, so the function owns the vector outright and indexes it freely; every binding that mutates — res, prefix, postfix — needs let mut, since bindings are immutable by default. vec![0; n] pre-fills the result with zeros before the forward pass overwrites each res[i], and the backward pass reaches for the (0..n).rev() reverse-iterator idiom rather than a hand-rolled decrementing index. The bare res on the final line is the return value — a Rust function yields its tail expression with no return keyword — and println!("{:?}", res) uses the {:?} debug formatter to print the whole Vec.

Go Solution

go

Go allocates the result with make([]int, n), which zero-fills every slot so the prefix pass can overwrite each res[i] in place. Short declarations (n := len(nums), prefix := 1) infer their types from the initialiser via :=, and both traversals are plain C-style three-clause loops — for i := 0; i < n; i++ forward and for i := n - 1; i >= 0; i-- backward — since Go has no reverse-range form. The []int result is handed back with an explicit return res, and fmt.Println prints the slice directly using its default formatting.

Comments (0)

Stub comments live in your browser only (localStorage). No server round-trip yet.

No comments yet. Be the first.