Balancing Parentheses in a String - Clarification

From working through some problems I’m given in a game plan put together by my advisors, one of the problems I wasn’t able to even code a brute force solution in my first try is “Balancing Parentheses in a String.” I looked through the solutions, but there’s one thing that isn’t quite clear.

Why are we iterating through the string instead of representing it as a tree of nested parentheses?

When I approached the problem, I paid attention to nesting of the parentheses, to which I would need to represent the string as a hierarchy of nested parentheses. I do get the idea on using a stack or a counter, but I don’t quite understand why it’s not necessary to parse out the string as a hierarchy.

I hope I understand correctly. I also just completed the question, I think when you are creating hierarchy, It is a time and space consuming and also will be challenging to know which parenthesis to keep or not whereas, with a stack, it is easily doable.

1 Like