Tutorialspoint
Problem
Solution
Submissions

Valid Parentheses

Certification: Basic Level Accuracy: 33.33% Submissions: 3 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.
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.
Constraints
  • 1 ≤ s.length ≤ 10^4
  • s consists of parentheses only: '()', '[]', '{}'
  • Time Complexity: O(n)
  • Space Complexity: O(n)
StringsStackKPMGApple
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 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

Steps to solve by this approach:

 Step 1: Initialize an empty stack and create a mapping of closing to opening brackets
 Step 2: Iterate through each character in the input string
 Step 3: If character is an opening bracket, push it onto the stack
 Step 4: If character is a closing bracket, check if stack is empty
 Step 5: If stack is not empty, pop the top element and check if it matches the current closing bracket
 Step 6: If it doesn't match or stack is empty when we encounter a closing bracket, return false
 Step 7: After processing all characters, return true if stack is empty, false otherwise

Submitted Code :