awelgorithms

Treat an empty string as balanced

Updated

No characters means no unmatched opener and no stray closer. The stack stays empty. Empty is valid, not an error.

What to focus on

isValid("") is true. isValid("()") is also true. Do not require at least one pair. A loop that never runs leaves [] — that is success.

Worked examples

empty

s = ""
  1. zero iterations
  2. stack []

Result: valid

one pair

s = "()"
  1. push pop
  2. []

Result: valid

nested

s = "(())"
  1. push push pop pop
  2. []

Result: valid

Try it

Write isValid(s). s is a string of brackets, and may be empty. Return true for empty. Empty is the base success: the loop never runs and the stack stays []. isValid("") is true. "()" and "(())" are also valid.

s is a well-formed string of the same bracket type, and may be empty. Empty is in scope. That is this skill.