Valid Parentheses

Try to solve the Valid Parentheses problem.

Statement#

Given a string that may consist of opening and closing parentheses, your task is to check whether or not the string contains valid parenthesization.

The conditions to validate are as follows:

  1. Every opening parenthesis should be closed by the same kind of parenthesis. Therefore, {)and [(]) strings are invalid.

  2. Every opening parenthesis must be closed in the correct order. Therefore, )( and ()(() are invalid.

Constraints:

  • 11 \leq s.length 103\leq 10^3
  • The string will only contain the following characters: (, ), [, ], { and }.

Examples#

Created with Fabric.js 3.6.6 (){[{()}]} Sample example 1 TRUE

1 of 4

Created with Fabric.js 3.6.6 ))){{}}}]] Sample example 2 FALSE

2 of 4

Created with Fabric.js 3.6.6 ))))) Sample example 3 FALSE

3 of 4

Created with Fabric.js 3.6.6 () Sample example 4 TRUE

4 of 4

Understand the problem#

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Valid Parentheses

1

Are the parentheses in the following string valid or not?

(){}[]

A)

Not valid

B)

Valid

Question 1 of 20 attempted

Figure it out!#

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Note: As an additional challenge, we have intentionally hidden the solution to this puzzle.

Drag and drop the cards to rearrange them in the correct sequence.

Start traversing the input string. If the current parenthesis is an opening parenthesis, push it onto the stack.

If the current parenthesis is a closing parenthesis and it corresponds to the opening parenthesis on the top of the stack, then pop it from the stack.

After complete traversal, if the stack is empty, then the parentheses are valid. Otherwise they are not.


Try it yourself#

Implement your solution in the following coding playground.

We have left the solution to this challenge as an exercise for you. The optimal solution to this problem runs in O(n) time and takes O(n) space. You may try to translate the logic of the solved puzzle into a coded solution.

Python
usercode > main.py
Input #1
Valid Parentheses

Solution: Implement Queue Using Stacks

Solution: Valid Parentheses