Derived a working optimized implementation that keeps track of the endpoints directly