changing algorithm for the end cases