Added functions to calculate the count and end in constant time where possible. Added unit tests too.