Write new duplicate-removal function to use no extra memory