simplify removeDuplicates, fix last position calculation