Fix the algorithms for edge cases