Leetcode 20: Valid Parentheses

grid47
grid47
Exploring patterns and algorithms
Nov 5, 2024 6 min read

An elegant loop of parentheses, glowing and connected in a balanced, harmonious way.
Solution to LeetCode 20: Valid Parentheses Problem

You are given a string containing characters representing various types of brackets: ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’. Your task is to determine if the input string is valid. A string is considered valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
  3. Every close bracket has a corresponding open bracket of the same type.
Problem
Approach
Steps
Complexity
Input: The input consists of a string s containing only the characters '(', ')', '{', '}', '[' and ']'.
Example: s = '({[]})'
Constraints:
• 1 <= s.length <= 10^4
• s consists of parentheses only '()[]{}'.
Output: The output is a boolean value: true if the string is valid, otherwise false.
Example: true
Constraints:
• The result should be a boolean indicating whether the input string is valid.
Goal: To check whether the string contains valid parentheses by ensuring each open bracket has a corresponding and correctly ordered closing bracket.
Steps:
• Initialize an empty stack to keep track of open brackets.
• Iterate through each character in the string.
• If the character is an open bracket ('(', '{', or '['), push it onto the stack.
• If the character is a closing bracket (')', '}', or ']'), check if the stack is not empty and if the top of the stack matches the corresponding open bracket.
• If there's a match, pop the stack, else return false.
• After iterating through the string, if the stack is empty, return true (valid). Otherwise, return false (invalid).
Goal: Conditions that the input string will always meet.
Steps:
• The input string will only contain characters from '(', ')', '{', '}', '[' and '].
Assumptions:
• The input string is always non-empty.
• The input string contains only valid characters.
Input: s = '({[]})'
Explanation: This string contains balanced brackets: each opening bracket has a corresponding closing bracket in the correct order. Thus, the output is true.

Input: s = '({[})'
Explanation: This string contains mismatched brackets. The order is incorrect, and the closing bracket doesn't match the last opening bracket, so the output is false.

Input: s = '([])'
Explanation: This string contains balanced brackets: each opening bracket has a corresponding closing bracket in the correct order. Thus, the output is true.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus