O(n) solution