Pregunta de entrevista de Microsoft

Find an efficient algorithm for this problem