What about an alternative for the “adding up” solution as follows. Instead of summing the first and second array, then subtracting from each other, which can cause overflow, we can interleave between adding and subtracting. That is,
-take the 1st element in the 1st array
- subtract it from the 1st element in the 2nd,
- add to the 2nd element in the 1st array,
- subtract the result from the 2nd element in the 2nd array.
- so on.
We have an O(n) in time and O(1) in space. Let me know what you think. Thanks for your wonderful blog Ardan.
]]>Your solutions to the problem are brilliant! I like how you analyze various approaches and slowly lead the reader to the optimal solution (rather than presenting the reader with the best solution at the beginning).
Keep up the good work and thanks so much for sharing!
]]>