This code is a improved version of implementation which asked for a review: Product of all but one number in a sequence.
#include <stdio.h>
#include <stdlib.h>
//without division, with O(n) time, but extra space complexity as suggested
//return new array on the heap
int *derive_products(const int *nums, int count)
{
int *retval = malloc(count * sizeof *retval);
if (!retval && count)
return 0;
int mult=1; //product of prefix or suffix elements
//swipe up
for(int i=0; i<count; i++) {
retval[i] = mult;
mult *= nums[i];
}
//swipe down
for(int j=count-1, mult=1; j>=0; j--) {
retval[j] *= mult;
mult *= nums[j];
}
return retval;
}
int main()
{
/*Given an array of integers, return a new array such that each element at index i of the
new array is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be
[120, 60, 40, 30, 24] */
int nums[] = {1, 2, 2, 4, 6};
int size = sizeof(nums)/sizeof(nums[0]);
int *products = derive_products(nums, size); //get a new array
for (int i = 0; i < size; i++)
printf("%d ", products[i] );
free(products); //release heap memory
}