commented solution with test cases (improved comments)