O(1) space complexity solution