Algorithm Solution for Interview in Java