Search⌘ K

Solution Review: Array of Products of All Elements

Explore how to solve the problem of computing the product of all elements in an array except the current index using efficient C# code. Understand a two-pass algorithm that calculates left and right products separately to achieve an O(n) time solution. Gain skills to implement this approach and improve your problem-solving techniques for coding interviews.

We'll cover the following...

Solution #

C#
namespace chapter_2
{
class Solution
{
// Array of Products of all Elements
static int[] findProduct(int []arr, int size)
{
int n = size;
int i, temp = 1;
int[] product = new int[n]; // Allocate memory for the product array
// temp contains product of elements on left side excluding arr[i]
for (i = 0; i < n; i++)
{
product[i] = temp;
temp *= arr[i];
}
temp = 1; // Initialize temp to 1 for product on right side
// temp contains product of elements on right side excluding arr[i]
for (i = n - 1; i >= 0; i--)
{
product[i] *= temp;
temp *= arr[i];
}
return product;
}
static void Main(string[] args)
{
int size = 4;
int []arr = { 1, 3, 4, 5 };
Console.Write( "Array before product: ");
for (int i = 0; i < size; i++)
{
Console.Write(arr[i] + " ");
}
Console.WriteLine("");
int[] prodArray = findProduct(arr, size);
Console.Write("Array after product: ");
for (int i = 0; i < size; i++)
{
Console.Write(prodArray[i] + " ");
}
return ;
}
}
}

Explanation

In this problem, you need to calculate the product of elements in a specific way. In the output array, the value at index i will be equal to the product of all the elements of the given array arr ...