O(n) space complexity