Tutorialspoint
Problem
Solution
Submissions

Valid Parentheses

Certification: Advanced Level Accuracy: 37.5% Submissions: 8 Points: 8

Write a C# function to determine if a given string contains valid parentheses. An input string is 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.

Example 1
  • Input: s = "()"
  • Output: true
  • Explanation:
    • The string contains one pair of parentheses that open and close correctly.
Example 2
  • Input: s = "([)]"
  • Output: false
  • Explanation:
    • The brackets are not closed in the correct order (closing ) before closing ]).
Constraints
  • 1 ≤ s.length ≤ 10^4
  • s consists of only '(', ')', '{', '}', '[', and ']'
  • Time Complexity: O(n)
  • Space Complexity: O(n)
StringsStackCapgeminiDropbox
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 track opening brackets
  • When encountering a closing bracket, check if it matches the most recent opening bracket
  • The string is valid if all brackets are matched and closed in the correct order
  • If the stack is empty at the end and all characters have been processed, the string is valid

Steps to solve by this approach:

 Step 1: Create a stack to store opening brackets.
 Step 2: Iterate through each character in the string.
 Step 3: If the character is an opening bracket ('(', '[', '{'), push it onto the stack.
 Step 4: If the character is a closing bracket (')', ']', '}'), check if the stack is empty. If it is, return false.
 Step 5: If the stack is not empty, pop the top element and check if it matches the current closing bracket.
 Step 6: If the brackets don't match, return false.
 Step 7: After processing all characters, return true if the stack is empty (all brackets were matched).

Submitted Code :