Refactored pair iterator for problem 27.