[mod] reduce space complexity to O(n)