Add solution from teachers java implementation.