Final code working with 6 test cases