Microsoft interview question

Require best algorithm both in time and space