Seeing the first post gained some popularity, here is the second problem
For quite some time I found my time procastinating after getting home fro...
For further actions, you may consider blocking this person and/or reporting abuse
In python 2.7, no division, O(n) time. The tradeoff is using a bunch of memory, if the list is very long.
Nice find :-)
For the first problem I'd loop over the array twice. The first time to compute the total product and the second time to fill in the output array, dividing out each element of the input array from the total product for the corresponding output element.
I'm guessing that your solution is for the follow-up question though :-). If you have logarithms you could use them to convert multiplication and division to addition and subtraction. This is a common trick when working over finite fields.
Or with no additional space required:
O(n) with division, in C#
stackblitz.com/edit/js-xqagwj
I did something very similar to this. I realised quickly that if any of the numbers in the array are repeated, the totals don’t come out right. I had to explicitly remove the element from the input array and then use the reduce function to calculate the product.
HTH
Solution in Python without division, still in O(n²), but inner loop is only executed n²/2 times:
Here's my TypeScript version.
This approach works in O(n) by dividing the product of all elements by
x[i]
.Without being aware of possible constraints on the input numbers, a solution with division is most efficient as it conserves both memory (2 array allocations: input and output) and cpu (2 enumerations of the the array, O(2n) ~= O(n)). This was described by @severinson . Here it is in F#.
To consider a solution without division, understand that we are using division here to reverse a multiplication. An alternative is to choose not to multiply in the first place. But in order to do that, we move to an O( n2 ) solution where we shape each element of the output array as we process the input. Then we can choose to selectively skip multiplication.
Note: This function is "pure", despite using mutation internally.
Part 2 solution, slightly better than O(n2), using a copy to initialize the array, and the inner loop runs 2 fewer times than the outer.
Don't know if the use of Parallel.ForEach is legit, but here's my take using C# and Linq
Simple Rust solution:
For follow-up question:
JavaScript O(n) but with division:
Javascript solution, no division, O(n) time.
The idea is basically two steps:
I also do a 3rd step to map from that object to the subproducts, but that could be spared if we created a new array during step 1, but still that step would still keep it O(n)
O(n) time, using division, in haskell:
O(n) time, without division, in haskell:
private void ArrayProduct(int arraySize, int [] numArray)
{
int[] prodArray = new int[arraySize];
I like the idea, I will be joining it daily. Thanks!
I used numpy, is that cheating? :)
gyazo.com/90a3ac57b8b3339867278e4f...