Microsoft interview question

Find an efficient algorithm for this problem