πDay 4. Product array puzzle π§
The problem can be found at the following link: Problem Link
π‘ Problem Description:
You are given an array arr[] of size n. Your task is to construct an array res[] such that res[i] is equal to the product of all the elements of arr[] except arr[i]. Return the resultant array res[].
Note: Each element in res[] lies within the 32-bit integer range.
π Example Walkthrough:
Input:
arr[] = [10, 3, 5, 6, 2]
Output:
[180, 600, 360, 300, 900]
Explanation:
For i = 0, res[i] = 3 * 5 * 6 * 2 = 180.
For i = 1, res[i] = 10 * 5 * 6 * 2 = 600.
For i = 2, res[i] = 10 * 3 * 6 * 2 = 360.
For i = 3, res[i] = 10 * 3 * 5 * 2 = 300.
For i = 4, res[i] = 10 * 3 * 5 * 6 = 900.
Input:
arr[] = [12, 0]
Output:
[0, 12]
Explanation:
For i = 0, res[i] = 0.
For i = 1, res[i] = 12.
Constraints:
$
2 <= arr.size() <= 10^5$-100 <= arr[i] <= 100
π― My Approach:
Handling Zeroes: If the array contains:
More than one zero: Every element in
res[]will be0.Exactly one zero: Only the position corresponding to the zero will have the product of all other non-zero elements, and the rest will be
0.No zeroes: Use the total product of all elements and divide by the current element for each position in the result array.
Efficient Computation:
Iterate through the array once to calculate the total product of non-zero elements and the count of zeroes.
Build the result array in a second pass.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where
nis the size of the array. The algorithm requires two linear traversals of the array.Expected Auxiliary Space Complexity: O(1), as the solution uses only a constant amount of additional space.
π Solution Code
Code (C++)
Code (Java)
Code (Python)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated