time complexity: O(n), space complexity: O(1)