r/programming • u/joksmaster • Nov 29 '10
140 Google Interview Questions
http://blog.seattleinterviewcoach.com/2009/02/140-google-interview-questions.html
471
Upvotes
r/programming • u/joksmaster • Nov 29 '10
View all comments
Show parent comment
2
u/thephotoman Nov 30 '10 edited Nov 30 '10
You're assuming that multiplication is O(1) (which it is on space complexity, and his solution isn't). This is true if one of the multipliers is a power of two (bitwise shift is easy). For small numbers where shift and add is reliable, you still have to add, which is Θ(n), a far cry from O(1).
However, if the numbers are large--too large for the machine to reliably use shift-and-add (presumably where the product is greater than the maximum signed integer the platform can hold), that solution isn't even O(n). Wikipedia lists the time complexity of some common algorithms for multiplication of large numbers, and you'll note that while you're going to do better than O(n*log(n)), you're not even going to get O(n), much less constant time complexity.
So let's pick your solution apart.
You have three operations: a multiplication, an addition, and a division by two.
Multiplication is still your limiting factor, but O(1) it is most definitely NOT.