
Problem
Solution
Submissions
Valid Parentheses
Certification: Basic Level
Accuracy: 20%
Submissions: 5
Points: 5
Write a JavaScript function to determine if the input string has valid parentheses. An input string is valid if open brackets are closed by the same type of brackets and in the correct order. The brackets include '()', '[]', and '{}'.
Example 1
- Input: s = "()"
- Output: true
- Explanation:
- We have one opening parenthesis '(' and one closing parenthesis ')'.
- The opening bracket is properly matched with its corresponding closing bracket.
- The brackets are in the correct order.
- Therefore, the string is valid.
- We have one opening parenthesis '(' and one closing parenthesis ')'.
Example 2
- Input: s = "([)]"
- Output: false
- Explanation:
- We have mixed types of brackets: '(', '[', ')', ']'.
- The opening parenthesis '(' is closed by ']' instead of ')'.
- The brackets are not properly matched.
- Therefore, the string is invalid.
- We have mixed types of brackets: '(', '[', ')', ']'.
Constraints
- 1 ≤ s.length ≤ 10^4
- s consists of parentheses only: '()', '[]', '{}'
- Time Complexity: O(n)
- Space Complexity: O(n)
Editorial
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. |
Solution Hints
- Use a stack data structure to keep track of opening brackets
- Iterate through each character in the string
- If the character is an opening bracket, push it onto the stack
- If the character is a closing bracket, check if it matches the top of the stack
- If it matches, pop the stack; if not, the string is invalid
- After processing all characters, the stack should be empty for a valid string