failed to fully understand how stack works in this problem