Working (passed all test cases) but MESSY solution