20. Valid Parentheses|LEETCODE EASY|

HolySpirit
2 min readDec 4, 2023

--

In this article let’s tackle another leetcode problem, which is based on the concept that we learnt in our last article on introduction to stack. Do read those articles including my articles on linked lists where I solved some of the important leetcode problems which would definitely help you when you are appearing for any coding interview.

Now, let’s see what the question asks us to do,

Here they asked us to find whether the given Parentheses are valid or not i.e. to check whether all the parentheses are closed or not. These are the conditions to be valid Parentheses,

👊 Open brackets must be closed by the same type of brackets.

👊 Open brackets must be closed in the correct order.

👊 Every close bracket has a corresponding open bracket of the same type.

Intuition: since we are dealing with the elements in the particular order i.e. we want them in the reverse order. So use the stack data structures here.

Now we know that we want to use stacks, so we are half done.

Let’s see what to do,

✊ start putting the open bracket into the stack.

✊ If you encounter any closing braces then check whether the last element inserted into the stack is correct opening braces (example for } the correct opening braces is of the same type i.e. } ).

Let’s see how to do,

The below code shows the implementation of the above approach.

class Solution {
public boolean isValid(String s) {
Stack<Character> stack=new Stack<>();
for(char i:s.toCharArray()){
if(i=='{'|| i=='['||i=='('){
stack.push(i);
}
if(i==')'){
if(stack.isEmpty() || stack.pop()!='('){
return false;
}
}
if(i=='}'){
if(stack.isEmpty() || stack.pop()!='{'){
return false;
}
}
if(i==']'){
if(stack.isEmpty() || stack.pop()!='['){
return false;
}
}
}

return stack.isEmpty();
}
}

Use debug pointers and get to know about the flow of statements.

If you find any value in this article, consider following me. Thanks.

#LearnInPublic #happy coding

--

--

HolySpirit

Budding Programmer sharing insights on life 👨‍💻✨ | Passionate about coding, tech trends, and personal growth | Join me on my journey of learning and discovery