A Product Array Puzzle in C?

A Product Array Puzzle is a common programming problem where we need to construct an array such that each element contains the product of all elements in the original array except the element at that position. The constraint is that we cannot use the division operator.

Syntax

void productArray(int arr[], int n, int result[]);
// arr[] - input array
// n - size of array  
// result[] - output array containing products

Approach: Using Left and Right Product Arrays

The solution uses two auxiliary arrays to store products of elements to the left and right of each position. For each index, we multiply the left product with the right product to get the final result −

#include <stdio.h>
#include <stdlib.h>

void productArray(int arr[], int n) {
    int *left = (int *)malloc(sizeof(int) * n);
    int *right = (int *)malloc(sizeof(int) * n);
    int *result = (int *)malloc(sizeof(int) * n);
    
    if (left == NULL || right == NULL || result == NULL) {
        printf("Memory allocation failed<br>");
        return;
    }
    
    /* Build left product array */
    left[0] = 1;
    for (int i = 1; i < n; i++)
        left[i] = arr[i-1] * left[i-1];
    
    /* Build right product array */
    right[n-1] = 1;
    for (int j = n-2; j >= 0; j--)
        right[j] = arr[j+1] * right[j+1];
    
    /* Calculate final product array */
    for (int i = 0; i < n; i++)
        result[i] = left[i] * right[i];
    
    /* Print the result */
    printf("Product array: ");
    for (int i = 0; i < n; i++)
        printf("%d ", result[i]);
    printf("<br>");
    
    free(left);
    free(right);
    free(result);
}

int main() {
    int arr[] = {10, 3, 5, 6, 2};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    printf("Original array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("<br>");
    
    productArray(arr, n);
    
    return 0;
}
Original array: 10 3 5 6 2 
Product array: 180 600 360 300 900 

How It Works

  • Left Array: left[i] contains the product of all elements to the left of index i
  • Right Array: right[i] contains the product of all elements to the right of index i
  • Result: result[i] = left[i] * right[i] gives the product of all elements except arr[i]

Key Points

  • Time complexity is O(n) with three separate loops
  • Space complexity is O(n) for the auxiliary arrays
  • Always check for memory allocation failures when using malloc()
  • Remember to free() allocated memory to prevent memory leaks

Conclusion

The Product Array Puzzle efficiently finds products without division using left and right product arrays. This approach handles all cases including zeros and maintains O(n) time complexity.

Updated on: 2026-03-15T12:10:15+05:30

390 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements