Tutorialspoint
Problem
Solution
Submissions

Valid Parentheses

Certification: Basic Level Accuracy: 50% Submissions: 2 Points: 5

Write a C program to determine if a given string containing just the characters '(', ')', '{', '}', '[' and ']' has valid parentheses arrangement. The string is valid if open brackets must be closed by the same type of brackets, open brackets must be closed in the correct order, and every close bracket has a corresponding open bracket of the same type.

Example 1
  • Input: s = "()"
  • Output: true
  • Explanation: The opening parenthesis '(' is correctly matched with the closing parenthesis ')', making the string valid.
Example 2
  • Input: s = "()[]{}"
  • Output: true
  • Explanation: The string contains three pairs of brackets: '()', '[]', and '{}'. Each pair is properly matched.
Example 3
  • Input: s = "(]"
  • Output: false
  • Explanation: The opening bracket '(' is matched with a closing bracket ']' of a different type, making the string invalid.
Constraints
  • 1 ≤ s.length ≤ 10^4
  • s consists of parentheses only: '()[]{}'
  • Time Complexity: O(n), where n is the length of the string
  • Space Complexity: O(n) in the worst case
StringsWalmartTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a stack data structure to keep track of opening brackets
  • Iterate through each character in the string
  • If the current character is an opening bracket, push it onto the stack
  • If the current character is a closing bracket, check if the stack is empty or if the top element doesn't match
  • After processing all characters, check if the stack is empty to ensure all brackets were matched
  • If the string length is odd, it cannot have valid parentheses (they must come in pairs)

Steps to solve by this approach:

 Step 1: Check if the string length is odd. If it is, return false immediately.

 Step 2: Create a stack to track opening brackets.
 Step 3: Iterate through each character in the string.
 Step 4: If the character is an opening bracket ('(', '{', or '['), push it onto the stack.
 Step 5: If the character is a closing bracket, check if the stack is empty. If it is, return false.
 Step 6: If the stack is not empty, check if the top element matches the current closing bracket. If not, return false.
 Step 7: After processing all characters, check if the stack is empty. If empty, return true; otherwise, return false.

Submitted Code :