Question d’entretien chez Microsoft

Find an efficient algorithm for this problem