Microsoft Interview Question

Find an efficient algorithm for this problem