AlgoMaster Logo

Valid Parentheses

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Using Stack

Intuition:

The problem of validating parentheses can be efficiently solved using a stack data structure as it is ideal for problems involving matched pairs and nested structures. The idea here is to iterate through the characters of the string and use the stack to keep track of opening parentheses. When we encounter a closing parenthesis, we check if it matches the top of the stack. If it does, we can pop the stack; otherwise, the string is invalid.

Steps:

  1. Initialize a stack to keep track of opening parentheses.
  2. Loop through each character in the string.
  3. If a character is an opening bracket ('(', '{', or '['), push it onto the stack.
  4. If it is a closing bracket, check the stack:
    • If the stack is empty, it means there is no matching opening bracket, thus the string is invalid.
    • If the stack is not empty, pop the top element from the stack and check if it matches the closing bracket. If not, return false.
  5. After processing all characters, if the stack is empty, it means all opening brackets had matching closing brackets, so the string is valid. Otherwise, return false.

Code: