Refactor implementation to avoid class variable and run in O(n) rather than O(n^2).