Implement the validParenthesesMixed method that checks whether mixed parentheses are correctly balanced.

The input contains a string text made of brackets such as (), [], and {}. Your task is to check whether the bracket sequence is valid.

A valid sequence means every opening bracket is closed by the same type of bracket, and brackets must close in the correct order.

For example, ()[]{} is valid, but (] is invalid because the opening and closing bracket types do not match.

Example 1

Input
text (string) = ()[]{}
Returns (boolean) true

Example 2

Input
text (string) = ()
Returns (boolean) true

Example 3

Input
text (string) = (]
Returns (boolean) false

Use a stack to remember opening brackets that have not been closed yet.

When an opening bracket appears, push it onto the stack. When a closing bracket appears, it must match the most recent opening bracket, which is stored at the top of the stack.

If a mismatch is found or a closing bracket appears when the stack is empty, return false. At the end, the stack must be empty for the string to be valid.

Pseudocode:

function validParenthesesMixed(text):
    create empty stack
    for each character ch in text:
        if ch is opening bracket:
            push ch into stack
        else if ch is closing bracket:
            if stack is empty:
                return false
            top = pop from stack
            if top does not match ch:
                return false
    return stack is empty
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.