Implementation for CTCI 7.7 problem