truly O(n) solution, bottom-up