I’m not sure that it’s O(N) with caching but this illustrates the N^2 part:
https://blog.exe.dev/expensively-quadratic