Check out my new course Learn you some Lambda best practice for great good! and learn the best practices for performance, cost, security, resilience, observability and scalability.
Another tasty challenge that I ran into during my preparation for technical interviews is this seemingly simple problem from Facebook.
Multiply all fields except it’s own position.
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
- Interview question on CareerCup
- DotNetFiddle snippet
- All my Project Euler solutions in F#
- All my Advent of Code solutions in F#
I specialise in rapidly transitioning teams to serverless and building production-ready services on AWS.
Are you struggling with serverless or need guidance on best practices? Do you want someone to review your architecture and help you avoid costly mistakes down the line? Whatever the case, I’m here to help.
Check out my new course, Learn you some Lambda best practice for great good! In this course, you will learn best practices for working with AWS Lambda in terms of performance, cost, security, scalability, resilience and observability. Enrol now and enjoy a special preorder price of £9.99 (~$13).
Are you working with Serverless and looking for expert training to level-up your skills? Or are you looking for a solid foundation to start from? Look no further, register for my Production-Ready Serverless workshop to learn how to build production-grade Serverless applications!
Here is a complete list of all my posts on serverless and AWS Lambda. In the meantime, here are a few of my most popular blog posts.
- Lambda optimization tip – enable HTTP keep-alive
- You are thinking about serverless costs all wrong
- Many faced threats to Serverless security
- We can do better than percentile latencies
- I’m afraid you’re thinking about AWS Lambda cold starts all wrong
- Yubl’s road to Serverless
- AWS Lambda – should you have few monolithic functions or many single-purposed functions?
- AWS Lambda – compare coldstart time with different languages, memory and code sizes
- Guys, we’re doing pagination wrong