refactor so it memoizes chain lengths