I came accross this question in a Online Coding Assesment. Can anyone give an optimal solution for this question?