only O(k) extra space