DEV Community

Kaushal
Kaushal

Posted on

Valid Parantheses

I recently was looking at this question and I don't know about all but I definitely was not aware of real-world use case of this DSA and Algorigthm question. I didn't just learned more about Stack Data Structure but I learned how and where in the real world this is being used.

A number of places:

  1. Browser navigation button it uses a Stack
  2. Normal copy and paste mechanism on computers uses Stack to add changes in one stack and remove from the other one and vice versa
  3. JS Call stack ofcourse how can that be missed
  4. Code editor's syntax highlighting and fixing

The most fascinating thing for me was the Code Editor's syntax validation because the "Valid Parantheses" leetcode problem was a pain in the beginning for me but now I visualize it in my mind easily because I work with code every day I look at the brackets everyday so now it all makes sense how that problem will be solved if ever I am asked that question.

The simplest reference I keep to myself for that question is that it does not matter how long the string would be you will first check if the current item that you are on is a key in the hashmap/js-object and if so you will check the last added item if its saved as value in the object for that same key that means its a match, it's an open and close bracket and we will not push the current item to the stack or array and we will also pop that matched item from the stack/array since it will always be on the last index we will use pop method

const bracketMap = {
            "}":"{",
            "]":"[",
            ")":"("
        }
Enter fullscreen mode Exit fullscreen mode

but let's say the current item is in the object but it did not have a match with last pushed item so that is return false immediately and break the loop. And the final part if the current item is not in the object as key that means we have an open bracket item that means we will do a push to the stack/array and we will keep doing it in the loop.

In the end we will just retun stack.length === 0 that is the requirement of the "Valid Parantheses" question only.

Stack has many more features to it and various usecases as well. I will definitely share what I understood and how I linked some of the code problems with real world things we interact with

Top comments (0)