change path algorithm to O(n)/O(1)