O(n) time complexity and O(1) space complexity