easystackstringpattern: two-pointer

Valid Parentheses

Given a string containing only (){}[], determine whether every opener has its matching closer, correctly nested.

Problem

Statement

A valid bracket string satisfies: every opener has a matching closer of the same kind, and openers close in reverse order of appearance ((()) is valid; ([)] is not).

The canonical solution is a stack: push openers, on a closer pop and compare. If the stack ends non-empty or a pop mismatches, the string is invalid.

Prints true or false.

Worked cases

Examples

Input
()
Output
true
Input
()[]{}
Output
true
Input
(]
Output
false
Input
([)]
Output
false
NoteInner ] closes before its ( pair.
Bounds

Constraints

  • 0 ≤ input length ≤ 10^4
  • Input contains only the characters ()[]{}
Reference

Sample solutions

Runnable starter code. Click "Try in playground" to open pre-loaded with the test fixtures.

Python
pairs = {')': '(', ']': '[', '}': '{'}
s = input()
stack = []
for c in s:
    if c in '([{':
        stack.append(c)
    else:
        if not stack or stack.pop() != pairs[c]:
            print('false'); exit()
print('true' if not stack else 'false')
Java
import java.util.*;

public class Solution {
    public static void main(String[] args) {
        String s = new Scanner(System.in).hasNextLine() ? new Scanner(System.in).nextLine() : "";
        Deque<Character> st = new ArrayDeque<>();
        Map<Character, Character> pairs = Map.of(')','(',']','[','}','{');
        for (char c : s.toCharArray()) {
            if (c == '(' || c == '[' || c == '{') st.push(c);
            else if (st.isEmpty() || st.pop() != pairs.get(c)) { System.out.println("false"); return; }
        }
        System.out.println(st.isEmpty() ? "true" : "false");
    }
}
C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    string s; getline(cin, s);
    stack<char> st;
    for (char c : s) {
        if (c == '(' || c == '[' || c == '{') st.push(c);
        else {
            if (st.empty()) { cout << "false\n"; return 0; }
            char t = st.top(); st.pop();
            if ((c == ')' && t != '(') || (c == ']' && t != '[') || (c == '}' && t != '{')) { cout << "false\n"; return 0; }
        }
    }
    cout << (st.empty() ? "true" : "false") << "\n";
}
Pattern

Practice this pattern

These problems solve on the same intuition — try one next while the pattern is fresh.

Also try