Kodewick
Start learning →
Matching brackets14 / 52

Matching brackets

Lesson 14 of 52 · Part 3 · Stacks and queues · about 12 minutes

Bracket matching uses a stack: push each opening bracket, check each closing one against the top, and end with an empty stack, so {[()]} passes and ([)] fails; the STL way uses std::stack<char>.

{[()]} matches and ([)] doesn't: the counts are the same, but ) arrives while [ is still open. Compilers, JSON parsers and an editor's bracket highlighting all have to answer this. The rule is: the bracket opened last must be closed first. That's exactly a stack.

The rule: push openers, check closers against the top

Read from left to right:

  1. An opening bracket: push it.
  2. A closing bracket: if the stack is empty, it has no partner: wrong. If the top isn't its partner: wrong. If it is: pop.
  3. At the end: anything left on the stack is a bracket never closed: wrong. An empty stack: right.
stack (bottom on the left)0123

Checking {[()]}: the stack holds the openers not yet closed, and each closer is matched against the top
Choose one

Checking ([]{}): just after reading {, what is in the stack, bottom to top?

Choose allPick all that apply

Which bracket strings are balanced? (You can pick more than one.)

Exercise 1

How deep does it nest?

The string holds only ( and ), and they match. Find the deepest nesting, that is, how many are on the stack at its highest.

It should print
3
exercise1.cpp
1#include <iostream>2#include <string>3using namespace std;4 5int main() {6    string s = "(()(()))()";7    int depth = 0, best = 0;8    // ( adds 1 to depth (keep the largest), ) takes 1 away9    cout << best << "\n";10    return 0;11}
Output
Press Run or Ctrl+Enter

Writing it

First use a char array as the stack, with t the index of the top, just like last lesson's array stack.

main.cpp
1#include <iostream>2#include <string>3using namespace std;4 5// are they a pair?6bool isPair(char open, char close) {7    return (open == '(' && close == ')') ||8           (open == '[' && close == ']') ||9           (open == '{' && close == '}');10}11 12bool match(const string& s) {13    char st[100];14    int t = -1;15    for (char c : s) {16        if (c == '(' || c == '[' || c == '{') {17            st[++t] = c;18        } else if (c == ')' || c == ']' || c == '}') {19            if (t == -1) return false;            // too many closers20            if (!isPair(st[t], c)) return false;  // wrong partner21            t--;22        }23        // anything else is skipped24    }25    return t == -1;                               // too many openers: not empty26}27 28int main() {29    string tests[] = {"{[()]}", "([)]", "(()", "())", "a[i] = f(b[j]);"};30    for (const string& s : tests)31        cout << s << string(18 - s.size(), ' ') << (match(s) ? "ok" : "wrong") << "\n";32    return 0;33}
Output
{[()]}            ok
([)]              wrong
(()               wrong
())               wrong
a[i] = f(b[j]);   ok

Look at the last example: anything that isn't a bracket is skipped, so this function can check a real line of code. const string& passes the string by reference, without copying it.

Fill inTap one to fill a blank; tap a blank to take it back

Fill in the last line so all three cases come out right: the program should print 1 0 0.

1#include <iostream>2#include <string>3using namespace std;4 5bool isPair(char open, char close) {6    return (open == '(' && close == ')') ||7           (open == '[' && close == ']') ||8           (open == '{' && close == '}');9}10 11bool match(const string& s) {12    char st[100];13    int t = -1;14    for (char c : s) {15        if (c == '(' || c == '[' || c == '{') {16            st[++t] = c;17        } else if (c == ')' || c == ']' || c == '}') {18            if (t == -1 || !isPair(st[t], c)) return false;19            t--;20        }21    }22    return ;23}24 25int main() {26    cout << match("{[()]}") << " " << match("(()") << " " << match("())") << "\n";27    return 0;28}
Exercise 2

Write match

Fill in match: true when the brackets match, false otherwise. It has to catch all three kinds of error.

It should print
1 0 0 0
exercise2.cpp
1#include <iostream>2#include <string>3using namespace std;4 5bool isPair(char open, char close) {6    return (open == '(' && close == ')') ||7           (open == '[' && close == ']') ||8           (open == '{' && close == '}');9}10 11bool match(const string& s) {12    char st[100];13    int t = -1;14    for (char c : s) {15        // opener: push; closer: empty stack or no pair means false, a pair means pop16    }17    return false;   // make it: right only if the stack is empty18}19 20int main() {21    cout << match("([]{})") << " " << match("(]") << " " << match("((") << " " << match("))") << "\n";22    return 0;23}
Output
Press Run or Ctrl+Enter

Three ways to go wrong

ExampleWhat's wrongFound when
())Too many closersAt the second ) the stack is already empty
(()Too many openersAfter the end a ( is still on the stack
([)]Wrong partnerAt ) the top is [

stack

Checking ([)]: when ) arrives, the top is [, not its partner

The easiest one to miss is the second: checking only inside the loop and forgetting the final return t == -1 lets (() pass as correct.

Guess the outputA wrong guess is fine

Checking {[(])}, at which character (counting from 0) is the error found?

1#include <iostream>2#include <string>3using namespace std;4 5int main() {6    string s = "{[(])}";7    char st[10];8    int t = -1, at = -1;9    for (int i = 0; i < (int)s.size() && at < 0; i++) {10        char c = s[i];11        if (c == '(' || c == '[' || c == '{') st[++t] = c;12        else if (t == -1 || !((st[t] == '(' && c == ')') || (st[t] == '[' && c == ']') || (st[t] == '{' && c == '}'))) at = i;13        else t--;14    }15    cout << at << "\n";16    return 0;17}
Guess the outputA wrong guess is fine

This match has only one kind of bracket, so the stack only ever holds ( and it just keeps the height t. It forgets the empty check at the end. What does it print?

1#include <iostream>2#include <string>3using namespace std;4 5bool match(const string& s) {6    int t = -1;7    for (char c : s) {8        if (c == '(') {9            t++;10        } else if (c == ')') {11            if (t == -1) return false;12            t--;13        }14    }15    return true;16}17 18int main() {19    cout << match("(()") << " " << match("())") << "\n";20    return 0;21}
Choose one

What kind of error is [[]?

With the STL

With std::stack<char> you no longer care how big the array is or how t moves. Add a common trick: on an opening bracket, push the closing bracket it needs. On a closing bracket just check that it's the same character as the top, and isPair goes away.

main.cpp
1#include <iostream>2#include <stack>3#include <string>4using namespace std;5 6bool match(const string& s) {7    stack<char> st;8    for (char c : s) {9        if (c == '(') st.push(')');10        else if (c == '[') st.push(']');11        else if (c == '{') st.push('}');12        else if (c == ')' || c == ']' || c == '}') {13            if (st.empty() || st.top() != c) return false;14            st.pop();15        }16    }17    return st.empty();18}19 20int main() {21    string tests[] = {"{[()]}", "([)]", "(()", "())"};22    for (const string& s : tests)23        cout << s << " " << (match(s) ? "ok" : "wrong") << "\n";24    return 0;25}
Output
{[()]} ok
([)] wrong
(() wrong
()) wrong

The order in st.empty() || st.top() != c matters: when the left side of || is true the right side isn't evaluated, so top() is never called on an empty stack (that's undefined behaviour).

VersionThe stackPer characterIn total
By handchar st[100] plus the index tO(1)O(n) time, up to O(n) stack space
STLstack<char> (a deque inside)push / top / pop all O(1)O(n) time, O(n) stack space

In interviews: "Valid parentheses" is nearly everyone's first stack problem. A stack<char> or just a string used as a stack (push_back, back, pop_back) both work; don't forget the final return st.empty(), or to check for empty when a closer arrives.

Choose one

In the STL version, the test is written st.top() != c || st.empty() (the two sides swapped). What happens when a ) is checked?

Summary

Take-away

Matching brackets: the last opened is the first closed

  • Opener: push it (or push the closer it needs)
  • Closer: an empty stack or no pair with the top is an error; a pair means pop
  • At the end the stack must be empty
  • Check empty() before top()
1if (c == '(') st.push(')');2else if (c == ')') {3    if (st.empty() || st.top() != c) return false;4    st.pop();5}6return st.empty();