Solution #1

Test cases 2,3 timed out for below solution.