I got this question in Microsoft OA and it took me a lot of time and I came up with a naive solution in the given time. Can anyone please help me with an optimized approach or code for the following question :