improved the stack solution