time complexity improved to O(n)