Stacks: Challenge 2 solution bug?

The provided solution is:

  for char in str {
    if char == "(" {
      myStack.push(char)
    } else if char == ")" {
      if myStack.isEmpty {
        return false
      } else {
        myStack.pop()
      }
    }
  }
  return myStack.isEmpty

This works for the provided string, however if you have a string in which “(” comes last, you will always get false, regardless of if the amount is equal or not. I solved this one by using two counters to count each time a “(” or “)” was pushed into my stack instead.

Anyone have thoughts?

I had the same perplexity as you initially, and I too implemented a counter. Afterwards, however, I reinterpreted the challenge, since it actually syntactically does not make sense to have a string in which, first there is a closing parenthesis and then an opening parenthesis. Interpreted in this way, the solution offered by the book is correct. :thinking: