20. Valid Parentheses

Solving the "Valid Parentheses" Problem with Stack 

The Valid Parentheses problem is a common question that comes up in coding interviews. The task is to determine whether a given string containing only parentheses—round (), square [], and curly {} brackets—is valid. A string is valid if:

  • Every opening bracket has a corresponding closing bracket of the same type.
  • Brackets are closed in the correct order (i.e., an opening bracket must be closed before another of a different type is opened).

Example

  1. Input: "{[()]}"
    Output: true
    This is valid since each opening bracket is closed properly in the right order.

  2. Input: "{[(])}"
    Output: false
    This is invalid because the brackets are mismatched.

Approach: Using a Stack

A stack is a perfect data structure for solving this problem because it follows a Last In, First Out (LIFO) principle. When we encounter an opening bracket, we push it onto the stack. When we encounter a closing bracket, we check if it matches the most recent (top) opening bracket. If it does, we pop the top element off the stack. Otherwise, the string is invalid.

At the end of this process, if the stack is empty, it means all the opening brackets were matched properly, and the string is valid. If the stack still contains elements, it means there are unmatched opening brackets, and the string is invalid.

Time and Space Complexity

  • Time Complexity: O(n), where n is the length of the string. We traverse the string once, and all stack operations (push and pop) take constant time.
  • Space Complexity: O(n), where n is the length of the string. In the worst case, all characters in the string are opening brackets, so the stack will hold n characters.

Code Implementation:

class Solution {
    public boolean isValid(String s) {
        Stack<Character> charStack = new Stack<>();
        for(char ch : s.toCharArray()) {
            if (ch == '(' || ch == '{' || ch == '[') {
            charStack.push(ch);
            }else {
                if(charStack.size() == 0) {
                    return false;
                }
                char top = charStack.peek();
                switch (ch) {
                    case ')' :
                        if (top == '(') {
                            charStack.pop();
                        } else {
                            return false;
                        }
                        break;
                    case '}' :
                        if (top == '{') {
                            charStack.pop();
                        } else {
                            return false;
                        }
                        break;
                    case ']' :
                        if (top == '[') {
                            charStack.pop();
                        } else {
                         return false;
                        }
                        break;
                }
            }
        }
    if(charStack.size() > 0){
        return false;
    }
    return true;
    }
}

Comments

Popular posts from this blog

3Sum Closest: O(n²) Two-Pointer Magic 🚀 leetcode: 16

Kadane's Algorithm: Maximum Subarray Problem - LeetCode(53) Solution

LeetCode Problem: Implement pow(x, n) leetcode:- 50