I was given the following prompt in a coding interview:
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]
I solved this in two ways:
fun
multiplies all elements together in the first iteration, and then loops again and divides by the number at that positionfun2
does not use division, and instead iteratively builds up the sum in each index
#include <stdio.h>
#include <stdlib.h>
int fun(int* nums, int arr_size)
{
int sum;
int i;
for(i=0, sum=1; i<arr_size; i++)
sum*=nums[i];
for(i=0; i<arr_size; i++)
nums[i]=sum/nums[i];
return 0;
}
int fun2(int* nums, int arr_size)
{
int i,j;
int sum=1;
int new_arr[arr_size];
for(i=0; i<arr_size; i++) {
for(j=0; j<arr_size; j++) {
if(i!=j)
sum*=nums[j]; //skip member same index in the loop
}
new_arr[i]=sum;
sum=1;
}
memcpy(nums, new_arr, arr_size*sizeof(int));
return 0;
}
int main(void)
{
/*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 i;
fun(nums, size);
for (i = 0; i < size; i++)
printf("%d ", nums[i]);
//what if you can't use division?
printf("\n");
int nums2[] = {1, 2, 2, 4, 6};
fun2(nums2, size);
for (i = 0; i < size; i++)
printf("%d ", nums2[i]);
return 0;
}
```
fun2
but I am not good enough at math to find it, so my only nit pick forfun2
is that you don't need thesum
var. Just usenew_arr[i]
directly. Also, I would suggest moving the description of what the code does from comment inmain
to actual text of you question above the code to make it easy for other users find it. It is easy to miss and people might ignore the question if they don't know what the code is suppose to produce. \$\endgroup\$