replace and reverse algorithms