O(n) solution to Multiply Others problem in F#

Another tasty challenge that I ran into during my preparation for technical interviews is this seemingly simple problem from Facebook.

input [2,3,1,4]
output [12,8,24,6]

Multiply all fields except it’s own position.

Restrictions:
1. no use of division
2. complexity in O(n)

The main challenge is in making the algorithm run in O(n) time.

One solution I saw (and thought it was quite clever) is to maintain two temporary arrays, calculated by multiplying the elements of the input array from front-to-back, and back-to-front.

ie. input is [ 2, 3, 1, 4 ]

The front array starts with [ 1, 0, 0, 0 ], and starting from position 1, we can say front[i] = front[i-1] * input[i-1] and end up with [ 1, 2, 6, 6 ] (which is the product of all the input elements before that position.

The rear array starts with [ 0, 0, 0, 1 ] and starting from position 2 (ie, second to last), we can say rear[i] = rear[i+1] * input[i+1] and end up with [ 12, 4, 4, 1 ].

And finally we can work out the output array by multiplying the corresponding elements in the front and rear arrays, and that runs in O(n) of time and space.

Here’s the implementation in F#.

 

Try it Yourself

Links

Enjoy what you’re reading? Subscribe to my newsletter and get more content on AWS and serverless technologies delivered straight to your inbox.


Yan Cui

I’m an AWS Serverless Hero and the author of Production-Ready Serverless. I have run production workload at scale in AWS for nearly 10 years and I have been an architect or principal engineer with a variety of industries ranging from banking, e-commerce, sports streaming to mobile gaming. I currently work as an independent consultant focused on AWS and serverless.

You can contact me via Email, Twitter and LinkedIn.

Hire me.


Check out my new course, Complete Guide to AWS Step Functions.

In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. Including basic concepts, HTTP and event triggers, activities, design patterns and best practices.

Get Your Copy