Back to articles

Fitting room analogy to explain the balanced parentheses problem

via Reddit Programming/u/guiferviz

When learning programming, one problem that shows up very often is checking if a sequence of parentheses (any type allowed ()[]{} ) is balanced. For example: (())() is valid, but ())( is not. This is easy to solve if we use an analogy. Imagine a fitting room where someone is trying on clothes. every ( , [ or { means putting on a piece of clothing every ) , ] or } means taking one off Three simple rules, that match real life: You can't take off clothes you never put on. You can't take off something if you have something on top of it. By the time you leave the fitting room, you shouldn't still be wearing items you tried on. That's basically the whole idea behind the stack data structure. In the post, I walk through it step by step , with interactive examples , following the same line of thought (not chain of thought ;) I had when I first came across the problem. submitted by /u/guiferviz [link] [comments]

Continue reading on Reddit Programming

Opens in a new tab

Read Full Article
2 views

Related Articles