LeetCode 20 Valid Parentheses - Example and Complexity Analysis

Walkthrough and analysis

Trace "{[()]}".

Read {: push. Stack: [{].

Read [: push. Stack: [{, [].

Read (: push. Stack: [{, [, (].

Read ): top is (, matches. Pop. Stack: [{, [].

Read ]: top is [, matches. Pop. Stack: [{].

Read }: top is {, matches. Pop. Stack: [].

Stack empty at end. Return true.

For "([)]": after ([, when you see ), top is [ which doesn't match. Return false.

Single pass through the string. O(n)O(n) time. Stack holds at most nn characters. O(n)O(n) space.